Custom configuration section

четверг, 31 июля 2008 г. ·

Have you ever saw such situation? You open web.config or app.config file trying to find some setting and get to huge list of AppSettings values? You may say that this is ok. I can't agree with you.

AppSettings section is good for small amount of settings. When number of settings begins to grow you should think about grouping settings into custom sections. You have already seen custom sections: ConnectionStrings, AppSettings, Complitation and etc.

It's easy to create custom configuration section. First of all i would like to say that i'm not going to pay attention to all details of section creation. I'm going to show you how you can create simple section and use it. More information can be found in MSDN.

Let's start!

We are going to create section which stores list of pages which require HTTPS protocol. Here is what I would like to have:
I will need three objects to read this information from configuration file:

  • Configuration section element. This element is container of settings. In my sample it corresponds to tag httpsSection
  • Configuration element collection. This is going to be a list of page urls. This collection uses patterns tag.
  • Configuration element. This element stores information about pattern. It's tag is add because it's a part of collection.
I think we should start from the simplies element of this list. This is pattern collection item. Here is a source code of this class:

using System.Configuration;

namespace Business.HttpsRedirect.Configuration
{
public class PatternElement : ConfigurationElement
{
[ConfigurationProperty("pattern", IsRequired = false)]
public string Pattern
{
get { return this["pattern"] as string; }
}
}
}
As you can see it's very simple. You should page attention to base class. It's ConfigurationElement. Also you should no forget about ConfigurationProperyAttribute.
This attribute contains other properties so you may get more information in MSDN.

Next we going to create configuration element collection:

using System.Configuration;

namespace Business.HttpsRedirect.Configuration
{
/// <summary>
/// List of configuration elements
/// </summary>
public class PatternElementCollection : ConfigurationElementCollection
{
/// <summary>
/// Creates the configuration element programmatically.
/// </summary>
/// <returns>The configuration element.</returns>
protected override ConfigurationElement CreateNewElement()
{
return new PatternElement();
}

/// <summary>
/// Gets the configuration element identifier.
/// </summary>
/// <param name="element">The configuration element.</param>
/// <returns>The configuration element identifier.</returns>
protected override object GetElementKey(ConfigurationElement element)
{
return ((PatternElement)element).Pattern;
}

/// <summary>
/// Matches the HTTPS pattern.
/// </summary>
/// <param name="url">The URL.</param>
public bool MatchesHttpsPattern(string url)
{
foreach (PatternElement pattern in this)
{
if (url.IndexOf(pattern.Pattern.ToLower().Trim()) >= 0)
return true;
}
return false;
}
}
}

You should pay attention to overridden methods. One method create instance of collection item (CreateNewElement) here we may put name of desired class. In our case we going to put PatternElement. The second method (GetElementKey) should return key for specified object. We are going to use pattern as a key. Last method (MatchesHttpsPattern) is simple check for url it maches some pattern. This method may be removed.

Last thing we need to do is to create configuration section. Here is a code for this section:



using System.Configuration;

namespace Business.HttpsRedirect.Configuration
{
/// <summary>
/// Provides information on https redirection.
/// </summary>
public class HttpsRedirectSection : ConfigurationSection
{
#region Properties

/// <summary>
/// Gets the patterns.
/// </summary>
/// <value>The patterns.</value>
[ConfigurationProperty("patterns")]
private PatternElementCollection Patterns
{
get { return this["patterns"] as PatternElementCollection; }
}

/// <summary>
/// Gets the configuration section.
/// </summary>
/// <returns>The configuration section.</returns>
private static HttpsRedirectSection GetConfig()
{
return ConfigurationManager.GetSection("httpsSection") as HttpsRedirectSection;
}

#endregion

#region Public Methods

/// <summary>
/// Matches the HTTPS pattern.
/// </summary>
/// <param name="url">The URL.</param>
public static bool MatchesHttpsPattern(string url)
{
return GetConfig().Patterns.MatchesHttpsPattern(url);
}

#endregion
}
}

All what is necessary for this class is Patterns property and attribute applied to this property. All other methods were created to simplify section usage.

Ok. What's next? We have code for configuration section but how can we let application know about this section? It should be registered in configuration file. Here is how it look like:



<configuration>
<configSections>
<section name="httpsSection" type="Business.HttpsRedirect.Configuration.HttpsRedirectSection, Business"/>
</configSections>

<httpsSection>
<patterns>
<add pattern="/UserArea/"/>
<add pattern="/AdminArea/"/>
<add pattern="/Newsletters/"/>
<add pattern="/Basket.aspx"/>
<add pattern="/Checkout.aspx"/>
<add pattern="/Track-Order.aspx"/>
<add pattern="/LogIn.aspx"/>
<add pattern="/Phone-Me.aspx"/>
<add pattern="/Request-For-Quote.aspx"/>
</patterns>
</httpsSection>

I have to register section in configurationSection of config file. Section name should match section tag name (httpsSection).

Conclusion: Here is description of steps which allow you to create simple and light-weight section to store related settings. Use custom section instead of making AppSettings to big

Обо мне

Моя фотография
Кто к нам с чем и зачем, тот от того и того!