Creating Custom Configuration Sections in Web.configBy Scott Mitchell
Most ASP.NET applications include a number of configuration settings, such as connection strings, mail server settings, system-wide default settings, and so forth. While these settings could be hard-coded in the source code, it's usually a wiser idea to place them in a configuration file, such as
Web.config. The reasoning being that if these values need to be modified, editing a configuration file is a lot easier than updating the code, rebuilding, and re-deploying. In fact,
<appSettings>section intended to hold application-wide configuration settings (see Specifying Configuration Settings in
Web.configfor more details).
<appSettings> work well for in-house applications, if you are building an application that will
be deployed by end users a more professional approach is to use a custom configuration section.
for example, requires that all values be simple scalars provided through
<add> elements, like:
With a custom configuration section, you can provide a more readable syntax. Moreover, custom configuration sections can support collection properties, as the following example illustrates:
In this article we'll examine how to use a custom configuration section technique that works in both ASP.NET 1.x and 2.0 applications. See Creating Custom Configuration Sections in Web.config Using .NET 2.0's Configuration API for more on .NET 2.0's new configuration classes and capabilities. Read on to learn more!
Custom Configuration Section Basics
Custom configuration sections can be created in
<configSections>element, specifying the name of the configuration section and the class type that is responsible for deserializing the configuration XML into a class instance. We'll explore the
Web.configonce we have created a class to handle the deserialization.
In ASP.NET 1.x applications, typically two classes are used:
- A handler class, which implements
System.Configuration.IConfigurationSectionHandler. This class is responsible for loading the configuration markup from
- A configuration class whose set of properties represent the information captured in the custom configuration section. Along with providing the properties, this class also is responsible for deserializing the configuration XML passed to it from its corresponding handler class.
In this article we will focus solely on the 1.x technique; Creating Custom Configuration Sections in Web.config Using .NET 2.0's Configuration API for more on .NET 2.0's new configuration classes and capabilities. We'll first look at creating and using a very simple custom configuration section. Following that, we'll add a collection property to the section.
|Why ASP.NET 1.x Syntax and Style is Used|
Since this article examines features that date back to the 1.x timeframe (even though they'll work perfectly fine in 2.0
and even though the download at the end of this article is an ASP.NET 2.0 website application),
I've used the syntax that works in 1.x rather than take advantage of new 2.0 features. For example, later on in this article
we'll use the |
Creating the Configuration Class
As aforementioned, the code for custom configuration sections in ASP.NET 1.x applications is typically broken down into two class files, a handler class and a configuration class. Let's create the configuration class first. Imagine that we want our custom configuration section to record three settings:
showMessageInBold. We would start by creating three public properties in this class like so:
The three private member variables specify the default values (i.e., the values used if the property is not provided in the custom configuration section). The three properties are read-only and simply return the corresponding member variable.
The configuration class also needs to provide a method for deserializing the configuration XML. To accomplish this, we need
to add a method that accepts an
XmlNode instance as input and steps through the XML data to populate the property
LoadValuesFromXml method inspects the
Attributes collection of the passed-in
instance. If it exists, it reads in the value into the corresponding member variable and removes the attribute from the
XmlNode. If, after the three properties have been deserialized, there are any additional attributes in the
ConfigurationException is raised since an invalid attribute is included in the
custom configuration section.
Creating the Handler Class
The handler class is reponsible for taking the XML from the configuration file and passing it to the configuration class for deserialization. The handler class must implement
IConfigurationSectionHandler, which defines a single method,
Createaccepts as one of its input parameters the
XmlNodefrom the configuration section and is tasked with returning an instance of the configuration data. This can all be accomplished with just a few lines of code, as shown below:
An instance of the
ASPNET1Configuration class is created and its
LoadValuesFromXml method is passed
XmlNode instance received by the
Create method. The
Create method completes by
returning the deserialized
Defining the Custom Configuration Section in
To use the custom configuration section in
Web.config, we need to first define it in the
<configSections>element like so:
Note that the
type value is the fully-typed name of the handler class. Since the handler class appears in my
folder, the value for the
type attribute is simply the class's name. If this class resided in a separate assembly,
type value would be: "Namespace.ClassName, AssemblyName".
With the custom configuration section specified in
<configSections>, we can add the custom
Web.config. Note that the custom section, like
appears outside of the
Programmatically Accessing the Configuration Information from the ASP.NET Application
To work with the configuration information from an ASP.NET page or one of the classes that make up the application's architecture, we need to use the
GetConfigmethod, passing in the path to the markup we are interested in ("aspnet1Configuration", for this example). This can be accomplished using the following code snippet:
What's cool about the
GetConfig() method is that is automatically caches the configuration information
returned by the associated handler class. This data remains cached until the application is restarted (such as through
restarting the webserver, modifying
Web.config, uploading an assembly to the
and so on). To convince yourself that this caching occurs, download the sample code at the end of this article and set a
breakpoint in the above line of code and in the
Create method of the handler class and then start debugging.
What you'll find is that the first time the configuration data is read in after an application restart, the
Create method is invoked when the
GetConfig() method is called. On subsequent calls,
Create method is not executed, as its results have been cached.
Rather than having to enter this code each time we want to work with configuration data, we can add a
method to the
ASPNET1Configuration that encapsulates this logic.
With this method in place, accessing a configuration value is as easy as doing the following:
The following ASP.NET page displays these configuration settings in a Label Web control, as the following code illustrates:
Deserializing More "Interesting" Configuration Markup
The code we've examined thus far has only allowed for scalar properties defined as attributes in the configuration markup. But what if we want to have the custom configuration section specify properties through the XML elements' text nodes (like
<someProperty<value</someProperty>) or what if we want to allow the configuration data to include an arbitrary collection of information?
Since the configuration class's
LoadValuesFromXml method is passed an
XmlNode, we simply need to update
that method to perform any of the more rigorous deserialization. For example, imagine that in addition to the
showMessageInBold properties we also wanted to allow the developer to specify
a list of "favorite colors" through the following pattern:
To accomplish this, we'd need to add a new property to the configuration class
ASPNET1Configuration to hold the
list of favorite colors. Moreover, we'd need to update the
LoadValuesFromXml method to find the
element and add its
<color> elements' text node values to the corresponding property. The following code
accomplishes these two tasks:
In this article we explored the technique used in ASP.NET 1.x for specifying custom configuration settings in
Web.config. This is accomplished by creating two classes: a handler class and a configuration class. The handler class is used to pump the XML data from the configuration file to the configuration class, where it is deserialized. In addition to its deserialization logic, the configuration class also contains the properties that model the configuration information. This class can be accessed programmatically via the
This method for providing custom configuration sections can be used by both ASP.NET 1.x and 2.0 applications. However, .NET 2.0 provides configuration classes that require much less code, letting us focus more on defining the properties and declaratively mapping them to the XML markup rather than writing XML deserialization code. .NET 2.0's configuration features are explored in: Creating Custom Configuration Sections in Web.config Using .NET 2.0's Configuration API.