Sunday, December 7, 2014

How to Create Custom Configuration Sections Using ConfigurationSection

In the below configuration file, a CustomSettingsGroup is been added. which is having two groups defined, EmailSettings and ServiceSettings. It is same like appSettings.
The only benefit is, you can group the settings information into relevant group rather than putting all into appSettings.

I found is useful when number of configuration settings are more and needs to be categorized for easy maintenance and readability.

In the GetValue mehod just specify the group you want to read from. 

public string GetValue(this string key)
        {
            NameValueCollection group = (NameValueCollection)ConfigurationManager.GetSection("CustomSettingsGroup/ServiceSettings");
            if (group != null)
                return group[key].ToString();
            else
                return "";
        }


xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="CustomSettingsGroup">
      <section name="ServiceSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      <section name="EmailSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
   </sectionGroup>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

  <connectionStrings>
  </connectionStrings>


  <CustomSettingsGroup>

    <EmailSettings>
      <add key="MyEmailSettingsKey" value="MyEmailSettingsKeyValue"/>
    </EmailSettings>

    <ServiceSettings>
      <add key="MyServiceSettingsKey" value=" MyServiceSettingsKeyValue" />
    </ServiceSettings>
  </CustomSettingsGroup>

  <appSettings>
  </appSettings>
</configuration>



No comments:

Post a Comment