Tuesday, December 16, 2008

Creating a configuration section

In general, a lot of application are using the appSettings section of a config file for storing application parameters. A major drawback of this practice, is the lack of prior knowledge about the format and default value of these parameters, so you need to program all this functionality yourself.
A better way to provide your application with configuration values, is the use of a configuration section. Instead of using the appSettings node, you can specify your own.
The key to your own configuration section is the System.Configuration namespace.
You write your own class, but should inherit ConfigurationSection.
Now you can spice up your properties in this class with the ConfigurationProperty attribute. Validation can be programmed with the attributes
  • IntegerValidatorAttribute
  • LongValidatorAttribute
  • RegexStringValidatorAttribute
  • StringValidatorAttribute
  • TimeSpanValidatorAttribute


For example:

public class TestConfigurationSection : ConfigurationSection
{
// Empty Construct
public TestConfigurationSection() { }

// default string property
[ConfigurationProperty("deliveryStore", IsRequired = true)]
public string DeliveryStore
{
get
{
return (string)this["deliveryStore"];
}
set
{
this["deliveryStore"] = value;
}
}
//uri types will work too
[ConfigurationProperty("serviceUrl", DefaultValue = "http://192.168.1.10/MessageService", IsRequired = false)]
public Uri ServiceUrl
{
get
{
return (Uri)this["serviceUrl"];
}
set
{
this["serviceUrl"] = value;
}
}

[ConfigurationProperty("timeOut", DefaultValue = "0:00:20")]
[TimeSpanValidator(MinValueString = "0:00:05", MaxValueString = "0:05:00", ExcludeRange = false)]
public TimeSpan TimeOut
{
get
{
return (TimeSpan)this["timeOut"];
}
set
{
this["timeOut"] = value;
}
}
}


To use this configuration section in your config, you need to add it to the configsections node, for instance:

<configSections>
<section name="testConfig" type="NJV.Utils.TestConfigurationSection, NJV.Utils"/>
</configSections>
<testConfig
deliveryStore="D:\Test"
serviceUrl="http://10.0.0.9/MessageService"
timeOut="0:00:20"
/>


Now you've the settings defined and validation setup. To read these values, you can use the following code:

TestConfigSection config = (TestConfigSection)System.Configuration.ConfigurationManager.GetSection("testConfig");
TimeSpan timeout = config.TimeOut;
string deliveryLocation = config.DeliveryStore;
Uri serviceLocation = config.ServiceUrl;


The only drawback here is, you should be sure to have a testConfig section defined in your config, and it should be of the correct type. So maybe there could be some type and null reference checking on line 1:

TestConfigSection config = System.Configuration.ConfigurationManager.GetSection("testConfig") as TestConfigSection;
if (config==null)
{
throw new ApplicationException("No configuration available");
}

No comments:

Share