Creating custom configuration sections in Web. config

Source: Internet
Author: User
Tags configuration settings

Ref: http://aspnet.4guysfromrolla.com/demos/printPage.aspx? Path =/articles/020707-1.aspx

Introduction
Most ASP. NET applications include a numberConfiguration Settings, Such as connection strings, mail server settings, system-wide default settings, and so forth. while these settings cocould be hard-coded in the source code, it's usually a wiser idea to place them in a configuration file, suchWeb. 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,Web. configProvides<Deleetask>Section intended to hold application-wide configuration settings (see specifying configuration settings inWeb. configFor more details ).

While<Deleetask>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 useCustom configuration section.<Deleetask>, For example, requires that all values be simple scalars provided through<Add>Elements, like:

<Deleetask>
<Add key = "message" value = "Hello, world! "/>
<Add key = "maxentriesperpage" value = "10"/>
<Add key = "showmessageinbold" value = "true"/>
</Appsettings>

With a custom configuration section, you can provide a more readable syntax. Moreover, custom configuration sections can support collection properties, as the following example extends strates:

<Scottssettings
Message = "Hello, world! "
Showmessageinbold = "true">
<Favoritecolors>
<Color> Red </color>
<Color> yellow </color>
<Color> brown </color>
</Favoritecolors>
</Scottssettings>

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 inWeb. configThrough<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 see e<Configsections>Element inWeb. 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 implementsSystem. configuration. iconfigurationsectionhandler. This class is responsible for loading the configuration markup fromWeb. config.
    • 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.

This model can be used in ASP. NET 2.0 applications,. NET 2.0 offers new configuration classes that eliminate the need for a handler class as well as for the deserialization code. in short, using. NET 2.0's new configuration classes you can simply create a class whose properties represent the configuration information and specify Declaratively, through attributes on the properties, how these properties map to the XML in the configuration markup.

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 configurationsettings class's getconfig method, which has been deprecated in 2.0 in favor of the configurationmanager class's getsection method. regardless, I stick with the using the configurationsettings class's getconfig method. similarly, when we look at specifying collections in the custom configuration section, I use a stringcollection object to hold this collection of strings. if I were creating this. NET 2.0, I 'd use a generic List instance of Type string instead.

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:Message,Favoritenumber, AndShowmessageinbold. We wocould start by creating three public properties in this class like so:

 
Public class aspnet1configuration {private string _ message = "Hello, world! "; Private int _ favoritenumber = 2; private bool _ showmessageinbold = true; Public String message {get {return _ message ;}} public int favoritenumber {get {return _ favoritenumber ;}} public bool showmessageinbold {get {return _ showmessageinbold ;}}...}

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 acceptsXmlnodeInstance as input and steps through the XML data to populate the property values.

Public class aspnet1configuration
{
... Property and member variable statements omitted for beted ...
Internal void loadvaluesfromxml (xmlnode Section)
{
Xmlattributecollection attrs = Section. attributes;
If (attrs ["message"]! = NULL)
{
_ Message = attrs ["message"]. value;
Attrs. removenameditem ("message ");
}
If (attrs ["favoritenumber"]! = NULL)
{
_ Favoritenumber = convert. toint32 (attrs ["favoritenumber"]. value );
Attrs. removenameditem ("favoritenumber ");
}
If (attrs ["showmessageinbold"]! = NULL)
{
_ Showmessageinbold = xmlconvert. toboolean (attrs ["showmessageinbold"]. value );
Attrs. removenameditem ("showmessageinbold ");
}
// If there are any further attributes, there's an error!
If (attrs. Count> 0)
Throw new configurationexception ("there are illegal Attributes provided in the section ");
}
}

TheLoadvaluesfromxmlMethod inspectsAttributesCollection of the passed-inXmlnodeInstance. If it exists, it reads in the value into the corresponding member variable and removes the attribute fromXmlnode. If, after the three properties have been deserialized, there are any additional attributes inXmlnode,ConfigurationexceptionIs raised since an invalid attribute is wrongly ded 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 implementIconfigurationsectionhandler, Which defines a single method,Create.CreateAccepts as one of its input parametersXmlnodeFrom 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:

 
Public class aspnet1configurationhandler: iconfigurationsectionhandler {public object create (Object parent, object configcontext, xmlnode section) {aspnet1configuration Config = new aspnet1configuration (); config. loadvaluesfromxml (section); Return config ;}}

An instance ofAspnet1configurationClass is created and itsLoadvaluesfromxmlMethod is passedXmlnodeInstance already ed byCreateMethod.CreateMethod completes by returning the deserializedAspnet1configurationInstance.

Defining the custom configuration section inWeb. config
To use the custom configuration section inWeb. config, We need to first define it in<Configsections>Element like so:

 
<Configuration> <! -- Define the custom configuration sections... --><Configsections> <section name = "aspnet1configuration" type = "aspnet1configurationhandler"/> </configsections><System. Web>... </system. Web> </configuration>

Note thatTypeValue is the fully-typed name of the handler class. Since the handler class appears in myApp_codeFolder, the value forTypeAttribute is simply the class's name. If this class resided in a separate assembly,TypeValue wocould be :"Namespace.Classname,Assemblyname".

With the custom configuration section specified in<Configsections>, We can add the custom sectionWeb. config. Note that the custom section, like<Configsections>, AppearsOutsideOf<System. Web>Section:

<Configuration> <! -- Define the custom configuration sections... --> <configsections> <section name = "aspnet1configuration" type = "aspnet1configurationhandler"/> </configsections><Aspnet1configuration message = "this is a test! "Showmessageinbold =" true "/><System. Web>... </system. Web> </configuration>

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 useConfigurationsettingsClass'sGetconfigMethod, passing in the path to the markup we are interested in ("aspnet1configuration", for this example). This can be accomplished using the following code snippet:

aspnet1configuration configinfo = (aspnet1configuration) configurationsettings. getconfig ("aspnet1configuration");
// work with the properties from the aspnet1configuration class...
string MSG = configinfo. message;
...

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 /bin folder, 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 upper 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 handler class's Create method is invoked when the getconfig () method is called. on subsequent CILS, however, the 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 addStaticMethod toAspnet1configurationThat encapsulates this logic.

Public static aspnet1configuration getconfig ()
{
Return configurationsettings. getconfig ("customconfigdemo/aspnet1configuration") as aspnet1configuration;
}

With this method in place, accessing a configuration value is as easy as doing the following:

String MSG =Aspnet1configuration. getconfig (). Message;

The following ASP. NET page displays these configuration settings in a label web control, as the following code implements strates:

String messagehtml = aspnet1configuration. getconfig (). message;
If (aspnet1configuration. getconfig (). showmessageinbold)
Messagehtml = "<B>" + messagehtml + "</B> ";
Int favnumber = aspnet1configuration. getconfig (). favoritenumber;
// Display the configuration settings
Aspnet1values. Text = string. Format ("The message is {0} and your favorite number is {1}.", messagehtml, favnumber );

Deserializing more "interesting" configuration Markup
The code we 've 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'sLoadvaluesfromxmlMethod is passedXmlnode, We simply need to update that method to perform any of the more rigorous deserialization. For example, imagine that in addition toMessage,Favoritenumber, AndShowmessageinboldProperties we also wanted to allow the developer to specify a list of "favorite colors" through the following pattern:

 
<Aspnet1configuration message = "this is a test! "Showmessageinbold =" true "><Favoritecolors> <color> Red </color> <color> olive </color> <color> purple </color>... </favoritecolors></Aspnet1configuration>

To accomplish this, we 'd need to add a new property to the configuration classAspnet1configurationTo hold the list of favorite colors. Moreover, we 'd need to updateLoadvaluesfromxmlMethod to find<Favoritecolors>Element and add its<Color>Elements 'text node values to the corresponding property. The following code accomplishes these two tasks:

Public class aspnet1configuration
{
... Prior property and member variable statements omitted for beted ...
Private stringcollection _ favcolors = new stringcollection ();
Public stringcollection favoritecolors {get {return _ favcolors ;}}

Internal void loadvaluesfromxml (xmlnode Section)
{
... Prior deserialization logic removed for brevity ...
// Now, get the child node
Bool processedfavcolors = false;
Foreach (xmlnode childnode in section. childnodes)
{
If (! Processedfavcolors & childnode. Name = "favoritecolors ")
{
Processedfavcolors = true;
Foreach (xmlnode favcolornode in childnode. childnodes)
{
If (favcolornode. Name = "color ")
{
// Get the text node Value
Xmlnode textnode = favcolornode. childnodes [0];
If (textnode = NULL)
Throw new configurationexception ("You must provide a text value for each element, like red ");
Else
_ Favcolors. Add (textnode. value );
}
Else
Throw new configurationexception ("can only contain child elements named ");
}
}
Else
Throw new configurationexception ("may only contain one child element and it must be named ");
}
}
}

conclusion
In this article we have Ed 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 configurationsettings class's getconfig method.

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, leadeus 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 already ed in: creating custom configuration sections in web. config using. NET 2.0's configuration API.

Happy programming!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.