Add Custom Configuration Elements In .NET

When we talk about configuration file in .NET, the obvious first question, which pops up in our mind is what is a configuration file and why do we actually need it?

According to MSDN, the Configuration files are the XML files that can be changed as needed.The reason why we actually need them is that we can change some data that may be required by the Application without recompiling the Application again.

While working with the .NET application we come across two very common configuration files ie. app.config and web.config. Both these configuration files have a <appSetting/> tag, where we can add the settings related to an application.But appSetting tag allows us to add only key value pair.

  1. <appSettings>  
  2.     <add key="" value=""/>  
  3. </appSettings>  

But there are many scenarios where we want our settings to be something more than just key value pairs.

To overcome this situation, Microsoft provides many classes, which allows us to write our custom configuration section. All the classes related to these are present in System.Configuration dll.In this sample Application, I will show how to create your custom configuration section Group, configuration section, configuration element. In the later part of this sample, I will be showing how to add intellisence to our custom tags in Visual Studio.

First of all, we will create a new class library project and name it as Custom tags.

Now, we will add the reference to System.Configuration to the project.

First of all, we will create a class that represents the innermost element of the custom section. In our case, it is company tag. To create a configuration element, we need to inherit it from ConfigurationElement class. Now, we need to define the attributes of the configuration element. For this, we will create public properties and add a ConfigurationPropertyAttribute to it. This ConfigurationProperty attribute has various parameters like name, DefaultValue, IsKey, IsRequired. The screenshot is given below of the CompanyElement class.

  1. #region Company Element  
  2.     public class CompanyElement : ConfigurationElement  
  3.     {  
  4.         [ConfigurationProperty("name", DefaultValue = "", IsKey = true, IsRequired = true)]  
  5.         public string Name  
  6.         {  
  7.             get { return (string)this["name"]; }  
  8.             set { this["name"] = value; }  
  9.         }  
  10.   
  11.         [ConfigurationProperty("shortName", DefaultValue = "", IsRequired = true)]  
  12.         public string ShortName  
  13.         {  
  14.             get { return (string)this["shortName"]; }  
  15.             set { this["shortName"] = value; }  
  16.         }  
  17.   
  18.         [ConfigurationProperty("companyCode", DefaultValue = "", IsRequired = true)]  
  19.         public string CompanyCode  
  20.         {  
  21.             get { return (string)this["companyCode"]; }  
  22.             set { this["companyCode"] = value; }  
  23.         }  
  24.     }  
  25.     #endregion  

Now, our Company Element is ready. We need to create a collection of type Company Element. To achieve this, we need to create a class CompanyElementCollection, which inherits from ConfigurationElementCollection, which is an abstract class, so we need to provide the implementation of its two abstract methods and will add ConfigurationCollection attribute to it. This ConfigurationCollection attribute has four parameters. First is the type of items, which this collection will contain and the remaining three parameters are AddItemName, ClearItemsName and RemoveItemName. If we don’t supply the AddItemName, we will get add tag instead of company tag.

  1. #region CompanyElement Collection    
  2.     [ConfigurationCollection(typeof(CompanyElement), AddItemName = "company")]    
  3.     public class CompanyElementCollection : ConfigurationElementCollection    
  4.     {    
  5.         protected override ConfigurationElement CreateNewElement()    
  6.         {    
  7.             return new CompanyElement();    
  8.         }    
  9.     
  10.         protected override object GetElementKey(ConfigurationElement element)    
  11.         {    
  12.             return ((CompanyElement)element).Name;    
  13.         }    
  14.     
  15.     }    
  16.     #endregion     

Now, we are done with creating an element and its collection. We will create a new class CompanySection, which inherits from ConfigurationSection. Our CompanySection will contain a public property of type company collection and decorated by an attribute ConfigurationProperty. We will add the name for the property collection and set IsDefaultCollection to true as it is our default collection.

  1. #region Company Section  
  2.     public class CompanySection : ConfigurationSection  
  3.     {  
  4.         [ConfigurationProperty("companies", IsDefaultCollection = true)]  
  5.         public CompanyElementCollection Companies  
  6.         {  
  7.             get { return (CompanyElementCollection)this["companies"]; }  
  8.             set { this["companies"] = value; }  
  9.         }  
  10.     }  
  11.     #endregion  

We can have multiple sections in our Application, which can be grouped into one. To highlight this, I have created one more section.

  1. #region Settings Section  
  2.     public class SettingSection : ConfigurationSection  
  3.     {  
  4.           
  5.         [ConfigurationProperty("countrycode", DefaultValue = "", IsKey = true, IsRequired = true)]  
  6.         public string CountryCode  
  7.         {  
  8.             get { return (string)this["countrycode"]; }  
  9.             set { this["countrycode"] = value; }  
  10.         }  
  11.         [ConfigurationProperty("isenabled", DefaultValue = true, IsRequired = true)]  
  12.         public bool IsEnabled  
  13.         {  
  14.             get { return (bool)this["isenabled"]; }  
  15.             set { this["isenabled"] = value; }  
  16.         }  
  17.   
  18.     }  
  19.     #endregion  

Now, we will create a new class MySectionGroup that inherits from ConfigurationSectionGroup. In this class, we will add two public properties that will return the sections, which we have created.

  1. #region MySection Group  
  2.     public class MySectionGroup : ConfigurationSectionGroup  
  3.     {  
  4.         [ConfigurationProperty("setting", IsRequired = false)]  
  5.         public SettingSection GeneralSettings  
  6.         {  
  7.             get { return (SettingSection)base.Sections["setting"]; }  
  8.         }  
  9.   
  10.         [ConfigurationProperty("companySection", IsRequired = false)]  
  11.         public CompanySection ContextSettings  
  12.         {  
  13.             get { return (CompanySection)base.Sections["companySection"]; }  
  14.         }  
  15.     }  
  16.     #endregion  

Now, we will build our class library project and create its DLL. Once our project builds successfully, we can test it by creating a console Application and add reference of our DLL to it. Open the App.config file and add the configSections, sectionGroup and section to it. We need to specify the name and fully qualified type of all the section and section group.

  1. <configSections>  
  2.   <sectionGroup name="mysection" type="CustomTags.MySectionGroup,CustomTags">  
  3.     <section name="companySection" type="CustomTags.CompanySection,CustomTags"/>  
  4.     <section name="settingSection" type="CustomTags.SettingSection,CustomTags"/>  
  5.   </sectionGroup>  
  6. </configSections>  

Note

configSections must be the first tag inside the configuration element, else you may end up in getting “The parameter 'sectionGroupName' is invalid” when you try to access a section from the code.

Now, we will add our custom tags in App.config file.

  1. <mysection>  
  2.   <settingSection countrycode="US" isenabled='true' />  
  3.   <companySection>  
  4.      <companies>  
  5.     <company name="Microsoft Corporation" shortName="MSFT" companyCode="MSFT"/>  
  6.     <company name="Yahoo" shortName="YHOO" companyCode="YHOO"/>  
  7.   </companies>  
  8.   </companySection>  
  9. </mysection>  

We will now try to access these tags from the code. The code snippet is given below for the same.

  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             MySectionGroup group= ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).SectionGroups["mysection"as MySectionGroup;  
  6.             foreach (ConfigurationSection section in group.Sections)  
  7.             {  
  8.                 Console.WriteLine("\n\n===========================================");  
  9.                 Console.WriteLine(section.SectionInformation.Name.ToUpper());  
  10.                 Console.WriteLine("===========================================");  
  11.                 if (section.GetType() == typeof(CompanySection))  
  12.                 {  
  13.                     CompanySection c = (CompanySection)section;  
  14.                     CompanyElementCollection coll = c.Companies;  
  15.                     foreach (CompanyElement item in coll)  
  16.                     {  
  17.                         Console.WriteLine("|{0,25}| {1,6}| {2,6}|", item.Name, item.ShortName , item.CompanyCode);  
  18.                         Console.WriteLine("-------------------------------------------");  
  19.                     }  
  20.                 }  
  21.                 else if (section.GetType() == typeof(SettingSection))  
  22.                 {  
  23.                     SettingSection s = (SettingSection)section;  
  24.                     Console.WriteLine("|{0,2}| {1,5}| ", s.CountryCode, s.IsEnabled);  
  25.                     Console.WriteLine("-------------------------------------------");  
  26.                 }  
  27.                     
  28.   
  29.             }  
  30.             Console.ReadLine();  
  31.         }  
  32.     }  

Output

We have successfully created a custom section and we are able to access its values from the code but still we have one issue i.e. Visual Studio doesn’t provide intellisense for the tags. This is because Visual Studio does not contain the schema definition for our tags. To do this, we have a simple hack.Open App.config. Go to XML menu item in the menu bar and click Create the schema. This will create xsd file. Copy your element from this file.
  1. <xs:element name="mysection">  
  2.     <xs:complexType>  
  3.       <xs:sequence>  
  4.         <xs:element name="settingSection">  
  5.           <xs:complexType>  
  6.             <xs:attribute name="countrycode" type="xs:string" use="required" />  
  7.             <xs:attribute name="isenabled" type="xs:boolean" use="required" />  
  8.           </xs:complexType>  
  9.         </xs:element>  
  10.         <xs:element name="companySection">  
  11.           <xs:complexType>  
  12.             <xs:sequence>  
  13.               <xs:element name="companies">  
  14.                 <xs:complexType>  
  15.                   <xs:sequence>  
  16.                     <xs:element maxOccurs="unbounded" name="company">  
  17.                       <xs:complexType>  
  18.                         <xs:attribute name="name" type="xs:string" use="required" />  
  19.                         <xs:attribute name="shortName" type="xs:string" use="required" />  
  20.                         <xs:attribute name="companyCode" type="xs:string" use="required" />  
  21.                       </xs:complexType>  
  22.                     </xs:element>  
  23.                   </xs:sequence>  
  24.                 </xs:complexType>  
  25.               </xs:element>  
  26.             </xs:sequence>  
  27.           </xs:complexType>  
  28.         </xs:element>  

Now, add a new schema file to your project and add the code given above in it and save it. Now, again go to App.config properties, browse your schema file and add it.

This will enable intellisense for your custom tags.


Similar Articles