.Net (2.0, 3.0, 3.5), C#, Asp.net, Com+, GIS(ESRI Software), Management, Analysis & Design, Life, Trips, And more...
It's a best practice to work with strong types instead of typing the name of the class/properties by our own hands. One of the common places that we are usually typing a string is when we're retrieving data from configuration file. In this post I will show you how to declare a custom configuration section with a strongly typed class.
1. Declare the configuration section in configuration file:
<configSections>
<section name="serviceSettings" type="ServiceSettingsHandler"></section>
</configSections>
2. Add the configuration section with its data:
<serviceSettings>
<service Assembly="asm1" Class="class1"/>
<service Assembly="asm2" Class="class2"/>
<service Assembly="asm3" Class="class3"/>
</serviceSettings>
3. Add a new class that will represent the service definition (assembly & class name):
public class ServiceSetting
{
public ServiceSetting(string className, string assembly)
{
_Class = className;
_Assembly = assembly;
}
private string _Class;
public string Class
{
get { return _Class; }
}
private string _Assembly;
public string Assembly
{
get { return _Assembly; }
}
}
4. Add a handler class. This class must implement the IConfigurationSectionHandler interface. This interface includes only one method that calls "Create", which creates a configuration section handler. The handler class look like this:
public class ServiceSettingsHandler : IConfigurationSectionHandler
{
#region IConfigurationSectionHandler Members
public object Create(object parent, object configContext,
System.Xml.XmlNode section)
{
List<ServiceSetting> list = new List<ServiceSetting>();
foreach (XmlNode service in section.ChildNodes)
{
list.Add(new ServiceSetting(service.Attributes
["Class"].Value , service.Attributes
["Assembly"].Value));
}
return list ;
}
#endregion
} 5. The last thing we should do is to create a wrapper class to work with strongly types. The class should looks like this:
public class ServiceConfigurationManager
{
private ServiceConfigurationManager() { }
public static List<ServiceSetting> GetServices()
{
return (List<ServiceSetting>)ConfigurationManager.
GetSection("serviceSettings");
}
}
And now let's write some code that will use this custom configuration handler:
protected void GetCustomConfigSectionDate_Click(object sender, EventArgs e)
{
List<ServiceSetting> list =
ServiceConfigurationManager.GetServices();
Services.DataSource = list;
Services.DataBind();
} And the result is:
