Monday, April 6, 2009

Retrieve and Manipulate Configuration (file) Information's

For example, we had below configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DefaultConnectionKey" value="DevSystem" />
</appSettings>
<connectionStrings>
<add name="DevSystem" providerName="System.Data.SqlClient"
connectionString="data source=(local)\sqlexpress;initial catalog=SomeDB;integrated security=SSPI;persist security info=False" />
</connectionStrings>
</configuration>

How to get "DefaultConnectionKey" value?

We can use ConfigurationManager class (already available on .NET 2.0), so that easy.
That also happen when we need to get the information's about our connection strings.

But, how if we had other section that not default on .NET configuration. Section that we create by design or runtime?

Still using ConfigurationManager class from .NET and some class on System.Xml, I create some mechanism as generic that possible to retrieve and manipulate configuration information's using sectionName.

Below are the code to retrieve the configuration information's:
  1: /// <summary>Get section of specified section name and attributes</summary>
  2: /// <author>Stevanus Ronald</author><date>Tuesday, March 31, 2009</date>
  3: /// <example>This sample shows how to call the <c>GetSection</c> method.<code>
  4: /// string sectionName = "connectionSets";
  5: /// List<string> attributes = new List<string>();
  6: /// attributes.Add("key");
  7: /// attributes.Add("value");
  8: /// SortedDictionary<string, Dictionary<string, string>> sectionSettings = csDotNetConfiguration.GetSection(sectionName, attributes);
  9: /// </code></example>
 10: /// <param name="sectionName">Section name.</param>
 11: /// <param name="attributes">Attributes on section.</param>
 12: /// <returns>Sorted dictionary that represent Outer XML; and Dictionary of params attributes, on tag [configuration >> {sectionName}]. 
 13: /// Return NULL if sectionName parameter not exists on configuration.</returns>
 14: public static SortedDictionary<string, Dictionary<string, string>> GetSection(string sectionName, List<string> attributes)
 15: {
 16:     SortedDictionary<string, Dictionary<string, string>> result = null;
 17:
 18:     if (!String.IsNullOrEmpty(sectionName))
 19:     {
 20:         Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 21:         ConfigurationSection configSection = config.Sections.Get(sectionName);
 22:         if (configSection != null)
 23:         {
 24:             result = new SortedDictionary<string, Dictionary<string, string>>();
 25:                    
 26:             XmlDocument document = new XmlDocument();
 27:             try { document.LoadXml(configSection.SectionInformation.GetRawXml()); }
 28:             catch (XmlException xmlEx)
 29:             {
 30:                 csDotNetConfiguration.HandleException(xmlEx);
 31:                 document = null;
 32:             }
 33:
 34:             if (document != null)
 35:             {
 36:                 XmlNode parentNode = document.SelectSingleNode(sectionName);
 37:                 foreach (XmlNode childNode in parentNode.ChildNodes)
 38:                 {
 39:                     Dictionary<string, string> dictAttribute = new Dictionary<string, string>();
 40:                     foreach (XmlAttribute xmlAttribute in childNode.Attributes)
 41:                     {
 42:                         bool isAttributeContains = true;
 43:                         if (attributes.Count > 0)
 44:                         isAttributeContains = attributes.Contains(xmlAttribute.Name);
 45:
 46:                         if (isAttributeContains)
 47:                             dictAttribute.Add(xmlAttribute.Name, xmlAttribute.Value);
 48:                     }
 49:                            
 50:                     if (dictAttribute.Count > 0)
 51:                         result.Add(childNode.OuterXml, dictAttribute);                               
 52:                 }
 53:             }
 54:         }
 55:     }
 56:
 57:     return result;
 58: }
And, below the code to manipulate the configuration information's:
  1: /// <summary>Set section with specified attributes.</summary>
  2: /// <author>Stevanus Ronald</author><date>Tuesday, March 31, 2009</date>
  3: /// <example>This sample shows how to call the <c>SetSection</c> method.
  4: /// <code>
  5: /// //Set exists sectionName with specified attribute where not exists
  6: /// string sectionName = "connectionSets";
  7: /// Dictionary<string, string> dictAttribute = new Dictionary<string, string>();
  8: /// dictAttribute.Add("key", "SomeDatabase");
  9: /// dictAttribute.Add("value", "Some Database (SQL Server 2005)");
 10: /// csDotNetConfiguration.SetSection(sectionName, dictAttribute);
 11: /// </code>
 12: /// <code>
 13: /// //Set exists sectionName with specified attribute where exists
 14: /// string sectionName = "connectionSets";
 15: /// Dictionary<string, string> dictAttribute = new Dictionary<string, string>();
 16: /// dictAttribute.Add("key", "DevSystem");
 17: /// dictAttribute.Add("value", "Development System (SQL Server 2005)");
 18: /// csDotNetConfiguration.SetSection(sectionName, dictAttribute);
 19: /// </code>
 20: /// <code>
 21: /// //Set not exists sectionName with specified attribute
 22: /// string sectionName = "SomeServices";
 23: /// Dictionary<string, string> dictAttribute = new Dictionary<string, string>();
 24: /// dictAttribute.Add("id", "Ronald.EmailAutomation");
 25: /// dictAttribute.Add("description", "Email Automation Windows Services");
 26: /// csDotNetConfiguration.SetSection(sectionName, dictAttribute);
 27: /// </code>
 28: /// </example>
 29: /// <param name="sectionName">Section name.</param>
 30: /// <param name="dictAttributes">Represents a collection of key/attribute and value.</param>
 31: public static void SetSection(string sectionName, Dictionary<string, string> dictAttributes)
 32: {
 33:     if (!String.IsNullOrEmpty(sectionName) && dictAttributes.Count > 0)
 34:     {
 35:         Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 36:         ConfigurationSection configSection = config.GetSection(sectionName);
 37:
 38:         //If sectionName not available then create new section.
 39:         if (configSection == null)
 40:         {
 41:             configSection = new DefaultSection();
 42:             configSection.SectionInformation.SetRawXml(csDotNetConfiguration.GetDefaultSectionRawXml(sectionName));
 43:             config.Sections.Add(sectionName, configSection);
 44:
 45:             try { config.Save(); }
 46:             catch (ConfigurationErrorsException configErrEx) { csDotNetConfiguration.HandleException(configErrEx); }
 47:         }
 48:
 49:         if (configSection != null)
 50:         {
 51:             XmlDocument document = new XmlDocument();
 52:             try { document.LoadXml(configSection.SectionInformation.GetRawXml()); }
 53:             catch (XmlException xmlEx)
 54:             {
 55:                 csDotNetConfiguration.HandleException(xmlEx);
 56:                 document = null;
 57:             }
 58:
 59:             if (document != null)
 60:             {
 61:                 XmlNode foundChildNode = null;
 62:                 string prefix = String.Empty;
 63:                 string localName = csDotNetConfiguration.LocalNameXmlNode;
 64:                        
 65:                 XmlNode parentNode = document.SelectSingleNode(sectionName);
 66:                 foreach (XmlNode childNode in parentNode.ChildNodes)
 67:                 {
 68:                     bool isContain = false;
 69:
 70:                     //Check all attribute of childNode
 71:                     foreach (XmlAttribute xmlAttribute in childNode.Attributes)
 72:                     {
 73:                         if (dictAttributes.ContainsKey(xmlAttribute.Name)
 74:                             && csString.Compare(dictAttributes[xmlAttribute.Name], xmlAttribute.Value, true))
 75:                         {
 76:                             isContain = true;
 77:                         }
 78:                     }
 79:
 80:                     prefix = childNode.Prefix;
 81:                     localName = childNode.LocalName;
 82:                                
 83:                     if (isContain)
 84:                     {
 85:                         foundChildNode = childNode;
 86:                         break;
 87:                     }
 88:                 }
 89:
 90:                 if (foundChildNode != null)
 91:                     parentNode.RemoveChild(foundChildNode);
 92:
 93:                 XmlNode newChildNode = document.CreateNode(XmlNodeType.Element, prefix, localName, document.NamespaceURI);
 94:                 foreach (string attributeKey in dictAttributes.Keys)
 95:                 {
 96:                     XmlAttribute attr = document.CreateAttribute(attributeKey);
 97:                     attr.Value = dictAttributes[attributeKey];
 98:                     newChildNode.Attributes.Append(attr);
 99:                 }
100:                 parentNode.AppendChild(newChildNode);
101:
102:                 configSection.SectionInformation.SetRawXml(document.InnerXml);
103:                 try { config.Save(); }
104:                 catch (ConfigurationErrorsException configErrEx) { csDotNetConfiguration.HandleException(configErrEx); }
105:             }
106:         }               
107:     }
108: }
109: 
Have fun coding!

1 comment:

  1. Updated method on manipulate the configuration information's
    Previous:
    38: //If sectionName not available then create new section.
    39: if (configSection == null)
    40: {
    41: configSection = new DefaultSection();
    42: configSection.SectionInformation.SetRawXml(csDotNetConfiguration.GetDefaultSectionRawXml(sectionName));
    43: config.Sections.Add(sectionName, configSection);
    44:
    45: try { config.Save(); }
    46: catch (ConfigurationErrorsException configErrEx) { csDotNetConfiguration.HandleException(configErrEx); }
    47: }

    After:
    38: //If sectionName not available then create new section.
    39: if (configSection == null)
    40: {
    41: configSection = new DefaultSection();
    42: configSection.SectionInformation.SetRawXml(csDotNetConfiguration.GetDefaultSectionRawXml(sectionName));
    43: configSection.SectionInformation.Type = typeof(NameValueSectionHandler).AssemblyQualifiedName;
    44: config.Sections.Add(sectionName, configSection);
    45: try { config.Save(); }
    46: catch (ConfigurationErrorsException configErrEx) { csDotNetConfiguration.HandleException(configErrEx); }
    47: }

    ReplyDelete