ASP.NET: Creating an Application Configuration Class

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

  • 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 section of your web.config file as shown in the following code fragment:

            

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. (See Sidebar 1: Do I Have to Use web.config?) 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 element in the web.config file.
  2. Add a
    element with some attributes that describe the name of your configuration class and where it is located.
  3. Add your own 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 element.

Changing the web.config File
The first step is to create a element in the web.config file. You may add one or more of your own 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.

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

In the element, add a

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 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 tags in the 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. (See Sidebar 2: What Else is in web.config?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 “.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.

  1. Display Webform1.aspx in design mode.
  2. Set the pageLayout property to FlowLayout.
  3. Select Table, Insert, Table from the Visual Studio .NET menu.
  4. Create a table with 2 rows and 2 columns.
  5. Click OK.
  6. Click into the first cell of the first row in the table and double-click on the Label control in the toolbox.
  7. Set the Text property of this control to Site Name.
  8. Click into the second cell of the first row in the table and double-click on the Label control in the toolbox.
  9. Set the Name property to lblSiteName.
  10. Set the Text property of this control to an empty value.
  11. Click into the first cell of the second row in the table and double-click on the Label control in the toolbox.
  12. Set the Text property of this control to Connect String.
  13. Click into the second cell of the second row in the table and double-click on the Label control in the toolbox.
  14. Set the Name property to lblConnect.
  15. Set the Text property of this control to an empty value.
  16. Double click the form to display the Page_Load event procedure.
  17. 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.

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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may