Introduction
The web.config file concept is one, which made the asp.net application really on top in web developement technologies.Actually the coding styles in the asp.net program is that, like a teacher who preparing his student, feelings of a programmer who starts with asp.net.
At the bigining we were hardcoded the keywords(a common example is connection string) inside our code lines. Gradually we looked for a common place, and atlast dotnet brought that as web.config file.
Here I'm adding a small section (but really have big use in our application) of web.config management.
The article which give inspiration to write this was http://www.developerfusion.co.uk/show/6682/
To manipulate Web.Config contents in programatically we had to consider Web.Config file as a normal file or an xml file. .NET 2.0 provides many useful operations to be carried out on Web.Config file; like editing and encrypting sections of Web.Config file. This articles illustrates these functionalities .
Namespaces
The classes and methods to take control of the Web.Config are in 2 namespaces.
System.ConfigurationSystem.Web.Configuration
Each section in the Web.Config file has a corresponding class in either of the namespace. These classes allow modification of corresponding sections. The classes for sections within the "system.web" section are found in System.Web.Configuration. Classes for other sections that are not specific to Web.Config are found in System.Configuration.
Web.Config modification from the code
- Open Web.Config for editing using
WebConfigurationManagerclass. - Using respective
Configurationclass, bring about the necessary changes. - Save changes to the physical file using
Configurationclass.
private void UpdateConfig(string strKey, string strValue)
{
Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
if (objAppsettings != null)
{
objAppsettings.Settings[strKey].Value = strValue;
objConfig.Save();
}
}
In the above piece of code, OpenWebConfiguration() method of WebConfigurationManager class opens Web.Config file in the root directory and returns it as a Configuration object. GetSection() method of Configuration class accepts path to a specific section as argument. The path is the relative path from the root node "configuration". You can refer to deeper nodes(sections in our context) by their names separated by '/'. For example, to get access to the "authentication" section, provide "system.web/authentication" as the parameter to GetSection() method. It returns a generic ConfigurationSecton object, which can be typecasted to proper configuration section class. In our example we get hold of the "appSettings" section with the help of AppSettingsSection class. AppSettingsSection class instance has a Settings collection property which contains application setting from the configuration section as key-value pairs. The Settings property can be indexed using key to get the corresponding value. You can also set the value property and call the Save() method of the Configuration object to write configurations in the Configuration instance to config file.
To delete an entry in the Web.config file: The Remove() method of Settings collection deletes an entry from the Configuration instance. Remove() method accepts key of the entry to be deleted.
Note: Please do not forget to call the Save() method of the Configuration instance to get the chanages reflected in the physical file.
objAppsettings.Settings.Remove("Location");
To iterate through all the key-value pairs in a configuration section, access the string array of keys via AllKeys property of Settings collection.foreach (string strKey in objAppsettings.Settings.AllKeys)
{
DataRow dr = dt.NewRow();
dr["Key"] = strKey;
dr["Value"] = objConfig.AppSettings.Settings[strKey].Value;
dt.Rows.Add(dr);
}
Encryption in Web.Config
Now comes the security issues. At times there comes the necessity for protecting sections of config file. In .NET 2.0 there are options available to encrypt sections of Web.config file programatically. The following method encrypts the "appSettings" section in Web.config file.
private void EncryptAppSettings()
{
Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
if (!objAppsettings.SectionInformation.IsProtected)
{
objAppsettings.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
objAppsettings.SectionInformation.ForceSave = true;
objConfig.Save(ConfigurationSaveMode.Modified);
}
}
The code above opens Web.Config file for modification. It then retrieves the "appSettings" section. The ProtectSection() method of SectionInformation class marks the configuration section for protection. It accepts the name of the protection provider to be used for the encryption. The ForceSave property indicates if the specified configuration section will be saved even if it has not been modified. Finally the Save() of the Configuration object writes the configuration settings to the Web.config file. The argument to the Save() method indicates the only properties modified need to be written to the physical file.
Decrypting sections of web.config file through code is very identical. The UnprotectSection() method of SectionInformation class removes the encryption from the configuration section.
private void DecryptAppSettings()This encrytion and decryption functionality can be applied to other sections of web.config file also. It comes in use mostly for "connectionStrings" section where usually the user name and password would be specified. This can done by creating a
{
Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
if (objAppsettings.SectionInformation.IsProtected)
{
objAppsettings.SectionInformation.UnprotectSection();
objAppsettings.SectionInformation.ForceSave = true;
objConfig.Save(ConfigurationSaveMode.Modified);
}
}
ConfigurationSection object. An example for "connectionStrings" section is listed below. ConfigurationSection objConfigSection = objConfig.ConnectionStrings;
ConfigurationSection class represents a section within the configuration file. Configuration class has propertes for each configuration section. This property can be used to get respective ConfigurationSection objects. This is an alternative to the usage of GetSection() method of Configuration class.