Configuration Section

This code snippet will show you how to use configuration section in C#.

Configuration:


<configuration>
<configSections>
<section name="NotificationConfiguration" type="SendNotification.NotificationConfiguration, SendNotification" />
</configSections>
<NotificationConfiguration>
<Configurations>

<add Key=”Time” Content=”It’s time to book time.”
URL=”https://time.com&#8221;
RoutingTarget=”chp0524″/>
</Configurations>
</NotificationConfiguration>

<startup>
<supportedRuntime version=”v4.0″ sku=”.NETFramework,Version=v4.0″/>
</startup>
</configuration>

Code:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace SendNotification
{

public class NotificationConfiguration : ConfigurationSection
{

[ConfigurationProperty(“Configurations”)]
public ConfigurationCollection Configurations
{
get { return this[“Configurations”] as ConfigurationCollection; }
}
}

public class ConfigurationCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new Configuration();
}

protected override object GetElementKey(ConfigurationElement element)
{
return ((Configuration)element).Key;
}
}

public class Configuration : ConfigurationElement
{

[ConfigurationProperty(“Key”,
IsRequired = true,
IsKey = true)]
public string Key
{
get { return this[“Key”] as string; }
set { this[“Key”] = value; }
}
[ConfigurationProperty(“Content”)]
public string Content
{
get { return this[“Content”] as string; }
set { this[“Content”] = value; }
}
[ConfigurationProperty(“URL”)]
public string URL
{
get { return this[“URL”] as string; }
set { this[“URL”] = value; }
}
[ConfigurationProperty(“RoutingTarget”)]
public string RoutingTarget
{
get { return this[“RoutingTarget”] as string; }
set { this[“RoutingTarget”] = value; }
}

}
}

Usage:

NotificationConfiguration = ((NotificationConfiguration)ConfigurationManager.GetSection("NotificationConfiguration")).Configurations.Cast<Configuration>();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s