Wednesday, December 11, 2013

Adding a simple custom section in App.config c#

In App.config: you need to set up a configSections / sectionGroup sections, then you can add your custom sections below appSettings:

xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="EpicSettings">
      <section name="EpicVersions" type="System.Configuration.DictionarySectionHandler"/>
    </sectionGroup>
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  <appSettings>
    <add key="rootLevel" value="C:\Program Files (x86)\Epic"/>
    
    <add key="drFltr" value="Interconnect-*"/>
    <add key="DevVersion" value="Interconnect-DEV"/>

    <add key="CmdBldr" value="CommandBuilder.exe"/>
    <add key="CnfgEdt" value="ConfigEditor.exe"/>
    <add key="TrcVw" value="TraceViewer.exe"/>

    <add key="GnrlCnfg" value="\Web\App_Data\Config\General.config"/>

    <add key="WbSvPxyBldrSubDir" value="\Tools\"/>
    <add key="WbSvPxyBldr" value="WebServiceProxyBuilder.exe"/>

    <add key="PhsGenSvcSubDir" value="\Web\bin\"/>

  </appSettings>
  
  <EpicSettings>
    <EpicVersions>
      <add key="v7.9" value="Epic 2012"/>
      <add key="v8.1" value="Epic 2014"/>
    </EpicVersions>
  </EpicSettings>

</configuration>



In code:  Here is one way to access your custom section in the code:  Here we’re trying to determine the Epic Version based on if the directory path contains a string matching one of the config keys.

private string getEpicVersion(string vrsnpth)
        {
            string ret = string.Empty;
 
            var epicVersions = (ConfigurationManager.GetSection("EpicSettings/EpicVersions"as System.Collections.Hashtable)
                 .Cast()
                 .ToDictionary(n => n.Key.ToString(), n => n.Value.ToString());
 
            foreach (System.Collections.Generic.KeyValuePair<stringstring> vrsn in epicVersions)
            {
                if (vrsnpth.ToLower().Contains(vrsn.Key.ToLower()))
                {
                    ret = vrsn.Value;
                    break;
                }
 
            }
 
            return ret;
        }





No comments: