March 14, 2012

Add a custom section in the config

Here is the method if you need to a custom section into you config file.

Here is my example of config that I need to include into my \App_Config\Include folder:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
 <MyCustomSection>
  <MyCustomElement Name="XXX" MyProperty="YYY" />
  <MyCustomElement Name="AAA" MyProperty="BBB" />
 </MyCustomSection>
  </sitecore>
</configuration>

And here is a way to read it:
using System.Collections.Generic;
using Sitecore.Configuration;
using System.Xml;
using Sitecore.Xml;

/// <summary>
/// TODO: Update summary.
/// </summary>
public class MyConfigElement
{
 //The two properties corresponding to the properties into the config
 public string Name { get; set; }
 public string MyProperty { get; set; }

 //The method who return the list of my custom elements
 public static List<MyConfigElement> GetListMyCustomElements()
 {
  List<MyConfigElement> lst = new List<MyConfigElement>();
  
  //Read the configuration nodes
  foreach (XmlNode node in Factory.GetConfigNodes("MyCustomSection/MyCustomElement"))
  {
   //Create a element of this type
   MyConfigElement elem = new MyConfigElement();
   elem.Name = XmlUtil.GetAttribute("Name", node);
   elem.MyProperty = XmlUtil.GetAttribute("MyProperty", node);
   lst.Add(elem);
  }
  return lst;
 }
}

Don’t forget to use a property “Name” to avoid the conflicts in the include folder (see this post: http://sitecoreblog.blogspot.com/2012/02/config-patching-system-for-external.html)

No comments:

Post a Comment

Post a Comment