Is it possible to change an ASP.NET Web.Config value at runtime without reloading the application domain? - asp.net

Is it possible to change a database connection string value in the Web.Config at runtime without reloading the application domain? The reason for doing this is that:
I am building a multi-tenanted application which uses the one code instance and multiple databases instances approach, so the database connection string in the web.config must be able to be changed at runtime for different tenant users.
ADO.NET always injecst the database connection string in the web.config when you are using entity framework/LINQ to SQL etc, dataset etc.
So I may have to do something weird like this. Hope it is clear enough. Thanks a lot!

Yes it is possible.
try this
System.Configuration.Configuration conf = WebConfigurationManager.OpenWebConfiguration(Server.MapPath);
conf.ConnectionStrings.ConnectionStrings["comp1"].ConnectionString = _connection_comp1;
conf.ConnectionStrings.ConnectionStrings["comp2"].ConnectionString = _connection_comp2;
conf.AppSettings.Settings["CompanyCode"].Value = _company_code;
conf.Save();

Use configuration sections.
http://www.kodyaz.com/articles/add-connection-string-to-web-configuration-file.aspx

Related

Can I use ServerManager from Microsoft.Web.Administration without admin user as an application pool identity

I want to read some settings of the application pool using the ServerManager object from the Microsoft.Web.Administration.dll. The problem is that it works only if the identity of the application pool is a windows user with administrator privileges. Otherwise I am getting UnauthorizedAccessException - Filename: redirection.config; Error: Cannot read configuration file due to insufficient permissions.
Is there any workaround about this issue.
My code is the following:
ServerManager manager = new ServerManager();
string currentSiteName = System.Web.Hosting.HostingEnvironment.SiteName;
Site currentSite = manager.Sites[currentSiteName];
string appVirtaulPath = HttpRuntime.AppDomainAppVirtualPath;
string appPoolName = string.Empty;
foreach (Application app in currentSite.Applications)
{
string appPath = app.Path;
if (appPath == appVirtaulPath)
{
appPoolName = app.ApplicationPoolName;
}
}
ApplicationPool currentAppPool = manager.ApplicationPools[appPoolName];
Thanks!
No, there is no workaround to read the configuration file without causing a big security concern. What are you trying to accomplish?
If reading configuration settings, you can use an API in the same DLL that will give you read-only configuration access for that site settings, such as reading web.config or values in applicationHost.config for that site only, and not encrypted ones (such as passwords). The API is called WebConfigurationManager and has a static method called GetSection, such as WebConfigurationManager.GetSection("system.webServer/defaultDocument")
See: https://msdn.microsoft.com/en-us/library/microsoft.web.administration.webconfigurationmanager.getsection.aspx
However, several settings (namely all the ones used to start the process w3wp.exe) are not possible to be read through that API.
Short story: Unfortunately for security reasons many of those settings are not possible to be read from a worker process. There are some things you can read using server variables such as Request.ServerVariables["APP_POOL_ID"]), or Request.ServerVariables["APP_POOL_CONFIG"]). Of course bitness you could calculate the size of a pointer (4 or 8), or use environment variables (like PROCESSOR_ARCHITECTURE)
Longer story: In IIS for security reasons we take the applicationHost.config file and we split it into smaller application pool.config files (by default located at C:\inetpub\temp\appPools) which are isolated for security reasons so that even if untrusted code were to run in the process (w3wp.exe) to try to steal/read the settings of other sites it would be physically impossible. You can open the file and see which settings are there and you can read those. You'll notice the appPools section is missing entirely since that is only used by WAS to start w3wp.exe.

How to construct ConnectionStrings

Could you explain me how to construct correct ConnectionStrings? I mean that one you can find in web.config file in MVC project. I understand that if you want to add a new connection string you have to write <add ... /> XML tag with parameters such as name, connectionString (it is the most interesting parameter for me) and providerName (perhaps some else?). What each parameter does and means? How to construct connectionString parameter? Where is the db engine indicated?
The questions above are only examples. I care about collecting the most amount of information about constructing ConnectionStrings.
Starting from NET 2.0 you have at your disposal a class named SqlConnectionStringBuilder
Its purpose is to help building dynamically the connection string. But the various properties available explain in great detail the functionality underlying to each possible setting
The SqlConnectionStringBuilder class is derived by a base class named DbConnectionStringBuilder and this allows all the ADO.NET provider to implement their own version of this class. In the link provided there are the references relative to other ADO.NET providers
If you are trying to construct entity framework connection string just use as follows.It will help you..
string connectionString = new System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Sample.csdl|res://*/Sample.ssdl|res://*/Sample.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;
UPDATED:
The easiest way to get the connection string is using the Server explorer window in Visual Studio (View-->Server Explorer menu) and connect to the server from that window. Then you can see the connection string in the properties of the connected server (F4 with your connection selected).
If you create the database in SQL Server Management Studio, that database will be created in a server instance, so that, to deploy your application you'll have to make a backup of the database and deploy it in the deployment SQL Server. Alternatively, you can use a data file using SQL Server Express (localDB in SQL Server 2012), that will be easily distributed with your app.
I.e. if it's an ASP.NET app, there's an App_Datafolder. If you right click it you can add a new element, which can be a SQL Server Database. This file will be on that folder, will work with SQL Express, and will be easy to deploy. You need SQL Express installed on your machine.

Need to set multiple DSN when connecting DB

It's a DB connecting asp code.
Dim db
Set db = Server.CreateObject("ADODB.Connection")
db.Open ("dsn=book;uid=bookmgr;pwd=bookmgr;")
And need to connect to two DSN..(two different DataBase)
but dsn=book,book_adm; is wrong and
dsn=book;dsn=book_adm; takes effect only the last one.
Creating another Server object variable requires editing lots of asp files..
So I want to avoid that way.. It all started when older database is divided into two..
I googled it.. but found nothing useful..
Please help me out this problem. Thanks.
You can't access multiple DSNs from a single connection.
If both dsns point to different catalogs (databases) on the same server, you can use the single connection to access both catalogs by including the catalog name in your sql code in the asp files. Otherwise you will need to change the asp code to use 2 connections.

ASP to database connection

I am new to ASP. I have two databases production and developer databases.
I need to check developer site is going to developer database or not. Both databases have same data and same table names.
But i must work on developer database only how can I?
Generally you'd have an environment configuration file. If you're talking about ASP.NET then it would be the Web.config file. If you're indeed talking about classic ASP then it would probably be an included script with some constants.
If the databases are structurally identical (which they should be) then all you should need to change is the connection string. For classic ASP, you'd probably just store it in a variable:
Dim connString = "This is your connection string"
On the production server, the connection string would be set to your production database. On development machines, it would be set to a development database. (And so on for a test environment, etc.) All of the data access code would just use this connection string variable.
Even more to the point, this should not be the only thing that prevents a developer from using the production database. The DBA should set the permissions such that only the production application has only the access it needs to that database and others do not. Developers should never be able to accidentally modify the production database. So even if you did use the production connection string from your workstation, the database should simply deny you access.
Have two connection strings. Then create a constant variable which will act as your switch and pick the correct connection string:
Dim strCon
CONST DEVELOPMENT = true
if(DEVELOPMENT = true) then
strCon = "Development connection string"
else
strCon = "Live connection string"
end if
adoCon.open strCon
Then you can simply change the switch to true/false depending on which database to pick.
When you specify the database connection you know where you are pointing, so this should be straightforward. But it might be a good idea to use separate logins on dev and production.
So the answer is that you should use the connectionstrings in the config files to get what you need: the "database =.." setting should be set correctly and your problem is aolvedsolved To get extra certainty use different logins, which is recommendable in any case.
you can also use server tracing to monitor activity, but it is not easy on a multi user database and is only a diagnostics tool, not a cure.

I don't know how to connect between the site and my database

I'm using SQL server and web developer(C#).
I know I should do something with my connection string, but I don't exactly what and where I should do that.
Can you write me code example
or explain me what to do?
Edit:
I should connect my database with the site(the site is on the internet).
how would i know the right path for this database?
I should put his address, IP or what?
first you have to know that you cannot just add the database to the server like this !!!
you have to script the whole database, and then you have to upload it into your database server like godaddy.com or what ever . your hosting server should support you with these setails ,they gonna give you a user name and password and other details so you can access to the sql manger ( like my ltitladmin) online ....there you have to upload or just copy and execute your code directly so you can make all your tables and stored procedures or what ever ....
after all this all what you have to is just take the online database new connection string and then add it o your web.confg or in you pages ,this is the way how to make it work right.
It depends on your ASP.NET application.
Basically, connection strings could be stored anywere.
One of suggested connection strings' store is Web.config file. Look for "connectionStrings" configuration element and you should find there the one to change for your production server.
Look at this page:
http://www.connectionstrings.com/
You'll find SQL Server connection string examples.
there is a lot os ways to do that, try to take a look to this simple example:
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson02.aspx
I guess you need to read about it a little:
http://msdn.microsoft.com/en-us/library/ff648340.aspx

Resources