ConfigurationHandler snippet

This is a small snippet for the basics of writing a ConfigurationHandler to read a configuration section from your web.config or app.config.

You start off with the XML definition in the config file:

<configSections>
    <section name="mysection" type="MyNamespace.ConfigurationHandler,Mynamespace" />
</configSections>

<mysection>
    <security enabled="true" />
    <username>bob</username>
</mysection>

And then define your own parser class, and a Settings class to store the details in:

public class ConfigurationHandler : IConfigurationSectionHandler
{
    #region IConfigurationSectionHandler Members
    /// <summary>
    /// Creates a <see cref="Settings"/> object from the configuration file.
    /// </summary>
    /// <seealso cref="Settings"/>
    public object Create(object parent, object configContext, System.Xml.XmlNode section)
    {
    	if (section == null)
    		throw new ArgumentNullException("'section' is null. Check your app.config or web.config exists and is valid.");

    	try
    	{
    		Settings settings = new Settings();

    		// Security
    		XmlNode node = section.SelectSingleNode("//security");
    		if (node != null)
    			Settings.Security = (node.Attributes["enabled"].Value == "true");
    		else
    			throw new Exception("No security node could be found in the web/app.config");


    		// Username
    		node = section.SelectSingleNode("//username");
    		if (node != null)
    			settings.Username = node.Value;
    		else
    			throw new Exception("No username could be found in the web/app.config");		

    		return settings;
    	}
    	catch (XPathException ex)
    	{
    		// Catch From SelectSingleNode,SelectNodes
    		throw new Exception("XPathException caught when reading config file", ex);
    	}
    }

    #endregion
}

public class Settings
{
    public bool Security { get;set; }
    public string Username { get;set; }
}

And then when you application first initializes, read the settings like so:

var settings = (Settings)ConfigurationManager.GetSection("mysection");

An alternative way of doing this is to make the Settings class responsible for initializing itself inside a static constructor, using the above line. You would then make the Settings class a singleton.

Last updated on 01 January 2010

Comments

blog comments powered by Disqus