ConfigurationCollectionAttribute Class

Note: This class is new in the .NET Framework version 2.0.

Declaratively instructs the .NET Framework to instantiate a configuration element collection. This class cannot be inherited.

Namespace: System.Configuration
Assembly: System.Configuration (in system.configuration.dll)

'Declaration
<AttributeUsageAttribute(AttributeTargets.Class Or AttributeTargets.Property)> _
Public NotInheritable Class ConfigurationCollectionAttribute
	Inherits Attribute
'Usage
Dim instance As ConfigurationCollectionAttribute

/** @attribute AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Property) */ 
public final class ConfigurationCollectionAttribute extends Attribute
AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Property) 
public final class ConfigurationCollectionAttribute extends Attribute

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

NoteNote

The simplest way of creating 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.

The example contains four classes. The class TestingConfigurationCollectionAttribute creates a custom configuration section containing a collection of elements. The remaining three classes are used to create the custom section. The custom section type UrlsSection contains an Urls property. This property is a custom collection of type UrlsCollection containing custom elements of type UrlConfigElement. Note that the key for this example to work is the Urls property, decorated with the ConfigurationCollectionAttribute.

Imports System
Imports System.Configuration


' Define a property section named <urls>
' containing a UrlsCollection collection of 
' UrlConfigElement elements.
' This section requires the definition of UrlsCollection and
' UrlsConfigElement types.

Public Class UrlsSection
   Inherits ConfigurationSection
   ' Declare the collection element.
   Private url As UrlConfigElement
   
   Public Sub New()
      ' Create a collection element.
      ' The property values assigned to 
      ' this instance are provided
      ' by the ConfigurationProperty attributes
      ' associated wiht the UrlConfigElement 
      ' properties.
      url = New UrlConfigElement()
   End Sub 'New
   
   ' 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:="addUrl", _
    ClearItemsName:="clearUrls", _
    RemoveItemName:="RemoveUrl")> _
    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()
        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(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(index As Integer)
      BaseRemoveAt(index)
   End Sub 'RemoveAt
   
   Overloads Public Sub Remove(name As String)
      BaseRemove(name)
   End Sub 'Remove
   
   Public Sub Clear()
      BaseClear()
   End Sub 'Clear
End Class 'UrlsCollection 

' Define the UrlConfigElement for the 
' types contained by the UrlsSection.
Public Class UrlConfigElement
   Inherits ConfigurationElement
   
   Public Sub New(name As String, 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


Class TestingConfigurationCollectionAttribute
   
   Shared Sub ShowUrls()
      
      Try
            Dim myUrlsSection As UrlsSection = _
            ConfigurationManager.GetSection("MyUrls")
         
            If myUrlsSection Is Nothing Then
                Console.WriteLine("Failed to load UrlsSection.")
            Else
                Console.WriteLine("My URLs:")
                Dim i As Integer
                For i = 0 To myUrlsSection.Urls.Count - 1
                    Console.WriteLine("  #{0 {1: {2", i, _
                    myUrlsSection.Urls(i).Name, _
                    myUrlsSection.Urls(i).Url + " port " + _
                    myUrlsSection.Urls(i).Port.ToString())
                Next i
            End If
      Catch e As Exception
         Console.WriteLine(e.ToString())
      End Try
   End Sub 'ShowUrls
   
   
   ' Create the custom section.
   ' It will contain a nested section as 
   ' defined by the UrlsSection (<urls>...</urls>).
   Shared Sub CreateSection(sectionName As String)
      ' Get the current configuration (file).
        Dim config As System.Configuration.Configuration = _
        ConfigurationManager.OpenExeConfiguration( _
        ConfigurationUserLevel.None)
      
      Dim urlsSection As UrlsSection
      
      ' Create an entry in the <configSections>. 
      If config.Sections(sectionName) Is Nothing Then
         urlsSection = New UrlsSection()
         config.Sections.Add(sectionName, urlsSection)
         config.Save()
      End If
      
      ' Create the actual target section and write it to 
      ' the configuration file.
        If config.Sections(("/configuration/" + sectionName)) _
        Is Nothing Then
            urlsSection = config.GetSection(sectionName) '
             urlsSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Full)
        End If
   End Sub 'CreateSection
   
   
    Public Overloads Shared Sub Main(ByVal args() As String)
        Console.WriteLine("[Current URLs]")
        CreateSection("MyUrls")
        ShowUrls()
        Console.ReadLine()
    End Sub 'Main

End Class 'TestingConfigurationCollectionAttribute

The following is an excerpt of the configuration file containing the custom section as defined in the previous sample.

<configuration>
  <configSections>
    <section name="MyUrls" 
      type="Samples.AspNet.UrlsSection, 
      ConfigurationCollectionAttribute, Version=1.0.0.0, 
      Culture=neutral, PublicKeyToken=null" />
  </configSections>
  <MyUrls>
    <urls>
      <clear />
      <add name="Microsoft" url="http://www.microsoft.com" port="0" />
    </urls>
  </MyUrls>
</configuration>

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 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

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

.NET Framework

Supported in: 2.0

Community Additions

ADD
Show: