*** When a New Article posted, get Notification to the email that you give below: ***

Tuesday, October 30, 2012

[ASP.Net] - Dynamically updating web config file in .net


1) Introduction


Web site settings are supplied by the web.config file. The settings are like connection strings, how many users allowed etc. Sometimes the situation arises that the configuration settings to be added or revoked without re-starting the server. In this article, we will see a demo of how do we add new settings when the site is running. Imagine that the page we are going to develop is used by the web admin of the site. The goal is adding a new web setting dynamically, and in the meantime the server will function as usual without any re-start.



2) About the sample


The page design screen shot is provided below.





In the user name section of the page, we add the session variable for the user name when the Set User Name button is clicked. The Get User Name button will retrieve the session variable content and displays that the label next to it.

In the Application Settings section of the page, we add a web setting dynamically by clicking the Store button. We should provide a setting name and an associated value to it in the corresponding text boxes. By clicking the Retrieve button, we can get the setting value by supplying the setting name.

In this demo, we are going to add new setting by clicking the Store button and make sure that session we set before this operation is kept unchanged. OK, Let us start.



3. Session Variable


A session identifies a user connecting to the website and the session continues until he/she disconnects from it. Now the session variable is one, which has the scope of the connected user session and the variable goes out-of-scope when he/she disconnects the web session. Therefore, once we define and assign a value to a session variable, the content is available for all the pages within that session.

In our sample, we store and retrieve the user name as the session variable.

1) In the button click handler for the Set User Name, we are setting the content of the user name in a session variable called “User Name”. Here, user name is the Key and the value is whatever we specify in the text box next to Set User Name.

//Sample 01: Store a session variable
protected void btnSetUser_Click(object sender, EventArgs e)
{
    Session["User Name"] = txtUserName.Text;
}

2) When Get User Name button is clicked, we get the “User Name” session variable and display that in the value textbox. Before doing so, we are checking the session variable User Name is actually having any value. If we don’t have a value, then we display session is lost. Actually, the message becomes meaningless when the session is not yet created. This session variable is just for demo purpose and our goal is modifying the web application setting without loosing the session variables. So, do not worry about the validation message and how meaningful it is in a variety of situations.

//Sample 02: Retrieve session variable Name
protected void btnGetUserName_Click(object sender, EventArgs e)
{
    if (null != Session["User Name"])
        lblSession.Text = Session["User Name"].ToString();
    else
        lblSession.Text = "The Session variable is lost";
}

3) In the clear button click event handler, we cleared some of the form fields for convenience while entring the new values

//Sample 03: Clear the form
protected void btnClear_Click(object sender, EventArgs e)
{
    lblSession.Text = "";
    txtName.Text = "";
    txtValue.Text = "";
}

OK, Let us test what we have written in the two button click events. The video below shows setting and retrieving the username in a session variable called User “User Name”.



Video Steps
1) The solution is run in debug mode
2) Then, the user name for the session is set by clicking the Set User Name
3) Finally, the user name in the session is retrieved by clicking the Get User Name



4. Retrieving the App Settings


1) We use the WebConfigurationManager to retrieve the application settings that is previously saved in web.config file. When we click the Retrieve button after supplying the setting name, the settings value is retrieved and displayed in the value text box. The code for that is given below.

//Sample 06: Retrieve the Setting
protected void btnRetrieve_Click(object sender, EventArgs e)
{
    string value = "";
    if (WebConfigurationManager.AppSettings[txtName.Text] != null )
        value = WebConfigurationManager.AppSettings[txtName.Text];
    txtValue.Text = value;
}

2) Have a look at the section of code taken from the web.config file, which is given below:

<appSettings>
    <add key="pageTitle" value="MsTechArticles.com" />
</appSettings>

In this, we have only one application setting. The setting name is pageTitle and the value is MsTechArticles.com.  Now watch the video below which shows retrieving the setting value for the given key pageTitle.



Video Steps
1) In web.config current application setting section is previewed
2) Moved to DynamicSettings.aspx and Run toolbar button is clicked
3) In the form Setting name (pageTitle) is given and setting value is retrieved



5. Dynamically storing the Settings


The settings are stored in the web configuration file under different sections. In this article, we are looking at the AppSettings section only. You can apply what you learn in this article to any configuration sections (With little exploration when required). Say for example ConnectionStrings. We use OpenWebConfiguration method of the WebConfigurationManager to dynamically add new setting to the web configuration.

//Sample 05: Add New settings
protected void btnStore_Click(object sender, EventArgs e)
{
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
    config.AppSettings.Settings.Add(txtName.Text , txtValue.Text);
    config.Save();
}

In the above code, we get the reference to the Configuration object by calling the OpenWebConfiguration available in the root directory of the web application. If it is not there then we get the settings from the default configuration of the machine. This configuration is the merged view of the all the available settings. Therefore, from the config instance, we get the Application settings to add the application-setting name and the associated value to it. In our sample application setting and the name is supplied by the user (Say web Admin). Once the settings added to the required data structure, we call the save method on the config object.

It is time to check the code written for storing the application setting. The below given video shows storing the configuration setting dynamically. It also shows that we add a new entry in the web.config file, we lose our session and application (Not shown in the demo) variables.



Video Steps
1) The form is run in the debugger mode
2) A first setting setting1 and corresponding value is added
3) Then a second setting setting2 and corresponding value is entered
4) Before clicking the store button, a session value is stored in a session variable
5) Then, store button of the Application setting clicked to append one more setting (Setting2)
6) The Get User Name button is clicked, and Session Variable content loss is shown
7) At last, dynamically added web setting are shown in the web.config file



6. Dynamic Update of Web Settings without losing the Sessions


We did modification in the web.config dynamically and all the session variable contents are lost. This we saw in the previous video. To avoid this we should move the application settings to a new configuration file. This file is referred as External Configuration file. Add a new configuration file called settings.config by right clicking the project name and selecting Add New Item from the displayed content menu. The picture given below shows entering the data in the Add New Item Dialog.


The external configuration file is added to the project after clicking the add button in the “add new item” dialog. Now go to the Web.Config file and remove or comment out the AppSettings section. The code given below shows the commented out piece of code in the web.config file.

<!-- Sample 07: Comment out AppSettings section 
<appSettings>
    <add key="pageTitle" value="MsTechArticles.com" />
</appSettings>
-->

Once the above code is commented out, we should specify the external file name in the web.config file to look for the AppSettings in it. Web.config file entry for that is shown below:

<!-- Sample 08: Specify the external settings source  -->
<appSettings configSource="settings.config"/>

Now add the AppSettings that is commented or Removed (From the original web.config file) to the newly created Settings.config file. The added AppSettings section is shown below:

<!-- Sample 09: Add the App settings in the external source file -->
<appSettings>
 <add key="pageTitle" value="MsTechArticles.com" />
</appSettings>

That is all the code change required on the configuration to make the dynamic update of the web configuration file. Now we will not lose our session variables when a new entry is added to the web configuration. This time new settings enter the Settings.config in place of the web.config. Watch this in the video given below:



Video Steps
1) The form is opened in the browser
2) The settings are entered in the Application Settings portion of the form
3) Also the session variable is stored and retrieved in between the settings change

The settings stored in Settings.config file by the above testing (One shown in the video) is shown in the below picture:



There is one more point that should be noted here. The AppSettings by default does not require any server re-start when we append the settings dynamically. For other sections, you should always make sure that ReStartOnExternalChanges is set to False. This we should check on the machine.config file and the screenshot given below shows the default entry for the appsettings.



Examine the path: <DriveLetter>:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG for machine.config file. Say for example you want to add a new connection string in the web configuration, the first thing you should do is check the machine.config file and set the restartonExternalChanges=false. Then follow what you learned in this article.

Source Code: Download

No comments:

Post a Comment

Leave your comment(s) here.

C++ Articles

DISCLAIMER

The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway