Export (0) Print
Expand All
14 out of 20 rated this helpful - Rate this topic

ConfigurationCollectionAttribute Class

Declaratively instructs the .NET Framework to create an instance of a configuration element collection. This class cannot be inherited.

Namespace:  System.Configuration
Assembly:  System.Configuration (in System.Configuration.dll)
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Property)]
public sealed class ConfigurationCollectionAttribute : Attribute

You use the ConfigurationCollectionAttribute attribute to decorate a ConfigurationElementCollection element. This instructs the .NET Framework to create an instance of the collection and to initialize it using your custom ConfigurationElement values.

NoteNote:

The simplest way to create a custom configuration element is to use the attributed (declarative) model. You declare the elements and decorate them with the ConfigurationCollectionAttribute attribute. For each element marked with this attribute, the .NET Framework uses reflection to read the decorating parameters and create a related ConfigurationElementCollection instance. You can also use the programmatic model. In this case it is your responsibility to declare the custom public collection but also to override the ConfigurationElementCollection member and return the properties collection.

The .NET Framework configuration system provides attribute types that you can use during the creation of custom configuration elements. There are two kinds of attributes:

The following example shows how to use the ConfigurationCollectionAttribute.

This example consists of three classes: UrlsSection, UrlsCollection and UrlConfigElement.The UrlsSection class uses the ConfigurationCollectionAttribute to define a custom configuration section. This section contains a URL collection (defined by the UrlsCollection class) of URL elements (defined by the UrlConfigElement class). When you run the example, an instance of the UrlsSection class is created and the following configuration elements are generated in the application configuration file:

<configuration>
    <configSections>
        <section name="MyUrls" type="UrlsSection, 
          ConfigurationCollectionAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </configSections>
    <MyUrls>
        <urls>
            <remove name="Contoso" />
            <add name="Contoso" url="http://www.contoso.com" port="0" />
        </urls>
    </MyUrls>
</configuration
using System;
using System.Configuration;


// Define a custom section that contains a custom 
// UrlsCollection collection of custom UrlConfigElement elements. 
// This class shows how to use the ConfigurationCollectionAttribute. 
public class UrlsSection : ConfigurationSection
{
    // Declare the Urls collection property using the 
    // ConfigurationCollectionAttribute. 
    // This allows to build a nested section that contains 
    // a collection of elements.
    [ConfigurationProperty("urls", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(UrlsCollection),
        AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]
    public UrlsCollection Urls
    {
        get
        {
            UrlsCollection urlsCollection =
                (UrlsCollection)base["urls"];
            return urlsCollection;
        }
    }

}

// Define the custom UrlsCollection that contains the  
// custom UrlsConfigElement elements. 
public class UrlsCollection : ConfigurationElementCollection
{
    public UrlsCollection()
    {
        UrlConfigElement url = (UrlConfigElement)CreateNewElement();
        Add(url);
    }

    public override ConfigurationElementCollectionType CollectionType
    {
        get
        {
            return ConfigurationElementCollectionType.AddRemoveClearMap;
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new UrlConfigElement();
    }

    protected override Object GetElementKey(ConfigurationElement element)
    {
        return ((UrlConfigElement)element).Name;
    }

    public UrlConfigElement this[int index]
    {
        get
        {
            return (UrlConfigElement)BaseGet(index);
        }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(index, value);
        }
    }

    new public UrlConfigElement this[string Name]
    {
        get
        {
            return (UrlConfigElement)BaseGet(Name);
        }
    }

    public int IndexOf(UrlConfigElement url)
    {
        return BaseIndexOf(url);
    }

    public void Add(UrlConfigElement url)
    {
        BaseAdd(url);
    }
    protected override void BaseAdd(ConfigurationElement element)
    {
        BaseAdd(element, false);
    }

    public void Remove(UrlConfigElement url)
    {
        if (BaseIndexOf(url) >= 0)
            BaseRemove(url.Name);
    }

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

    public void Remove(string name)
    {
        BaseRemove(name);
    }

    public void Clear()
    {
        BaseClear();
    }
}

// Define the custom UrlsConfigElement elements that are contained  
// by the custom UrlsCollection. 
// Notice that you can change the default values to create new default elements. 
public class UrlConfigElement : ConfigurationElement
{
    public UrlConfigElement(String name, String url)
    {
        this.Name = name;
        this.Url = url;
    }

    public UrlConfigElement()
    {

        this.Name = "Contoso";
        this.Url = "http://www.contoso.com";
        this.Port = 0;
    }

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

    [ConfigurationProperty("url", DefaultValue = "http://www.contoso.com",
        IsRequired = true)]
    [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
    public string Url
    {
        get
        {
            return (string)this["url"];
        }
        set
        {
            this["url"] = value;
        }
    }

    [ConfigurationProperty("port", DefaultValue = (int)0, IsRequired = false)]
    [IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)]
    public int Port
    {
        get
        {
            return (int)this["port"];
        }
        set
        {
            this["port"] = value;
        }
    }
}
using System;
using System.Configuration;


class UsingConfigurationCollectionAttribute
{

    // Create a custom section and save it in the  
    // application configuration file. 
    static void CreateCustomSection()
    {
        try
        {

            // Create a custom configuration section.
            UrlsSection myUrlsSection = new UrlsSection();

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Add the custom section to the application 
            // configuration file. 
            if (config.Sections["MyUrls"] == null)
            {
                config.Sections.Add("MyUrls", myUrlsSection);
            }


            // Save the application configuration file.
            myUrlsSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Modified);

            Console.WriteLine("Created custom section in the application configuration file: {0}",
                config.FilePath);
            Console.WriteLine();

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateCustomSection: {0}", err.ToString());
        }

    }

    static void ReadCustomSection()
    {
        try
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Read and display the custom section.
            UrlsSection myUrlsSection =
               ConfigurationManager.GetSection("MyUrls") as UrlsSection;

            if (myUrlsSection == null)
                Console.WriteLine("Failed to load UrlsSection.");
            else
            {
                Console.WriteLine("URLs defined in the configuration file:");
                for (int i = 0; i < myUrlsSection.Urls.Count; i++)
                {
                    Console.WriteLine("  Name={0} URL={1} Port={2}",
                        myUrlsSection.Urls[i].Name,
                        myUrlsSection.Urls[i].Url,
                        myUrlsSection.Urls[i].Port);
                }
            }

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString());
        }

    }

    static void Main(string[] args)
    {

        // Get the name of the application.
        string appName =
            Environment.GetCommandLineArgs()[0];

        // Create a custom section and save it in the  
        // application configuration file.
        CreateCustomSection();

        // Read the custom section saved in the 
        // application configuration file.
        ReadCustomSection();

        Console.WriteLine();
        Console.WriteLine("Enter any key to exit.");

        Console.ReadLine();
    }
}
System.Object
  System.Attribute
    System.Configuration.ConfigurationCollectionAttribute
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.