Let us learn the usage and benefits of Custom Section Handler.

Niladri.Biswas
Posted by in C# category on for Beginner level | Points: 250 | Views : 1453 red flag

In this article, we will look into the usage of Custom Section Handler by the help of IConfigurationSectionHandler.


 Download source code for Let us learn the usage and benefits of Custom Section Handler.

Introduction

Sometimes we may need to create our own section handler in the .config file for which we need the help of IConfigurationSectionHandler. This interface handles the access to certain configuration sections.It has only one method "Create" whose signature is as under

object Create(object parent, object configContext, XmlNode section);

The method is responsible for creating a configuration section handler.

This article will show us how to do so with a simple example

Straight to Experiment

Let us create a class say "FileFormat" and expose the below properties

namespace IConfigurationSectionHandlerDemo
{
    public class FileFormat
    {
        public string TableRegex { set; get; }
        public string ProcedureRegex { set; get; }
        public string FunctionRegex { set; get; }
        public string ViewRegex { set; get; }
    }
}

Next create a config entry as under

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>    
    <section name="FileFormat" type="IConfigurationSectionHandlerDemo.FileFormatHandler,IConfigurationSectionHandlerDemo"/>    
  </configSections>

  <FileFormat>    
    <TableRegex>
      <![CDATA[^(?:(dbo|test)\.)([[a-zA-Z0-9_]+)(\.(table)+)(\.(sql)$)]]>
    </TableRegex>
    <ProcedureRegex>
      <![CDATA[^(?:(dbo|test)\.)([[a-zA-Z0-9_]+)(\.(storedprocedure)+)(\.(sql)$)]]>
    </ProcedureRegex>
    <FunctionRegex>
      <![CDATA[^(?:(dbo|test)\.)([[a-zA-Z0-9_]+)(\.(userdefinedfunction)+)(\.(sql)$)]]>
    </FunctionRegex>
    <ViewRegex>
      <![CDATA[^(?:(dbo|test)\.)([[a-zA-Z0-9_]+)(\.(view)+)(\.(sql)$)]]>
    </ViewRegex>
  </FileFormat>
  
</configuration>

Next create a class name "FileFormatHandler" that implements "IConfigurationSectionHandler" interface.This class is responsible to reading the custom config values.

using System.Configuration;
using System.Xml;

namespace IConfigurationSectionHandlerDemo
{
    public class FileFormatHandler : IConfigurationSectionHandler 
    {
        public object Create(object parent, object configuration, XmlNode node)
        {
            FileFormat fileFormatObject = new FileFormat();
            XmlNodeList fileFormatNodes = node.SelectNodes("/FileFormat");
            if (fileFormatNodes == null) return null;
            XmlElement sqlElement = fileFormatNodes[0] as XmlElement;
            if (sqlElement == null) return fileFormatObject;

            for (int item = 0; item < sqlElement.ChildNodes.Count; item++)
            {
                XmlElement xmlElement = sqlElement.ChildNodes[item] as XmlElement;
                if (xmlElement == null) continue;
                switch (xmlElement.Name)
                {  
                    case "TableRegex":
                        fileFormatObject.TableRegex = xmlElement.InnerText;
                        break;
                    case "ProcedureRegex":
                        fileFormatObject.ProcedureRegex = xmlElement.InnerText;
                        break;
                    case "FunctionRegex":
                        fileFormatObject.FunctionRegex = xmlElement.InnerText;
                        break;
                    case "ViewRegex":
                        fileFormatObject.ViewRegex = xmlElement.InnerText;
                        break;
                    default: break;
                }
            }
            return fileFormatObject;
        }
    }
}

The "XMLNode" in the "Create" method contains information about the XML node section.We can get the information about the various "FileFormats" from the "ChildNodes" property

Then for every node, get the element and from there get the name.Inside the switch case, after finding the match, get the value from the innertext of the element.

Please note that, the section "type" value in configuration file is

type="namespace.classname,namespace"

Finally, we need to invoke and test it.

static void Main(string[] args)
{
	try
	{
		var fileFormatValues = ConfigurationManager.GetSection("FileFormat") as FileFormat;
		var SPRegexValue = fileFormatValues.ProcedureRegex;

		var input = "dbo.mystoredprocedure.storedprocedure.sql";
		var result = Regex.IsMatch(input, SPRegexValue, RegexOptions.IgnoreCase);

	}
	catch(Exception ex)
	{
		throw ex;
	}
}

First we are obtaining all the fileFormat value from the "FileFormat" config section by using

ConfigurationManager.GetSection("FileFormat") as FileFormat

Then we are getting the regular expression value for the Store Procedure as under

var SPRegexValue = fileFormatValues.ProcedureRegex;

Finally we are checking if the supplied value matched with the Store Procedure regular expression or not.

Conclusion

Hope we have understood the concept of dealing with a Custom Section Handler with the help of IConfigurationSectionHandler interface.Hope this will be useful.Thanks for reading.Zipped file is attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)