How to create custom attribute in web.config

1. Add a class file in AppCode with any name and add the following code
--------------------------------------------------------------------------

public class FeedElement : ConfigurationElement
{
    [ConfigurationProperty("Key", IsKey = true, IsRequired = true)]
    public string Key
    {
        get { return (string)this["Key"]; }
        set { this["Key"] = value; }
    }

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

[ConfigurationCollection(typeof(FeedElement))]
public class FeedElementCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new FeedElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((FeedElement)element).Value;
    }
}

public class FeedRetriever : ConfigurationSection
{
    [ConfigurationProperty("feeds", IsDefaultCollection = true)]
    public FeedElementCollection Feeds
    {
        get { return (FeedElementCollection)this["feeds"]; }
        set { this["feeds"] = value; }
    }
}

------------------------------------------------------------------

2. Add following code in web.config under <configuration> attribute

<configSections>
           <section name="FeedRetriever"  type="FeedRetriever" />
</configSections>
 
 <FeedRetriever>
    <feeds>
           <add Key="Key1" Value="value 1"/>
            <add Key="Key2" Value="value 2"/>
            <add Key="Key3" Value="value 3"/>
    </feeds>
</FeedRetriever>

3. You can get all the keys and value with given code

 FeedRetriever _Config = ConfigurationManager.GetSection("FeedRetriever") as FeedRetriever;
        foreach (FeedElement feedEl in _Config.Feeds)
        {
            Response.Write(feedEl.Value);
        }

---------------------------------
Enjoy the code!!
Thanks
---------------------------------


Comments

Popular posts from this blog

Executing PowerShell scripts from C#

HOW TO Use the NumericUpDown Control

Exposing Agile Software Development Myths