Online courses in ASP.NET MVC / Core, jQuery, Angular, and Design Patterns conducted by Bipin Joshi. Read more...
Learn ASP.NET MVC / Core, jQuery, Angular, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

Modifying Web

Modifying Web.config file programmatically

Introduction

ASP.NET 1.x allowed developers to modify web.config file by hands. However, there was no way to modify the configuration file programmatically. At times  this proved to be a limitation and developers used some tweaks to achieve this. Thankfully ASP.NET 2.0 has come up with a neat way of accessing (reading and writing) the web.config file via code. This article is going to demonstrate an example of how this is done.

Classes and namespaces

The System.Configuration and System.Web.Configuration namespaces provide necessary classes to manipulate web.config. For each web.config section there is corresponding class in either System.Configuration or System.Web.Configuration namespace.

You can open the web.config for modification using WebConfigurationManager class. Then you get hold of the section to be modified using Configuration class. Finally, when you are done you can save changes using Configuration class again.

For the sections that are not specific to a web application as such (<appSettings> and <connectionStrings>) the classes can be found in System.Configuration namespaces. For example, for <appSettings> section there is a class called AppSettingsSection in the System.Configuration. For the sections that are specific to a web application (<authentication>, <compilation> etc.) there are classes in the System.Web.Configuration namespace. For example, there is a class called CompilationSection that represents <compilation> section under <system.web>. These classes allow you to read and modify various properties which in turn are reflected in the corresponding section of web.config.

Example - Modifying the <appSettings> section

As an example we will demonstrate the use of above classes in reading and modifying <appSettings> section.

Create a new web site using VS.NET 2005. Add a web form to it and design it as shown in Figure 1.

Figure 1: Designing App Settings Editor

The web form consists of a DropDownlist and two TextBoxes. The AutoPostBack property of the DropDownList is set to true. When the page loads we will read the <appSettings> section and fill all the keys into the DropDownList. You can select the key in the DropDownList and its existing value will be displayed in the TextBox below. You can also add new key in the <appSettings> section by adding it in the TextBox placed beside the DropDownList. When you click on the Save button the key is either added or updated with its new value. Similarly, when you click the Delete button the selected key from the DropDownList is deleted.

Add a web.config file to the web site and key in the following markup to it:

<appSettings>
   <add key="key1" value="value1" />
   <add key="key2" value="value2" />
   <add key="key3" value="value3" />
</appSettings>

We simply added an appSettings section with three keys - key1, key2 and key3.

Now go in the code behind of the web form and import the following two namespaces:

using System.Configuration;
using System.Web.Configuration;

Add a function called FillDropDownList() that populates the DropDownList with all the keys from <appSettings> section.

private void FillDropDownList()
{
Configuration config;
config = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appsettings;
appsettings = (AppSettingsSection)config.GetSection("appSettings");
DropDownList1.Items.Clear();
foreach (string key in appsettings.Settings.AllKeys)
{
DropDownList1.Items.Add(key);
}
}

Here, we called OpenWebConfiguration() static method of WebConfigurationManager class. Since we are interested to access web.config of our own application and that too residing in the root folder we pass "~" as the parameter. You can also open web.config files of other web sites and locations using various overloads of OpenWebConfiguration method. The return value of OpenWebConfiguration() method is an instance of class Configuration.

We then call GetSection() method of Configuration class to get hold of the <appSettings> section. The GetSection() methods accepts the path of the section within the configuration file. Since <appSettings> resides immediately within <configuration> root node we specified appSettings as the parameter. If you want to access, let's say, <compilation> section you would have passed system.web/compilation as the parameter to GetSection() method.

The return value of GetSection() method is of generic type ConfigurationSecton and hence we typecast it to AppSettingsSection. Then we iterate through all the keys of <appSettings> section using the Settings name value collection of AppSettingsSection class and add it to the DropDownList.

Now call the FillDropDownList() method in Page_Load event as shown below:

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
     FillDropDownList();
   }
}

Now handle SelectedIndexChanged event of the DropDownList as shown below:

protected void DropDownList1_SelectedIndexChanged
(object sender, EventArgs e)
{
Configuration config;
config = WebConfigurationManager.
OpenWebConfiguration("~");
AppSettingsSection appsettings;
appsettings = (AppSettingsSection)
config.GetSection("appSettings");
TextBox2.Text = appsettings.Settings
[DropDownList1.SelectedValue].Value;
}

Here we simply read the value of the selected key from the DropDownList using Settings collection of AppSettingsSection and assign it to the Text property of TextBox2.

Next, add the following code in the Click event of Save button.

protected void Button1_Click
(object sender, EventArgs e)
{
Configuration config;
config = WebConfigurationManager.
OpenWebConfiguration("~");
AppSettingsSection appsettings;
appsettings = (AppSettingsSection)config.
GetSection("appSettings");
if (appsettings != null)
{
if (TextBox1.Text == "")
{
appsettings.Settings
[DropDownList1.SelectedValue].Value = 
TextBox2.Text;
}
else
{
appsettings.Settings.Add
(TextBox1.Text,TextBox2.Text);
}
config.Save();
}
}

We get hold of the appSettings section as before. Then we check if the user has entered any value in the TextBox (indicating that this is a new key to be added). If the TextBox1 is empty we set the key selected in the DropDownList with the value entered in the TextBox2. Otherwise, we add a new key in the Settings collection. Finally, we call Save() method of Configuration class to persist the changes to the disk.

Add the following code to the Click event of Delete button.

protected void Button2_Click
(object sender, EventArgs e)
{
Configuration config;
config = WebConfigurationManager.
OpenWebConfiguration("~");
AppSettingsSection appsettings;
appsettings = (AppSettingsSection)config.
GetSection("appSettings");
if (appsettings != null)
{
appsettings.Settings.Remove
(DropDownList1.SelectedValue);
config.Save();
FillDropDownList();
}
}

Here we call Remove() method of the Settings collection and pass the key selected from the DropDownList. As before we call Save() method to persist the changes. We call FillDropDownList() method again so that latest keys are displayed back in the DropDownList.

Run the web form and see if modifications and deletions work as expected.

Things to note

It is important to know the impact of changing web.config file via code on the overall behavior of the application.

When you change web.config file ASP.NET senses the changes automatically and restarts your web application. This means values stored in the session and application variables are lost. If you are changing web.config often then it can affect performance of your web application because of such frequent restarts.

You must have write access to the web.config file. You may think of using Windows based security coupled with impersonation.

Summary

ASP.NET 2,0 allows a flexible way to change web.config file programmatically. Using this technique you can access various sections of the configuration file and read or write to them. However, one should use this feature with proper understanding of side-effects such as application restarts and permissions.




Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 05 May 2006



Tags : ASP.NET Security Configuration Deployment XML