Web.config in ASP.NET 2.0
By AzamSharp
Views: 15866

Introduction:

Configuration files are just great they let you configure the website (pretty obvious huh). It's a great place to store the information which you are going to be using throughout the application and which is not changing. In this article I will show you that how you can extract the information from the configuration file using API's provided by the .NET Framework 2.0. I will also show you that how easily you can encrypt the sections of the configuration files.


Extracting Information from the Configuration Files Programmatically:

Let's first see how we can extract the information from the tags that are defined in the configuration files. Let's say our configuration files contains the <appSettings> section which looks something like this:

<appSettings>

<add key="SQLProvider" value="AzamSharp.Data.SqlClient" />

<add key="SQLConnection" value="System.Data.SqlClient.SqlConnection" />

<add key="OracleProvider" value="System.Data.OracleClient" />

</appSettings>

Now, if you want to get all the keys you can easily use the AllKeys property of the AppSettingsSection. Take a look at the code below:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

AppSettingsSection appSettings = (AppSettingsSection) config.GetSection("appSettings");

string[] appKeys = appSettings.Settings.AllKeys;

for (int i = 0; i < appSettings.Settings.Count; i++)

{

Response.Write(appSettings.Settings[appKeys[i]].Value);

Response.Write("<BR>");

}

The above code will simply print out the value of all the keys in the AppSettings section of the configuration file.

If you want to extract just a single value based on its key name then you can simply use the following code:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");

string msSqlProvider = appSettings.Settings["SQLProvider"].Value;

Pretty simple right!

I am using the above example with the appSettings section of the configuration file but you can use it with most of the other sections of the web.configuration file.

Extracting ConnectionString Dynamically:

Let's try the same thing with the connection strings stored in web.config file. Check out the connection string settings below:

<appSettings>

<add key="SQLProvider" value="AzamSharp.Data.SqlClient" />

<add key="SQLConnection" value="System.Data.SqlClient.SqlConnection" />

<add key="OracleProvider" value="System.Data.OracleClient" />

</appSettings>

I can easily extract all of the connection strings using the following code:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

 

ConnectionStringsSection conSection = (ConnectionStringsSection)config.GetSection("connectionStrings");

ConnectionStringSettingsCollection conCollection = conSection.ConnectionStrings;

foreach (ConnectionStringSettings conSetting in conCollection)

{

Response.Write(conSetting.ConnectionString);

Response.Write("<BR>");

}

You can also extract a single connection using the conSection object which is of ConnectionStringSection type.

Writing Connection String Dynamically:

You can also write the connection string back to the Web.config dynamically. In ASP.NET 1.X this was done using the XmlDocument class and iterating through the XML tags of Web.config (Writing to Web.config file dynamically). In ASP.NET 2.0 this is much easier take a look at the code below where I dynamically change the value of the connection string.

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

 

ConnectionStringsSection conSection = (ConnectionStringsSection)config.GetSection("connectionStrings");

conSection.ConnectionStrings["SQLConnectionString"].ConnectionString = "NewConnectionString";

config.Save();

 

Please note that when you write to a web.config file the application restarts which means all the session and application variables are lost.


Encrypting Config Sections:

In ASP.NET 2.0 you can also easily encrypt the config sections dynamically. Let's see how we can encrypt the connection strings section.

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

ConfigurationSection configSection = config.GetSection("connectionStrings");

if (configSection.SectionInformation.IsProtected)

{

configSection.SectionInformation.UnprotectSection();

config.Save();

}

else

{

configSection.SectionInformation.ProtectSection

("DataProtectionConfigurationProvider");

config.Save();

}

First we check that if the section is already encrypted if it is then we decrypt it else we encrypt it. Take a look at the resulting connection string section in web.config.

<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAVClqG40BZkCjK40

adynN8gQAAAACAAAAAAADZgAAqAAAABAAAABIhtOWxFnMKjMa8/cR5tYzAAA

AAASAAACgAAAAEAAAAPfywOeewrUxUGUKp+WpCPE</CipherData>
</EncryptedData>
</connectionStrings>

I hope you liked this article, happy coding!

If you are one of the thousands that visit GridViewGuy for your .NET articles and resources, you might be interested in making a donation. Extra cash helps pay for the hosting services and speed things up around here, and makes this website possible.

Make a Donation

Once, again thank you very much and remember its because of you FINE people that this website is up and running.

 

Export Button is a custom control that let's you export your DataGrid or TextBox data to several different formats. The control is extremely easy to use and also exposes design time features. In this article I will discuss some of the features of the Export Button and how it benefits the developer.

BUY IT NOW

 

 

By AzamSharp




Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Good Article
Name: Mr. Crazy
Date: 3/6/2007 4:43:08 PM
Comment:
The article is very helpful for me
Subject: RE: Good
Name: AzamSharp
Date: 3/12/2007 8:50:11 PM
Comment:
I am glad that you liked it!
Subject: ConnectionString dynamically
Name: Kamal Ashraf
Date: 6/15/2007 12:52:53 PM
Comment:
I am using .net 2.0 and in that I am using DataSet to build the data layer. The datasets are placed in a separate project.

In my webpage after setting up proper references I was able to get the data from my data layer from the project I mentioned above but here is the issue;

I have two connection strings and I need to switch my connection string based on a logic. I have build the logic already but I don't know how to switch the connection string. I actually don't specify any connection string in my the webpage. The connection string is being picked up by the dataset layer itself.

Both the connection strings are in my web.config file and also in the app.config file of the dataset layer.

Can you please help brother?
Subject: Good piece
Name: Sharmin
Date: 7/2/2007 11:53:26 AM
Comment:
Article is very useful
Subject: Feedback
Name: awadhesh k kushwaha
Date: 8/28/2007 10:09:16 PM
Comment:
I have realy some problems regarding the connection string in web config file. after reading solution at ur site . my problems was realy solved. thanking you a lot.
Subject: ConnectionStrings
Name: Nosper
Date: 9/6/2007 7:26:55 AM
Comment:
Hi, I've read your article and enjoy it, but in my project, I modify the connectionStrings and the application don't restart and don't use the modification I've made. When I look at my web.config file, it changed to the modification I've made. Could you help me with that??

Thanks
Subject: RE: ConnectionStrings
Name: AzamSharp
Date: 9/9/2007 9:22:13 AM
Comment:
Hi Nosper,

When you change the Web.config file your application will be restarted and the Session, Application values are lost.

Let me know exactly what you are trying to accomplish.
Subject: RE: ConnectionStrings
Name: Nosper
Date: 9/10/2007 4:44:11 AM
Comment:
Hi,

I have a web application that runs un a primary server and on a backup server for redundency. I don't want to have a different web.config on each server.

So I decided to modify the connectionStrings of the web.config on the Application_Start() function on the file Global.asax. I look at the server name on witch the web application is currently running and if the connectionStrings doesn't correspond I change it.

I have no problem to change it, I saved the file an as this article says, "Please note that when you write to a web.config file the application restarts which means all the session and application variables are lost.", it is supposed to restart. If I look at the web.config file without quiting the browser, the file has been modified. But my web application still run with the old web.config. At the next start it will take my new web.config file with the modification.

Presently, When I modify the web.config, my application crash because it doesn't find the database. I open it again and it works...

Isn't it suppose to restart my web application, using my web.config modified? Is there an option in visual studio that stop it??

Thanks for your help!
Subject: Thanks
Name: Frederick
Date: 9/10/2007 5:53:57 AM
Comment:
Thanks a lot!
You really helped my!

Bye

Frederick
Subject: Encription & Decrption
Name: Manish Sinha
Date: 2/14/2008 4:39:13 AM
Comment:
Very Well.
but i want know abt why we use encription and decription in ConnectionString.plz rply me.
Subject: RE: Encription & Decrption
Name: AzamSharp
Date: 2/15/2008 7:30:34 AM
Comment:
Hi Manish Sinha, The above article explains the encryption and decryption process.
Subject: writing in web.config
Name: abdul kadar
Date: 6/4/2008 5:41:47 AM
Comment:
I already stored a connection string in web.config.how to change the connection string dynamically ( if database user id ,server name,password are changed)
Subject: Trust Level
Name: elmar
Date: 6/5/2008 5:41:23 PM
Comment:
How to make it working under Medium Trust level?
WebConfigurationManager.OpenWebConfiguration gives me an error: System.Security.Permissions.FileIOPermission
Thanks
Subject: re: Trust Level
Name: AzamSharp
Date: 6/8/2008 8:21:41 AM
Comment:
Hi Elmar,

Please check that if you have write permissions on the web.config file.


Win a free book
You can win yourself ASP.NET AJAX in ACTION
Read details







Join WebHost4Life.com







Copyright GridViewGuy 2007-2008