Using Generic Custom Section Handler in Config file of your application

Hi All,

For one of my application i needed custom configuration handler. And I have implemented a generic version of it as below.
As you can see we need to first define the custom config modal object as a saperate class as below.
SocketConfig.cs
namespace GenericConfigHandler
{
public class SocketConfig
{
public int PortNumber { get; set; }
public string Name { get; set; }
public string RequestVersionNumber { get; set; }
public List InvalidIpList { get; set; }
}
}

After that we need to provide the configuration handler on file ConfigurationHandler.cs as below.
As you can see the Type T is decided at runtime and based on the configuration values provided in app.config.
the below code deserialize xml data into and object of typeT and returns.

namespace GenericConfigHandler
{
public class ConfigurationHandler : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
XmlNode environmentNode = section.SelectSingleNode("/" + typeof(T).Name);
XmlSerializer ser = new XmlSerializer(typeof(T));
XmlNodeReader reader = new XmlNodeReader(environmentNode);
return ser.Deserialize(reader);
}
}
}

Below is the Config file which contain the Config


XML File
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="SocketConfig" type="GenericConfigHandler.ConfigurationHandler`1[[GenericConfigHandler.SocketConfig, GenericConfigHandler]],
GenericConfigHandler"/>
</configSections>
<SocketConfig>
<PortNumber>2000</PortNumber>
<Name>Listener</Name>
<RequestVersionNumber>1.2</RequestVersionNumber>
<InvalidIpList>
<string>10.51.120.4</string>
<string>10.51.120.5</string>
<string>10.51.6.14</string>
<string>10.51.6.13</string>
</InvalidIpList>
</SocketConfig>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

After that before reading the config file you need to include system.Configuration from GAC as reference into your project and then use the below code to access the configuration data.
using System.Configuration;

SocketConfig config = (SocketConfig)ConfigurationManager.GetSection("SocketConfig");

Comments

Popular posts from this blog

Authorize.net Integration eCommerce Payment Gateway ( Direct Post Method New! )

Get Organised with OneNote

Test your Sql Query Online