Most of you are probably aware that the web.config file in an ASP.NET project controls the behavior of your Web site.

If you make a change to one of the built-in settings in this file, ASP.NET automatically detects those changes and applies them immediately. Wouldn't it be nice if you could have your own settings in this file applied immediately as well? In this article you will learn how to do just that. You will also learn the difference between the Application object and creating your own Configuration class.

Most programmers have used the Application object to store system-wide values. While this is a convenient storage facility, it does have a few disadvantages:

  • Everything is stored as an Object data type in the Application object. This takes up more memory than a specific data type and, since you must explicitly cast the value each time you wish to use it, this can be a performance hit.
  • There is no IntelliSense when retrieving or setting values into the Application object. If you are setting a value and you do not remember what you called the key of the stored value, you will need to look up the key manually by searching through your program. If you do not spell the key correctly, you will inadvertently create a new variable in the Application object.
  • If you read values from the web.config file, you will need to refresh the values within the Application object yourself. There is no automatic detection of changes.

Retrieving Application Variables Using web.config

The most common method of storing application-wide settings is to place these values into the <appSettings> section of your web.config file as shown in the following code fragment:

<appSettings>
  <add key="ConnectString"
   value="Server=(local);Database=Northwind;uid=sa" />
  <add key="SiteName" value="ConfigSample" />
</appSettings>

You can then read these values during the Application_Start event by using the following code:

Sub Application_Start(ByVal sender As Object, _
 ByVal e As EventArgs)
  Application("ConnectString") = System.Configuration. _
   ConfigurationSettings.AppSettings("ConnectString")
  Application("SiteName") = System.Configuration. _
   ConfigurationSettings.AppSettings("SiteName")
End Sub

To retrieve the values, you would write code like the following:

Private Sub Page_Load(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles MyBase.Load
  lblAppSiteName.Text = Application("SiteName").ToString
  lblAppConnectString.Text = _
   Application("ConnectString").ToString
End Sub

The values SiteName and ConnectString that you pass to the Application object are not verified until runtime. This means that if you misspell "SiteName" as "SileName," you will not notice this error until runtime. This type of error can be very hard to track down. In addition, you must apply the ToString method to convert the object within the Application object to a string. If you store any other data type within the Application object, you need to call the CType() or use the Convert class and one of its appropriate methods. This means more typing and time to perform the conversion.

Creating a Configuration Class

There is a better mechanism for reading in values in the web.config file. This mechanism takes advantage of ASP.NET's ability to call any class you specify to read values from the web.config file. You do this by using settings within the web.config file.

There are many benefits to using this class: You get an IntelliSense-aware list of properties for each value you specify, each property has a specific data type and, finally, if any values have changed in the web.config file the values are automatically refreshed.

While it does take a little time to learn how to create a configuration class, the steps are not difficult and you will find the payoff in increased functionality and reusability well worth the effort.

Overview of Steps

There are some basic steps that you must perform to create a configuration class that can be automatically reloaded with values. Below is a list of general steps to create a configuration class.

  1. Create a <configSections> element in the web.config file.
  2. Add a <section> element with some attributes that describe the name of your configuration class and where it is located.
  3. Add your own <config> element with your own user-defined keys and values to read.
  4. Create a Class that implements the IConfigurationSectionHandler interface.
  5. Write the appropriate implementation of the Create method in your class.
  6. Create an initialization method to be called from the Application_Start event in Global.asax.
  7. Add a call to an initialization method in your class from the Application_Start event procedure in Global.asax.
  8. Add properties that correspond to each of the keys and values you created in your configuration section in web.config.

After you have done these steps, it is a simple matter of adding properties to the class that correspond to the various keys that you create in your <config> element.

Changing the web.config File

The first step is to create a <configSections> element in the web.config file. You may add one or more of your own <config> sections depending on how you might want to categorize your settings.

Follow the steps below to create a sample project that demonstrates how to create a configuration class that can dynamically change values.

  • Create a new ASP.NET Web Application project in Visual Studio .NET. Set the name to ConfigSample.
  • Open web.config and add the XML, shown in Listing 1, immediately below the <configuration> tag.

In the <configSections> element, add a <section> tag to define the name of the next element. In this example, it is called AppConfig. This means that you will create another section with the <AppConfig> element somewhere in the web.config file. In addition, you need to define the full namespace and class name of the class you create to read the data from this configuration section. In this example it is called ConfigSample.AppConfig. ConfigSample is the name of this project (and thus the name of the namespace), AppConfig is the name of the class you will create in this project to read the values from the AppConfig section. After this you add a comma and then repeat the namespace one more time.

You can define as many <add key=> tags in the <AppConfig> element as you want. For each one of these tags, you will most likely create a public property to expose these from the AppConfig class. In the example shown in Listing 1 you have two keys: ConnectString and SiteName.

Create the AppConfig Class

Now that you have the configuration section created, it is time to create the AppConfig class. There are three important items that you must do to create this class correctly. First, you must implement the interface IConfigurationSectionHandler (for more information on implementing interfaces see the ".NET Interface-based Programming" in the May/June issue of CoDe Magazine). Second, you must create an Init method. Third, you must implement the Create method from the IConfigurationSectionHandler interface. Refer to Listing 2.

The Init Method

You need to create a method within the AppConfig class to call from the Application_Start event procedure in the Global.asax page. This initializes the "AppConfig" configuration section of the web.config file. Refer to Listing 3.

The Create Method

The Create method is called the first time you start an application or anytime that the web.config file is modified. This forces your shared property values to be reloaded with the current values from the web.config file. Refer to Listing 4.

Change Global.asax

From the Application_Start event procedure in the Global.asax you must call the Init method in the AppConfig class. This method loads the Configuration section named "AppConfig" into a global memory space within the ASP.NET engine. Refer to Listing 5.

Testing the Application

Now that you have created your class and set key values into your web.config file, it is time to test the application. Follow the steps below to create a user interface to display the values from the web.config file.

  • Display Webform1.aspx in design mode.
  • Set the pageLayout property to FlowLayout.
  • Select Table, Insert, Table from the Visual Studio .NET menu.
  • Create a table with 2 rows and 2 columns.
  • Click OK.
  • Click into the first cell of the first row in the table and double-click on the Label control in the toolbox.
  • Set the Text property of this control to Site Name.
  • Click into the second cell of the first row in the table and double-click on the Label control in the toolbox.
  • Set the Name property to lblSiteName.
  • Set the Text property of this control to an empty value.
  • Click into the first cell of the second row in the table and double-click on the Label control in the toolbox.
  • Set the Text property of this control to Connect String.
  • Click into the second cell of the second row in the table and double-click on the Label control in the toolbox.
  • Set the Name property to lblConnect.
  • Set the Text property of this control to an empty value.
  • Double click the form to display the Page_Load event procedure.
  • Add the following code to the page.

You can test your AppConfig class by retrieving the properties and placing them into labels.

Private Sub Page_Load(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles MyBase.Load
  lblSiteName.Text = AppConfig.SiteName
  lblConnect.Text = AppConfig.ConnectString
End Sub

Run the application and you should see the values you typed into the web.config file appear in the labels on the form.

With the application still running, modify the values in the web.config file and click the Refresh button on your browser. After a couple of refreshes the values should automatically refresh with the new values.

Summary

Creating a configuration class has a lot of benefits when compared to just using the Application object by itself. The ability to have an IntelliSense listing of properties, automatic reload of values when the web.config file changes and having typed properties are just some of the advantages. While using this method requires a little more setup work, the payoff is well worth the effort.