System.Configuration Namesp ...


.NET Framework Class Library
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)
Syntax

Visual Basic (Declaration)
<AttributeUsageAttribute(AttributeTargets.Class Or AttributeTargets.Property)> _
Public NotInheritable Class ConfigurationCollectionAttribute _
    Inherits Attribute
Visual Basic (Usage)
Dim instance As ConfigurationCollectionAttribute
C#
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Property)]
public sealed class ConfigurationCollectionAttribute : Attribute
Visual C++
[AttributeUsageAttribute(AttributeTargets::Class|AttributeTargets::Property)]
public ref class ConfigurationCollectionAttribute sealed : public Attribute
JScript
public final class ConfigurationCollectionAttribute extends Attribute
Remarks

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:

Examples

The following example shows how to use the ConfigurationCollectionAttribute.

The example consists of an app.config file and four classes. The app.config file has a custom section that contains a collection of elements that store URLs and associated data. The class TestingConfigurationCollectionAttribute reads the app.config file and writes the contents of the custom section to the console. The other classes define the custom section, collection, and elements. The custom section type UrlsSection contains a Urls property. This property is a custom collection of type UrlsCollection that contains custom elements of type UrlConfigElement. The Urls property is marked with the ConfigurationCollectionAttribute.

None
<configuration>
  <configSections>
    <section name="MyUrls" type="Samples.AspNet.UrlsSection, ConfigurationCollectionAttribute" />
  </configSections>
  <MyUrls>
    <urls>
      <clear />
      <add name="Microsoft" url="http://www.microsoft.com" port="0" />
      <add name="Contoso" url="http://contoso.com" port="1" />
    </urls>
  </MyUrls>
</configuration>
Visual Basic
' Set assembly name to "ConfigurationCollectionAttribute", 
' and set root namespace to "Samples.AspNet" to match the
' section declaration in the sample app.config file.
' Set startup object to "TestingConfigurationCollectionAttribute".
Imports System
Imports System.Configuration

Class TestingConfigurationCollectionAttribute

    Shared Sub Main()
        ' Call ConfigurationManager to read the custom UrlsSection
        ' of the app.config file and put its contents into an 
        ' instance of the custom class created for it.
        Dim myUrlsSection As UrlsSection = _
            ConfigurationManager.GetSection("MyUrls")

        If myUrlsSection Is Nothing Then
            Console.WriteLine("Failed to load UrlsSection.")
        Else
            Console.WriteLine("URLS defined in app.config:")
            Dim i As Integer
            For i = 0 To myUrlsSection.Urls.Count - 1
                Console.WriteLine("  Name={0} URL={1} Port={2}", _
                myUrlsSection.Urls(i).Name, _
                myUrlsSection.Urls(i).Url, _
                myUrlsSection.Urls(i).Port)
            Next i
        End If
        Console.ReadLine()
    End Sub 'Main

End Class

' Define a custom section named UrlsSection containing a
' UrlsCollection collection of UrlConfigElement elements.
' The collection is wrapped in an element named "urls" in the
' app.config file.
' UrlsCollection and UrlsConfigElement classes are defined below.
Public Class UrlsSection
    Inherits ConfigurationSection

    ' Declare the urls collection property.
    ' Note: the "IsDefaultCollection = false" instructs 
    '.NET Framework to build a nested section of 
    'the kind <urls> ...</urls>.
    <ConfigurationProperty("urls", _
        IsDefaultCollection:=False), _
        ConfigurationCollection(GetType(UrlsCollection), _
        AddItemName:="add", _
        ClearItemsName:="clear", _
        RemoveItemName:="remove")> _
    Public ReadOnly Property Urls() As UrlsCollection
        Get
            Dim urlCollection As UrlsCollection = _
            CType(MyBase.Item("urls"), UrlsCollection)
            Return urlCollection
        End Get
    End Property

End Class 'UrlsSection 

' Define the UrlsCollection that will contain the 
' UrlsConfigElement elements.
Public Class UrlsCollection
    Inherits ConfigurationElementCollection

    Public Sub New()
        ' When the collection is created, always add one element 
        ' with the default values. (This is not necessary; it is
        ' here only to illustrate what can be done; you could 
        ' also create additional elements with other hard-coded 
        ' values here.)
        Dim url As UrlConfigElement = _
        CType(CreateNewElement(), UrlConfigElement)
        Add(url)
    End Sub 'New

    Public Overrides ReadOnly Property CollectionType() _
    As ConfigurationElementCollectionType
        Get
            Return ConfigurationElementCollectionType.AddRemoveClearMap
        End Get
    End Property

    Protected Overrides Function CreateNewElement() _
    As ConfigurationElement
        Return New UrlConfigElement()
    End Function 'CreateNewElement

    Protected Overrides Function GetElementKey(ByVal element _
    As ConfigurationElement) As [Object]
        Return CType(element, UrlConfigElement).Name
    End Function 'GetElementKey

    Default Public Shadows Property Item( _
    ByVal index As Integer) As UrlConfigElement
        Get
            Return CType(BaseGet(index), UrlConfigElement)
        End Get
        Set(ByVal value As UrlConfigElement)
            If Not (BaseGet(index) Is Nothing) Then
                BaseRemoveAt(index)
            End If
            BaseAdd(index, value)
        End Set
    End Property

    Default Public Shadows ReadOnly Property Item( _
    ByVal Name As String) As UrlConfigElement
        Get
            Return CType(BaseGet(Name), UrlConfigElement)
        End Get
    End Property

    Public Function IndexOf(ByVal url _
    As UrlConfigElement) As Integer
        Return BaseIndexOf(url)
    End Function 'IndexOf

    Public Sub Add(ByVal url As UrlConfigElement)
        BaseAdd(url)
    End Sub 'Add

    Protected Overrides Sub BaseAdd(ByVal element _
    As ConfigurationElement)
        BaseAdd(element, False)
    End Sub 'BaseAdd

    Public Overloads Sub Remove(ByVal url _
    As UrlConfigElement)
        If BaseIndexOf(url) >= 0 Then
            BaseRemove(url.Name)
        End If
    End Sub 'Remove

    Public Sub RemoveAt(ByVal index As Integer)
        BaseRemoveAt(index)
    End Sub 'RemoveAt

    Public Overloads Sub Remove(ByVal name As String)
        BaseRemove(name)
    End Sub 'Remove

    Public Sub Clear()
        BaseClear()
    End Sub 'Clear
End Class 'UrlsCollection 

' Define the element type contained by the UrlsCollection
' collection.
Public Class UrlConfigElement
    Inherits ConfigurationElement

    Public Sub New(ByVal name As String, ByVal url As String)
        Me.Name = name
        Me.Url = url
    End Sub 'New

    Public Sub New()
    End Sub

    <ConfigurationProperty("name", _
    DefaultValue:="Microsoft", _
    IsRequired:=True, _
    IsKey:=True)> _
    Public Property Name() As String
        Get
            Return CStr(Me("name"))
        End Get
        Set(ByVal value As String)
            Me("name") = value
        End Set
    End Property

    <ConfigurationProperty("url", _
    DefaultValue:="http://www.microsoft.com", _
    IsRequired:=True), _
    RegexStringValidator("\w+:\/\/[\w.]+\S*")> _
    Public Property Url() As String
        Get
            Return CStr(Me("url"))
        End Get
        Set(ByVal value As String)
            Me("url") = value
        End Set
    End Property

    <ConfigurationProperty("port", _
    DefaultValue:=0, IsRequired:=False), _
    IntegerValidator(MinValue:=0, _
    MaxValue:=8080, ExcludeRange:=False)> _
   Public Property Port() As Integer
        Get
            Return CInt(Me("port"))
        End Get
        Set(ByVal value As Integer)
            Me("port") = value
        End Set
    End Property
End Class 'UrlConfigElement 
C#
// Set assembly name to "ConfigurationCollectionAttribute" to match
// the section declaration in the sample app.config file.
using System;
using System.Configuration;


namespace Samples.AspNet
{
    class TestingConfigurationCollectionAttribute
    {
        static void Main(string[] args)
        {
            // Call ConfigurationManager to read the custom UrlsSection
            // of the app.config file and put its contents into an 
            // instance of the custom class created for it.
            UrlsSection myUrlsSection =
               ConfigurationManager.GetSection("MyUrls") as UrlsSection;

            if (myUrlsSection == null)
                Console.WriteLine("Failed to load UrlsSection.");
            else
            {
                Console.WriteLine("URLs defined in app.config:");
                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);
                }
            }
            Console.ReadLine();
        }
    }

    // Define a custom section named UrlsSection containing a
    // UrlsCollection collection of UrlConfigElement elements.
    // The collection is wrapped in an element named "urls" in the
    // app.config file.
    // UrlsCollection and UrlsConfigElement classes are defined below.
    public class UrlsSection : ConfigurationSection
    {
        // Declare the urls collection property.
        // Note: the "IsDefaultCollection = false" instructs 
        // .NET Framework to build a nested section of 
        // the kind <urls>...</urls>.
        [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 UrlsCollection that will contain the UrlsConfigElement
    // elements.
    public class UrlsCollection : ConfigurationElementCollection
    {
        public UrlsCollection()
        {
            // When the collection is created, always add one element 
            // with the default values. (This is not necessary; it is
            // here only to illustrate what can be done; you could 
            // also create additional elements with other hard-coded 
            // values here.)
            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 element type contained by the UrlsCollection
    // collection.
    public class UrlConfigElement : ConfigurationElement
    {
        public UrlConfigElement(String name, String url)
        {
            this.Name = name;
            this.Url = url;
        }

        public UrlConfigElement()
        {
            // Attributes on the properties provide default values.
        }

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

        [ConfigurationProperty("url", DefaultValue = "http://www.microsoft.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;
            }
        }
    }
}
Inheritance Hierarchy

System..::.Object
  System..::.Attribute
    System.Configuration..::.ConfigurationCollectionAttribute
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Platforms

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.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0
See Also

Reference

Tags :


Community Content

Thomas Lee
Port number in sample restricted up to 8080
The port number restriction 0-8080 in this sample obviously represents a completely arbitrary set of boundaries that's not related to the actual TCP port range.
Tags : contentbug

Page view tracker