ASP.net: Custom Web.config Sections and Elements

On occasion you will find it necessary to add your own configuration sections to your web application’s web.config configuration file. This allows you to encapsulate configuration options needed by your components into a manageable section within your applications configuration. The information you place in the custom configuration section should be items that may change frequently.

By adding configuration information used by your components to the web,config file you can at any time without recompiling your application code alter the behavior and functionality of your components by changing these configuration options. This is because the web.config file is monitored by the ASP.net worker process and when ever it is altered the application is restarted and the configuration is re-read so that all components utilizing the configuration will receive the updates.

Here is what the config section definition looks like. This is added to the ‘configSections’ portion of the web.config files (at the top usually). This section defines what other sections are within the rest of the configuration file and which can be read by the web application. It takes a name which is the name of th e


<section name="myconfigsection" type="MyAssembly.MyConfigSection, MyAssembly, Version=1.0.0.0, Culture=neutral" requirePermission="false"/>

Here is what the config section we will be working from looks like


<myconfigsection>
    <mylistoffoods>
        <add name="bacon" enjoy="true" />
<
add name="steak" enjoy="true" />
<add name="celery" enjoy="false" /> </mylistoffoods>

</myconfigsection>
The first thing to do is create what I call a ‘Configuration Helper’ class which is responsible for pulling our configuration section and exposing it to our component as a public property which our code can access. Here is the class:


using System;
using System.Configuration;
namespace MyAssembly
{
    /// 
    /// This class is used to retrieve most important settings from web.config
    /// 
    public class ConfigurationHelper
    {

#region Private Fields private static MyConfigSection _myConfigSection =

            (MyConfigSection)ConfigurationManager.GetSection("myconfigsection");
        #endregion
        #region Public Properties
        /// 
        /// Gets the client admin logging section.
        /// 
        /// The client admin logging section.
        public static MyConfigSection MyConfigSection
        {
            get{ return _MyConfigSection; }
        }
        #endregion
    }
}

Next you create the class which represents the actual configuration section you introduced to the web.config. It is through this class that you will be able to access your Foods collection.


using System.Configuration;
namespace MyAssembly
{
    /// 
    /// Represents the section within
    /// the web.config.
    /// 
    public class MyConfigSection : ConfigurationSection
    {
        #region Public Properties
        /// 
        /// Returns a collection of event handler configurations
        /// 
        /// The event handlers.
        [ConfigurationProperty("mylistoffoods")]
        public FoodCollection MyListOfFoods
        {
            get
            {
                return this["mylistoffoods"] as FoodCollection;
            }
        }
        #endregion
    }
}

Next we need to create a class which will represent a food in the collection. Here is the class:


using System.Configuration;
namespace MyAssembly
{
    /// 
    /// Represents the configuration for an event handler 
    /// within the web.config
    /// 
    public class Food : ConfigurationElement
    {
        #region Public Properties
        /// 
        /// Gets the name of the event handler.
        /// 
        /// The name.
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
        /// 
        /// Gets a value indicating whether  I like the food
        /// 
        /// true if like; otherwise, false.
        [ConfigurationProperty("enjoy", IsRequired = true)]
        public bool Enjoy
        {
            get
            {
                return (bool) this["enabled"];
            }
        }
        #endregion
    }
}

Next we create a class to represent a collection of foods. Here is the class:


using System.Configuration;
namespace MyAssembly
{
    /// 
    /// Represents a collection of event handlers pulled
    /// from the web.config
    /// 
    public class FoodCollection : ConfigurationElementCollection
    {
        #region Overrides of ConfigurationElementCollection
        /// 
        /// When overridden in a derived class, creates a new .
        /// 
        /// 
        /// A new .
        /// 
        protected override ConfigurationElement CreateNewElement()
        {
            return new EventHandler();
        }
        /// 
        /// Gets the element key for a specified configuration element when overridden in a derived class.
        /// 
        /// 
        /// An  that acts as the key for the specified .
        /// 
        /// The  to return the key for. 
        ///                 
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((EventHandler) element).Name;
        }
        #endregion
    }
}

Well that’s all there is to it now within your components code you simply call your Configuration Helper and pull the food collection and use the foods as you need to.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s