C# - Custom Configuration Reader

This code snippet demonstrates how to read configuration data from a CSS like configuration file. Each configuration section is encapsulated in curly braces. Sections can be cloned and properties can be overwritten.

Config

  1. /* Create a new section */  
  2. @dev {  
  3.     DbHost : localhost  
  4.     DbName : dbname  
  5.     DbUid : root  
  6.     DbPwd : pass  
  7. }  
  8.  
  9. /* Clone the dev section and name it live */  
  10. @clone {  
  11.     live : dev  
  12. }  
  13.  
  14. /* Overwrite the DbHost property of the live section */  
  15. @live {  
  16.     DbHost : remote.db.com  
  17. } 

Program.cs

  1. using System;  
  2.  
  3. namespace xConfigurationDemo  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             xConfiguration config = new xConfiguration("config.cf");  
  10.  
  11.             /* Get a property by section name and property name */  
  12.             Console.WriteLine(config.GetProperty("dev""DbHost"));  
  13.  
  14.             /* Get a list of properties for a section */  
  15.             var dev = config.GetSection("dev");  
  16.  
  17.             Console.ReadKey();  
  18.         }  
  19.     }  
  20. } 

xConfiguration.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.IO;  
  5. using System.Text.RegularExpressions;  
  6.  
  7. class xConfiguration : Dictionary<stringDictionary<stringstring>>  
  8. {  
  9.     public xConfiguration(string file)  
  10.     {  
  11.         string configData;  
  12.  
  13.         using (StreamReader reader = new StreamReader(file))  
  14.         {  
  15.             configData = reader.ReadToEnd();  
  16.  
  17.             Regex regx = new Regex(@"@.*?{.*?\n}"RegexOptions.Singleline);  
  18.             MatchCollection mCollection = regx.Matches(configData);  
  19.  
  20.             foreach (Match match in mCollection)  
  21.             {  
  22.                 string matchStr = match.ToString();  
  23.                 string sectionName = matchStr.Substring(1, matchStr.IndexOf("{") - 1).Trim();  
  24.  
  25.                 string sectionBlock = matchStr.Substring(matchStr.IndexOf("{") + 1, matchStr.LastIndexOf("}") - matchStr.IndexOf("{") - 1).Trim();  
  26.  
  27.                 string[] strProperties = sectionBlock.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);  
  28.  
  29.                 Dictionary<stringstring> propertyCollection = new Dictionary<stringstring>();  
  30.  
  31.                 foreach (string strPoperty in strProperties)  
  32.                 {  
  33.                     string[] propertyValuePair = strPoperty.Split(new string[] { ":" }, 2, StringSplitOptions.RemoveEmptyEntries);  
  34.  
  35.                     if (propertyValuePair.Length == 2)  
  36.                     {  
  37.                         string propertyName = propertyValuePair[0].Trim();  
  38.                         string propertyValue = propertyValuePair[1].Trim();  
  39.  
  40.                         propertyCollection.Add(propertyName, propertyValue);  
  41.                     }  
  42.                     else  
  43.                     {  
  44.                         throw new Exception(string.Format("Property/value error ({0}) ", propertyValuePair[0].Trim()));  
  45.                     }  
  46.                 }  
  47.  
  48.                 if (this.ContainsKey(sectionName))  
  49.                 {  
  50.                     Dictionary<stringstring> collection = this[sectionName];  
  51.  
  52.                     foreach (KeyValuePair<stringstring> pair in propertyCollection)  
  53.                     {  
  54.                         collection[pair.Key] = pair.Value;  
  55.                     }  
  56.  
  57.                 }  
  58.                 else  
  59.                 {  
  60.                     this[sectionName] = propertyCollection;  
  61.                 }  
  62.  
  63.                 Dictionary<stringstring> cfcollection;  
  64.  
  65.                 switch (sectionName)  
  66.                 {  
  67.                     case "clone":  
  68.                         cfcollection = this[sectionName];  
  69.  
  70.                         foreach (KeyValuePair<stringstring> item in cfcollection)  
  71.                         {  
  72.                             this[item.Key] = new Dictionary<stringstring>(this[item.Value]);  
  73.                         }  
  74.  
  75.                         this.Remove("clone");  
  76.                         break;  
  77.  
  78.                     case "import":  
  79.                         cfcollection = this[sectionName];  
  80.  
  81.                         foreach (KeyValuePair<stringstring> item in cfcollection)  
  82.                         {  
  83.                             xConfiguration newConfig;  
  84.  
  85.                             try  
  86.                             {  
  87.                                 newConfig = new xConfiguration(item.Value);  
  88.                             }  
  89.                             catch(FileNotFoundException e)  
  90.                             {  
  91.                                 throw new Exception(string.Format("Unable to import configuration file. {0}", e.Message));   
  92.                             }  
  93.  
  94.                             if (item.Key == "*")  
  95.                             {  
  96.                                 List<string> sections = newConfig.GetSectionNames;  
  97.  
  98.                                 foreach (string imSectionName in sections)  
  99.                                 {  
  100.                                     this[imSectionName] = new Dictionary<stringstring>(newConfig.GetSection(imSectionName));  
  101.                                 }  
  102.                             }  
  103.                             else  
  104.                             {  
  105.                                 this[item.Key] = new Dictionary<stringstring>(newConfig.GetSection(item.Key));  
  106.                             }  
  107.                         }  
  108.  
  109.                         this.Remove("import");  
  110.                         break;  
  111.                 }  
  112.             }  
  113.         }  
  114.     }  
  115.  
  116.     public string GetProperty(string sectionName, string propertyName)  
  117.     {  
  118.         try  
  119.         {  
  120.             return this[sectionName][propertyName];  
  121.         }  
  122.         catch  
  123.         {  
  124.             throw new Exception("Section or property does not exist");  
  125.         }  
  126.     }  
  127.  
  128.     public Dictionary<stringstringGetSection(string sectionName)  
  129.     {  
  130.         try  
  131.         {  
  132.             return this[sectionName];  
  133.         }  
  134.         catch  
  135.         {  
  136.             throw new Exception("Section does not exist");  
  137.         }  
  138.     }  
  139.  
  140.     public List<stringGetSectionNames  
  141.     {  
  142.         get  
  143.         {  
  144.             return this.Keys.ToList<string>();  
  145.         }  
  146.     }  
  147. } 

No comments:

Post a Comment