Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Custom Configuration Sections Example - .NET Framework

RSS
Modified on Fri, Sep 06, 2013, 9:34 AM by Administrator Categorized as ·Net Framework

Overview

This article explains how to implement a custom configuration section in your app.config or web.config file.

Process

1. Set a reference to System.Configuration

2. Create your custom configuration class, inheriting from System.Configuration.ConfigurationSection.

3. "Register" the custom section in your config file

4. Create the custom section in your config file.

Sample Code

Usage

static void Main(string[] args)
{
    var settings = CustomConfig.Settings;
    var someString = settings.SomeString;
    var someInteger = settings.SomeInteger;

    foreach (EmailRecipient item in settings.EmailRecipients)
    {
        Debug.Print(item.AddressExt);
    }
}

Custom Configuration Class

using System;
using System.Configuration;
using System.Diagnostics;

namespace ConsoleApplication1
{
    public class CustomConfig : ConfigurationSection
    {
        /*== Singleton Members ==================================================================*/
        /* Prevent instantiation of this class -- except via static constructor. */
        private CustomConfig() { }

        static CustomConfig()
        {
            try
            {
                Settings = ConfigurationManager.GetSection("CustomConfigGroup/CustomConfig") as CustomConfig;
            }
            catch (Exception ex)
            {
                var s = ex.Recurse();
                Debug.Print(s);
                throw;
            }
        }

        public static CustomConfig Settings { get; private set; }

        /*== Instance Members ===================================================================*/
        [ConfigurationProperty("someInteger", DefaultValue = 20, IsRequired = false)]
        [IntegerValidator(MinValue = 1, MaxValue = 100)]
        public int SomeInteger
        {
            get { return (int)this["someInteger"]; }
            set { this["someInteger"] = value; }
        }

        [ConfigurationProperty("someString", IsRequired = true)]
        [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;’\"|\\", MaxLength = 256)]
        public string SomeString
        {
            get { return (string)this["someString"]; }
            set { this["someString"] = value; }
        }

        [ConfigurationProperty("font")]
        public FontElement Font
        {
            get
            {
                return (FontElement)this["font"];
            }
            set
            { this["font"] = value; }
        }

        [ConfigurationProperty("emailRecipients")]
        public EmailRecipientCollection EmailRecipients
        {
            get { return (EmailRecipientCollection)this["emailRecipients"]; }
            set { this["emailRecipients"] = value; }
        }
        
    }

    /*===========================================================================================*/
    public class FontElement : ConfigurationElement
    {
        [ConfigurationProperty("name", DefaultValue = "Arial", IsRequired = true)]
        [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
        public String Name
        {
            get
            {
                return (String)this["name"];
            }
            set
            {
                this["name"] = value;
            }
        }

        [ConfigurationProperty("size", DefaultValue = "12", IsRequired = false)]
        [IntegerValidator(ExcludeRange = false, MaxValue = 24, MinValue = 6)]
        public int Size
        {
            get
            { return (int)this["size"]; }
            set
            { this["size"] = value; }
        }
    }

    /*===========================================================================================*/
    public class EmailRecipient : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired=false)]
        public string Name
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }

        [ConfigurationProperty("address", IsRequired = true, IsKey = true)]
        public string Address
        {
            get { return (string)this["address"]; }
            set { this["address"] = value; }
        }

        public string AddressExt
        {
            get
            {
                if (string.IsNullOrWhiteSpace(Name))
                    return Address;

                return Name + " <" + Address + ">";
            }
        }
    }

    /*===========================================================================================*/
    public class EmailRecipientCollection : ConfigurationElementCollection
    {
        public EmailRecipient this[int index]
        {
            get { return (EmailRecipient)BaseGet(index);}
            set
            {
                if (BaseGet(index) != null)
                    BaseRemoveAt(index);
                BaseAdd(index, value);
            }
        }
        public void Add(EmailRecipient item)
        {
            BaseAdd(item);
        }
        public void Clear()
        {
            BaseClear();
        }
        protected override ConfigurationElement CreateNewElement()
        {
            return new EmailRecipient();
        }

        protected override object GetElementKey(ConfigurationElement item)
        {
            return ((EmailRecipient)item).Address;
        }

        public void Remove(EmailRecipient item)
        {
            BaseRemove(item.Address);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        public void Remove(string name)
        {
            BaseRemove(name);
        }
    }
    /*===========================================================================================*/
    public class EmailRecipientsConfigurationSection : ConfigurationSection
    {
        [ConfigurationProperty("EmailRecipients", IsDefaultCollection=false)]
        [ConfigurationCollection(typeof(EmailRecipientCollection), AddItemName="add", ClearItemsName="clear",RemoveItemName="remove")]
        public EmailRecipientCollection EmailRecipients
        {
            get { return (EmailRecipientCollection)base["EmailRecipients"]; }
        }
    }
}

App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="CustomConfigGroup">
      <section name="CustomConfig" type="ConsoleApplication1.CustomConfig, ConsoleApplication1"/>
    </sectionGroup>
  </configSections>
  <CustomConfigGroup>
    <CustomConfig someInteger="5" someString="Hello world">
      <font name="TimesNewRoman" size="18"/>
      <emailRecipients>
        <add name="Patrick Jasinski" address="patrick.jasinski@soltech.net" />
        <add name="Rob Farmer" address="rob.farmer@soltech.net" />
      </emailRecipients>
    </CustomConfig>
  </CustomConfigGroup>
</configuration>

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.