Creating custom configuration sections in Web. config using. NET 2.0's configuration API

Source: Internet
Author: User

Ref: http://aspnet.4guysfromrolla.com/demos/printPage.aspx? Path =/articles/032807-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.

we can define custom configuration sections in Web. config that conforms to a pre-determined XML schema. for example, our web application might have a couple of scalar configuration settings ( quoteoftheday and yourage ) as well as a collection of settings ( favoritestates ) where each setting in the collection can have its own scalar values ( name and abbreviation , let's say ). this configuration information cocould be expressed in Web. config using the following XML markup:

<Scottssettings
Quoteoftheday = "Hello, world! "
Yourage = "28">
<Favoritestates>
<Add name = "California" abbreviation = "ca"/>
<Add name = "Missouri" abbreviation = "Mo"/>
<Add name = "Illinois"/>
</Favoritestates>
</Scottssettings>

In creating custom configuration sections inWeb. configWe examined a technique for parsing the XML in custom configuration section that works in both ASP. net 1.x and 2.0 applications. this required writing a bit of code. ASP. NET 2.0 applications, however, can utilize. NET 2.0's new configuration API, which makes creating custom configuration sections much easier. 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. As we saw in the creating custom configuration sections inWeb. configArticle, ASP. NET 1.x applications typically use two classes:

    • 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 approach works equally well with ASP. NET 2.0 applications. however,. NET 2.0 Framework except des a new configuration API that makes creating custom configuration sections even easier. rather than having to create two classes and write code that deserializes the XML into the configuration class, we can instead create the configuration class and decorate its properties withConfigurationpropertyAttribute. In short, the. NET 2.0 configuration API automatically deserializes the XML into an instance of the configuration class based on the attributes on the class's properties.

In this article we will focus solely on this new 2.0 technique; for more on the technique that works in both ASP. NET 1.x and ASP. NET 2.0, see creating custom configuration sections inWeb. config.

Creating the configuration class
To use the. NET 2.0 configuration API, all we need to do is create a class that derives fromConfigurationsectionClass. This class represents the root XML element of the custom configuration section inWeb. config. To capture scalar data for the custom configuration section, simply add properties with scalar data types and decorate them usingConfigurationpropertyAttribute.

Imagine that we wanted a configuration section that captured two scalar configuration settings:QuoteofthedayAndYourage. We cocould create a configuration class with the following two properties:

public class aspnet2configuration: configurationsection
{< br> [configurationproperty ("quoteoftheday ", defaultvalue = "It is what it is. ", isrequired = false)]
Public String quoteoftheday
{< br> Get
{< br> return this ["quoteoftheday"] as string;
}< BR >}< br> [configurationproperty ("yourage", isrequired = true)]
Public int yourage
{< br> Get
{< br> return (INT) This ["yourage"];
}< BR >}

the key parts are in bold . first, note that the class aspnet2configuration is derived from the configurationsection class. next, note the class's two properties: quoteoftheday and yourage , of types string and int , respectively. the configurationproperty attribute decorating each property indicates that these properties are to be specified via the custom configuration XML. the configurationproperty attribute can accept a number of parameters, including:

    • name -this is the first parameter, which specifies the name of the property as encoded in the custom configuration XML in Web. config .
    • defaultvalue -the default value for the property if it is not specified in the custom configuration XML.
    • isrequired -A boolean value that indicates whether the property must be specified in the custom configuration XML. if isrequired is true, but the property's value isn' t specified in the custom configuration section in Web. config , then an exception will be thrown when attempting to visit the site.

The scalar values specified in the configuration XML can be accessed fromConfigurationsectionClass UsingThis ["Xmlattributename"], And this is the syntax used in the get accessors to read the configuration information. The configuration information cannot be directly written to (hence the omission of a set accessor ).

Adding the custom configuration section inWeb. config
Defining the custom configuration section inWeb. configFor an application that uses the. NET 2.0 configuration API is no different than when using the ASP. NET 1.x approach examined in creating custom configuration sections inWeb. config. To use the custom configuration section inWeb. config, We need to first define it in the element like so:

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

Note thatTypeValue is the fully-typed name of the configuration class. Since the handler class appears in myApp_codeFolder, the value forTypeAttribute is simply the class's name (Aspnet2configuration). 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 = "aspnet2configurationdemo" type = "aspnet2configuration"/> </configsections><Aspnet2configurationdemo quoteoftheday = "Love your enemy like thy neighbor." yourage = "28"/><System. Web>... </system. Web> </configuration>

SinceYourageProperty was markedIsrequired = true, If the value is omitted a configuration error is displayed when attempting to visit the site with the message: "required attribute 'yourage' not found ."

Programmatically accessing the configuration information
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 ("aspnet2configurationdemo", for this example). This can be accomplished using the following code snippet:

Aspnet2configuration configinfo = (aspnet2configuration) configurationsettings. getconfig ("aspnet2configurationdemo ");
// Work with the properties from the aspnet2configuration class...
String quote = configinfo. quoteoftheday;
...

What's cool aboutGetconfig ()Method is that is automatically caches the configuration information. This data remains cached until the application is restarted (such as through restarting the webserver, modifyingWeb. config, Uploading an assembly to/BinFolder, and so on ).

Rather than having to enter the above Code each time we want to work with configuration data, we can addStaticMethod toAspnet2configurationThat encapsulates this logic.

Public static aspnet2configuration getconfig ()
{
Return configurationsettings. getconfig ("aspnet2configurationdemo") as aspnet2configuration;
}

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

String quote =Aspnet2configuration. getconfig (). quoteoftheday;

capturing collection-based configuration information
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 capture a set of values? Imagine that for our application we want to display information about a number of States (or cities or countries), but want to let the page developer dictate what States, exactly, are available from the application. in short, we want to augment the custom configuration markup to include a collection. to accomplish this using. NET 2.0's configuration API we need to create two new classes: one that models the data that represents each instance of the collection and one that models the collection.

for example, imagine that we wanted to capture the name and abbreviation of a variable number of States via the custom configuration section. we wocould start by creating a class that derives from the configurationelement class and captures information for a particle state (namely its name and abbreviation ). just like with the aspnet2configuration , these scalar values are specified via class Properties Using the configurationproperty attribute:

public class aspnet2configurationstate: configurationelement
{< br> [configurationproperty ("name", isrequired = true)]
Public string name
{
Get
{
return this ["name"] as string;
}< BR >}< br> [configurationproperty ("abbreviation", isrequired = false)] Public String abbreviation
{< br> Get
{< br> return this ["abbreviation"] as string;
}< BR >}

Next we need to create a class that models A CollectionAspnet2configurationstateObjects. the. NET 2.0 configuration API between desConfigurationelementcollectionBase class that we can extend to capture a setAspnet2configurationstateObjects. when extendingConfigurationelementcollectionClass we need to overrideCreatenewelementAndGetelementkeyMethods. TheseCreatenewelementMethod is responsible for creating a new instance of the object being held by the collection. each object in the collection is indexed via a key, so we need to specify what property of the objects in the collection qualifies as the key. theGetelementkeyReturns the key value for a participant element in the collection.

Public class aspnet2configurationstatecollection: Configurationelementcollection
{
Public aspnet2configurationstate this [int Index]
{
Get
{
Return base. baseget (INDEX) as aspnet2configurationstate;
}
Set
{
If (base. baseget (INDEX )! = NULL)
{
Base. baseremoveat (INDEX );
}
This. baseadd (index, value );
}
}
Protected override configurationelement createnewelement ()
{
Return new aspnet2configurationstate ();
}
Protected override object getelementkey (configurationelement element)
{
Return (aspnet2configurationstate) element). Name;
}

}

Now that the two necessary classes have been created, we can add the collection class (Aspnet2configurationstatecollection) As a property ofAspnet2configurationClass:

public class aspnet2configuration: configurationsection
{< br>... quoteoftheday and yourage properties and getconfig () method removed for breaching ...
[configurationproperty ("favoritestates")]
Public aspnet2configurationstatecollection favoritestates
{< br> Get
{< br> return this ["favoritestates"] As aspnet2configurationstatecollection;
}< BR >}

}

A simple demo
The download at the end of this article includes the custom configuration classes examined in this article along with a simple demo using strating how to read the configuration data from code in an ASP. NET page's code-behind class. the demo provided des a label web control that displays the various configuration setting values. for example, given the following configuration settings:

<Aspnet2configurationdemo
Quoteoftheday = "Love your enemy like thy neighbor ."
Yourage = "28">
<Favoritestates>
<Add name = "California" abbreviation = "ca"/>
<Add name = "Missouri" abbreviation = "Mo"/>
<Add name = "Illinois"/>
</Favoritestates>
</Aspnet2configurationdemo>

The demo displays the following output:

Be sure to download the demo and code at the end of this article and give it a try on your computer.

Conclusion
In this article we have Ed the. NET 2.0 configuration API and how it can be used to specify custom configuration settings inWeb. config. Unlike the approach used in ASP. NET 1.x, the custom configuration API automatically handles the deserialization of configuration markup to our configuration classes.

Happy programming!

  • By Scott Mitchell
  • 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.