Hello people!
I am back with yet another interesting post about something very interesting in ASP.Net – custon configuration sections. Those of you who are familiar with ASP.Net web development will be aware various sections in web.config such as <appSettings /> and <connectionStrings />. These “sections” are supported ASP.Net itself and thus we are able to use these sections to define custom key/value based settings and connection string for our application!
But, what’s the fun in using stuff only provided to us by default? None, isn’t it? Custom configuration sections are there to provide some fun
I was experimenting a few things for sBlog.Net and found custom configuration sections good for maintaining a few settings related to the blog, that rarely change, in the web.config, instead of having them in the database. While thinking about it, I thought why not write a post about them and so here I am with the new post!
So, let me get to the point of this post after that short introduction. I am going to show how I created a new “section” called <sblognet /> that could store some of a blog’s settings that rarely change. Here is the new section I have added to my web.config:
<sblognet smtpAddress="mail.mysite.net"
smtpPassword="password123"
emailErrors="true"
adminEmail="administrator@mysite.net"
blogTheme="PlainClean">
<logging enabled="true" />
</sblognet>
With the help of custom configuration sections, we can create a class that strongly types every attribute or element within the <sblognet /> element! To do this, the first step is to add a new <section /> element within the <configSections /> element in your web.config as shown below:
<configuration>
<configSections>
<!-- snip -->
<section name="sblognet" type="ConfigSectionsSample.Configuration.SblogNetConfiguration, ConfigSectionsSample" />
</configSections>
<!-- snip -->
</configuration>
In the above listing, the name attribute specifies the name of our section, which is sblognet. Then the type attribute specifies the fully-qualified namespace of the type that would represent a strongly typed representation of our custom section followed by the assembly that would contain this type in a comma-seperated format. Now that the “wiring” is done, let me show you the class that represents the custom type itself!
public class SblogNetConfiguration : ConfigurationSection
{
[ConfigurationProperty("smtpAddress", DefaultValue = "")]
public string SmtpAddress
{
get { return (string) this["smtpAddress"]; }
set { this["smtpAddress"] = value; }
}
[ConfigurationProperty("smtpPassword", DefaultValue = "")]
public string SmtpPassword
{
get { return (string)this["smtpPassword"]; }
set { this["smtpPassword"] = value; }
}
[ConfigurationProperty("emailErrors", DefaultValue = false)]
public bool EmailErrors
{
get { return (bool)this["emailErrors"]; }
set { this["emailErrors"] = value; }
}
[ConfigurationProperty("blogTheme", DefaultValue = "PerfectBlemish")]
public string BlogTheme
{
get { return (string)this["blogTheme"]; }
set { this["blogTheme"] = value; }
}
[ConfigurationProperty("adminEmail", DefaultValue = "")]
public string AdminEmail
{
get { return (string)this["adminEmail"]; }
set { this["adminEmail"] = value; }
}
// -- snip --
}
If you observe the listing above for SblogNetConfiguration class, you can immediately notice what’s going on! In listing 1, you noticed that the <sblognet /> element has a number of attributes with the corresponding values. The first attribute/value pair is smtpAddress with the value set to mail.mysite.net. This attribute is represented by the SmtpAddress property in this class, as shown below:
[ConfigurationProperty("smtpAddress", DefaultValue = "")]
public string SmtpAddress
{
get { return (string) this["smtpAddress"]; }
set { this["smtpAddress"] = value; }
}
Note that the property is decorated with the ConfigurationProperty annotation. This implies that this property maps to an attribute name "smtpAddress" in the section named <sblognet />. The get/set methods are pretty straight-forward by which the value in web.config is returned/set. The ConfigurationProperty annotation also has the DefaultValue property that can be used to set a default value, in case this attribute is not present in the <sblognet /> element, in this case I have set it to return an empty string.
Following this property there are other properties that represent other attributes such as smtpPassword, emailErrors, adminEmail, blogTheme and so on.
Now, obviously you noticed that the class does not contain any definition for the <logging /> element that is contained within the <sblognet /> element. That’s because complex elements like these have to be represented by another class themselves! Given below is the listing the highlights the property that maps to this element alone:
public class SblogNetConfiguration : ConfigurationSection
{
// -- snip --
[ConfigurationProperty("logging")]
public LoggingElement Logging
{
get { return (LoggingElement) this["logging"]; }
set { this["logging"] = value; }
}
}
Just like the other properties in the class, I have used ConfigurationProperty data annotation, but without the DefaultValue property, implying if not specified we will get a null. Notice the return type of this property – LoggingElement. This is another class that will represent the logging element within our custom section. The listing for this class is given below:
public class LoggingElement : ConfigurationElement
{
[ConfigurationProperty("enabled", DefaultValue = false)]
public bool Enabled
{
get { return (bool) this["enabled"]; }
set { this["enabled"] = value; }
}
}
Note that this class inherits from the ConfigurationElement unlike the previous class, which inherited from the ConfigurationSection class. As the name implies, this class act as a representation of an element within a custom section. At this point, this element contains a single property called Enabled which is represented as shown above and is similar to other properties within the SblogNetConfiguration class! That’s it! You now have a created a custom section just for your application!!!
Let’s see how to put this in to use. Given below is a section from the HomeController class that utilzes this custom section!
public class HomeController : Controller
{
private static readonly SblogNetConfiguration Configuration =
ConfigurationManager.GetSection("sblognet") as SblogNetConfiguration;
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
ViewData["data"] = Configuration.BlogTheme;
return View();
}
}
The above snippet deserves a very short explanation, even though it’s pretty straight forward. In line 3, I have used ConfigurationMananger.GetSection method provided by ASP.Net to get a reference to the section named “sblognet”. ASP.Net does all the heavy-weight-lifting for us and so we just have to cast it to SblogNetConfiguration. It’s now ready for use, which is proven by line 10 where the BlogTheme property is passed on to the view using ViewData. I am not going to present screenshots or the part where I display it and I am just going to delegate those things to you
Hope this post interested you a bit and for the sake of sanity, here is a link download a sample application that implements things explained in this post!
Happy coding!






