ConfigurationElementCollection Class
Updated: September 2008
Represents a configuration element containing a collection of child elements.
Assembly: System.Configuration (in System.Configuration.dll)
The ConfigurationElementCollection represents a collection of elements within a configuration file.
Note: |
|---|
An element within a configuration file refers to a basic XML element or a section. A simple element is an XML tag with related attributes, if any. A simple element constitutes a section. Complex sections can contain one or more simple elements, a collection of elements, and other sections. |
You use the ConfigurationElementCollection to work with a collection of ConfigurationElement objects. Implement this class to add collections of custom ConfigurationElement elements to a ConfigurationSection.
Notes to Implementers:You can use a programmatic or a declarative (attributed) coding model to create a custom configuration element.
The programmatic model requires that for each element attribute you create a property to get and set its value, and that you add it to the internal property bag of the underlying ConfigurationElement base class.
The declarative model, also referred to as the attributed model, allows you to define an element attribute by using a property and configuring it with attributes. These attributes instruct the ASP.NET configuration system about the property types and their default values. ASP.NET can use reflection to obtain this information and then create the element property objects and perform the required initialization.
The following example shows how to implement a custom ConfigurationElementCollection class. The example consists of the following files:
The custom ConfigurationElementCollection class.
A custom ConfigurationSection class for a section that contains the custom collection.
A custom ConfigurationElement class that defines the elements that are contained in the collection.
A Main method for running the example as a console application.
An app.config file.
Imports System Imports System.Configuration Imports System.Collections Public Class UrlsCollection Inherits ConfigurationElementCollection Public Sub New() ' Add one url to the collection. This is ' not necessary; could leave the collection ' empty until items are added to it outside ' the constructor. Dim url As UrlConfigElement = _ CType(CreateNewElement(), UrlConfigElement) ' Add the element to the collection. Add(url) End Sub 'New Public Overrides ReadOnly Property CollectionType() _ As ConfigurationElementCollectionType Get Return ConfigurationElementCollectionType.AddRemoveClearMap End Get End Property Protected Overloads Overrides Function CreateNewElement() _ As ConfigurationElement Return New UrlConfigElement() End Function 'CreateNewElement Protected Overloads Overrides Function CreateNewElement( _ ByVal elementName As String) _ As ConfigurationElement Return New UrlConfigElement(elementName) End Function 'CreateNewElement Protected Overrides Function GetElementKey( _ ByVal element As ConfigurationElement) As [Object] Return CType(element, UrlConfigElement).Name End Function 'GetElementKey Public Shadows Property AddElementName() As String Get Return MyBase.AddElementName End Get Set(ByVal value As String) MyBase.AddElementName = value End Set End Property Public Shadows Property ClearElementName() As String Get Return MyBase.ClearElementName End Get Set(ByVal value As String) MyBase.ClearElementName = value End Set End Property Public Shadows ReadOnly Property RemoveElementName() As String Get Return MyBase.RemoveElementName End Get End Property Public Shadows ReadOnly Property Count() As Integer Get Return MyBase.Count End Get End Property 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) ' Add custom code here. End Sub 'Add Protected Overrides Sub BaseAdd( _ ByVal element As ConfigurationElement) BaseAdd(element, False) ' Add custom code here. 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
Imports System Imports System.Configuration Imports System.Collections ' Define a custom section containing an individual ' element and a collection of elements. Public Class UrlsSection Inherits ConfigurationSection <ConfigurationProperty("name", _ DefaultValue:="MyFavorites", _ IsRequired:=True, _ IsKey:=False), _ StringValidator( _ InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", _ MinLength:=1, MaxLength:=60)> _ Public Property Name() As String Get Return CStr(Me("name")) End Get Set(ByVal value As String) Me("name") = value End Set End Property ' Declare an element (not in a collection) of the type ' UrlConfigElement. In the configuration ' file it corresponds to <simple .... />. <ConfigurationProperty("simple")> _ Public ReadOnly Property Simple() _ As UrlConfigElement Get Dim url As UrlConfigElement = _ CType(Me("simple"), _ UrlConfigElement) Return url End Get End Property ' Declare a collection element represented ' in the configuration file by the sub-section ' <urls> <add .../> </urls> ' Note: the "IsDefaultCollection = false" ' instructs the .NET Framework to build a nested ' section like <urls> ...</urls>. <ConfigurationProperty("urls", _ IsDefaultCollection:=False)> _ Public ReadOnly Property Urls() _ As UrlsCollection Get Dim urlsCollection _ As UrlsCollection = _ CType(Me("urls"), UrlsCollection) Return urlsCollection End Get End Property Protected Overrides Sub DeserializeSection( _ ByVal reader As System.Xml.XmlReader) MyBase.DeserializeSection(reader) ' Enter your custom processing code here. End Sub 'DeserializeSection Protected Overrides Function SerializeSection( _ ByVal parentElement As ConfigurationElement, _ ByVal name As String, _ ByVal saveMode As ConfigurationSaveMode) As String Dim s As String = _ MyBase.SerializeSection(parentElement, _ name, saveMode) ' Enter your custom processing code here. Return s End Function 'SerializeSection End Class 'UrlsSection
Imports System Imports System.Configuration Imports System.Collections Public Class UrlConfigElement Inherits ConfigurationElement ' Constructor allowing name, url, and port to be specified. Public Sub New(ByVal newName As String, _ ByVal newUrl As String, _ ByVal newPort As Integer) Name = newName Url = newUrl Port = newPort End Sub 'New ' Default constructor, will use default values as defined Public Sub New() End Sub 'New ' Constructor allowing name to be specified, will take the ' default values for url and port. Public Sub New(ByVal elementName As String) Name = elementName End Sub 'New <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 Fix(Me("port")) End Get Set(ByVal value As Integer) Me("port") = value End Set End Property Protected Overrides Sub DeserializeElement(ByVal reader _ As System.Xml.XmlReader, _ ByVal serializeCollectionKey As Boolean) MyBase.DeserializeElement(reader, _ serializeCollectionKey) ' Enter your custom processing code here. End Sub 'DeserializeElement Protected Overrides Function SerializeElement(ByVal writer _ As System.Xml.XmlWriter, _ ByVal serializeCollectionKey As Boolean) As Boolean Dim ret As Boolean = _ MyBase.SerializeElement(writer, serializeCollectionKey) ' Enter your custom processing code here. Return ret End Function 'SerializeElement Protected Overrides Function IsModified() As Boolean Dim ret As Boolean = MyBase.IsModified() ' Enter your custom processing code here. Return ret End Function 'IsModified End Class 'UrlConfigElement
' Set Assembly name to ConfigurationElement ' and set Root namespace to Samples.AspNet Imports System Imports System.Configuration Imports System.Collections Class TestConfigurationElement ' Entry point for console application that reads the ' app.config file and writes to the console the ' URLs in the custom section. Shared Sub Main(ByVal args() As String) ' Get the current configuration file. Dim config As System.Configuration.Configuration = _ ConfigurationManager.OpenExeConfiguration( _ ConfigurationUserLevel.None) ' Get the MyUrls section. Dim myUrlsSection As UrlsSection = _ config.GetSection("MyUrls") If myUrlsSection Is Nothing Then Console.WriteLine("Failed to load UrlsSection.") Else Console.WriteLine("The 'simple' element of app.config:") Console.WriteLine(" Name={0} URL={1} Port={2}", _ myUrlsSection.Simple.Name, _ myUrlsSection.Simple.Url, _ myUrlsSection.Simple.Port) Console.WriteLine("The urls collection of app.config:") Dim i As Integer For i = 0 To myUrlsSection.Urls.Count - 1 Console.WriteLine(" Name={0} URL={1} Port={2}", _ i, myUrlsSection.Urls(i).Name, _ myUrlsSection.Urls(i).Url, _ myUrlsSection.Urls(i).Port) Next i End If Console.ReadLine() End Sub End Class
<configuration>
<configSections>
<section name="MyUrls" type="Samples.AspNet.UrlsSection, ConfigurationElement, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" />
</configSections>
<MyUrls name="MyFavorites">
<simple name="Microsoft1" url="http://www.microsoft1.com" port="1" />
<urls>
<clear />
<add name="Microsoft2" url="http://www.microsoft2.com" port="2" />
<add name="Contoso" url="http://www.contoso.com" port="8080" />
</urls>
</MyUrls>
</configuration>
System.Configuration.ConfigurationElement
System.Configuration.ConfigurationElementCollection
System.Configuration.ConnectionStringSettingsCollection
System.Configuration.KeyValueConfigurationCollection
System.Configuration.NameValueConfigurationCollection
System.Configuration.ProviderSettingsCollection
System.Configuration.SettingElementCollection
System.Net.Configuration.AuthenticationModuleElementCollection
System.Net.Configuration.BypassElementCollection
System.Net.Configuration.ConnectionManagementElementCollection
System.Net.Configuration.WebRequestModuleElementCollection
System.Runtime.Serialization.Configuration.DeclaredTypeElementCollection
System.Runtime.Serialization.Configuration.ParameterElementCollection
System.Runtime.Serialization.Configuration.TypeElementCollection
System.ServiceModel.Configuration.ServiceModelConfigurationElementCollection(Of ConfigurationElementType)
System.Web.Configuration.AssemblyCollection
System.Web.Configuration.AuthorizationRuleCollection
System.Web.Configuration.BufferModesCollection
System.Web.Configuration.BuildProviderCollection
System.Web.Configuration.ClientTargetCollection
System.Web.Configuration.CodeSubDirectoriesCollection
System.Web.Configuration.CompilerCollection
System.Web.Configuration.ConvertersCollection
System.Web.Configuration.CustomErrorCollection
System.Web.Configuration.EventMappingSettingsCollection
System.Web.Configuration.ExpressionBuilderCollection
System.Web.Configuration.FormsAuthenticationUserCollection
System.Web.Configuration.HttpHandlerActionCollection
System.Web.Configuration.HttpModuleActionCollection
System.Web.Configuration.NamespaceCollection
System.Web.Configuration.OutputCacheProfileCollection
System.Web.Configuration.ProfileGroupSettingsCollection
System.Web.Configuration.ProfilePropertySettingsCollection
System.Web.Configuration.ProfileSettingsCollection
System.Web.Configuration.RuleSettingsCollection
System.Web.Configuration.SqlCacheDependencyDatabaseCollection
System.Web.Configuration.TagMapCollection
System.Web.Configuration.TagPrefixCollection
System.Web.Configuration.TransformerInfoCollection
System.Web.Configuration.TrustLevelCollection
System.Web.Configuration.UrlMappingCollection
System.Web.Mobile.DeviceFilterElementCollection
System.Web.Services.Configuration.ProtocolElementCollection
System.Web.Services.Configuration.SoapExtensionTypeElementCollection
System.Web.Services.Configuration.TypeElementCollection
System.Web.Services.Configuration.WsiProfilesElementCollection
System.Web.UI.MobileControls.ControlElementCollection
System.Web.UI.MobileControls.DeviceElementCollection
System.Workflow.Runtime.Configuration.WorkflowRuntimeServiceElementCollection
System.Xml.Serialization.Configuration.SchemaImporterExtensionElementCollection
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.
Note: