3.6 Building a Custom Configuration Section Handler


Although most commonly used application-specific settings can be stored in the appSettings element, you may sometimes want to augment the set of available configuration elements with your own custom one. Even if you never need to do this, it is still instructive to walk through an implementation of a custom configuration section handler to better understand how the web.config file is parsed.

To see an example of building a custom configuration section handler, suppose we want our applications to be able to specify custom elements using an element called acme , contained in a new section called acmeGroup , as shown in Listing 3-11. The elements we are interested in are font , backgroundColor , underlineLinks , horizontalWidth , and verticalWidth , presumably to customize the way our application appears on a particular installation site.

Listing 3-11 Sample Custom Configuration Element
 <! File: web.config > <configuration>   <acmeGroup>     <acme>       <font>Courier New</font>       <backgroundColor>Green</backgroundColor>       <underlineLinks>true</underlineLinks>       <horizontalWidth>600</horizontalWidth>       <verticalWidth>800</verticalWidth>      </acme>   </acmeGroup> </configuration> 

To begin with, we must come up with some mechanism for saving the state associated with this configuration. There are many ways of doing this, but to keep things simple, let's take the approach of defining a class with public data members corresponding to the configuration elements we have defined. The AcmeSettings class shown in Listing 3-12 should be suitable.

Listing 3-12 Sample Custom Configuration Settings State Class
 // File: AcmeSettings.cs namespace EssentialAspDotNet.Config {   public class AcmeSettings   {     public string Font;     public string BackgroundColor;     public bool   UnderlineLinks;     public int    HorizontalWidth;     public int    VerticalWidth;   } } 

Next, we need to build a class that implements IConfigurationSectionHandler to parse our section of the configuration file and store the contents into our new AcmeSettings class, shown in Listing 3-13.

Listing 3-13 Sample Custom Configuration Section Handler
 // File: AcmeConfigHandler.cs namespace EssentialAspDotNet.Config {   public class AcmeConfigHandler :                                IConfigurationSectionHandler   {     public object Create(object parent, object input,                          XmlNode node)     {       AcmeSettings aset = new AcmeSettings();       foreach (XmlNode n in node.ChildNodes)       {         switch (n.Name)         {           case ("font"):             aset.Font = n.InnerText;             break;           case ("backgroundColor"):             aset.BackgroundColor = n.InnerText;             break;           case ("underlineLinks"):             aset.UnderlineLinks = bool.Parse(n.InnerText);             break;           case ("horizontalWidth"):             aset.HorizontalWidth = int.Parse(n.InnerText);             break;           case ("verticalWidth"):             aset.VerticalWidth = int.Parse(n.InnerText);             break;         }       }       return aset;     }   } } 

The final step is to tell the configuration file to use this class to parse the acme element in our configuration files. As shown in Listing 3-14, we do this by adding a section element to the configSections portion of our configuration file ”this could be in the systemwide machine.config file, the sitewide web.config , or the application-wide web.config , and it will apply to all configuration files parsed after that one is read.

Listing 3-14 Installing a Custom Configuration Section Handler
 <! File: web.config > <configuration>   <configSections>     <sectionGroup name="acmeGroup">        <section name="acme"          type="EssentialAspDotNet.Config.AcmeConfigHandler, AcmeConfigHandler"        />     </sectionGroup>   </configSections>   <! ... > </configuration> 

Any page or piece of code in our application could now access this configuration information using the ConfigurationSettings.GetConfig() method, passing in the section group and section name we created, and casting the result to our AcmeSettings class, as shown in Listing 3-15.

Listing 3-15 Accessing Custom Configuration Information
 // File: TestAcmeSettings.aspx protected void Page_Load(object src, EventArgs e) {   AcmeSettings set;   set = ConfigurationSettings.GetConfig("acmeGroup/acme")         as AcmeSettings;   // use set here (like set.Font, set.BackgroundColor,   // etc.) } 

3.6.1 Using the NameValueFileSectionHandler

If you want a custom configuration section, but you don't want to go to the trouble of writing your own class that implements the IConfigurationSectionHandler interface, you can create a new section that reuses the same class as the appSettings element. You are limited to using the add element with key/value pairs for adding new configuration elements, but if this is tolerable, adding a new configuration section becomes even easier. For example, Listing 3-16 shows how to add a new section called myGroup to a configuration file and populate it with values similar to our custom acmeGroup shown earlier. Notice that the type specified in the section element refers to a class found in the system assembly called NameValueFileSectionHandler . Instances of this class store the key/ value pairs in a NameValueCollection for later access. Listing 3-17 shows how you would access this collection from within an .aspx page in the application.

Listing 3-16 Adding a Custom Configuration Section with a Prebuilt Handler
 <! File: web.config > <configuration>   <configSections>      <section name="myGroup"     type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>   </configSections>   <myGroup>     <add key="font" value="Courier New"/>     <add key="backgroundColor" value="Green"/>     <add key="underlineLinks" value="true"/>     <add key="horizontalWidth" value="600"/>     <add key="verticalWidth" value="800"/>   </myGroup>   <! ... > </configuration> 
Listing 3-17 Accessing Custom Configuration Information with NameValueCollection
 // File: TestAcmeSettings.aspx protected void Page_Load(object src, EventArgs e) {   NameValueCollection set;   set = ConfigurationSettings.GetConfig("myGroup")         as NameValueCollection;   // use set here (like set["Font"],   // set["BackgroundColor"], etc.) } 


Essential ASP.NET With Examples in C#
Essential ASP.NET With Examples in C#
ISBN: 0201760401
EAN: 2147483647
Year: 2003
Pages: 94
Authors: Fritz Onion

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net