Export (0) Print
Expand All

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)

[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Property)] 
public sealed class ConfigurationCollectionAttribute : Attribute
/** @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.


using System;
using System.Configuration;


namespace Samples.AspNet
{
    

    // 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 : ConfigurationSection
    {
        // Declare the collection element.
        UrlConfigElement url;
 
        public UrlsSection()
        {
            // 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();
        

        
        // 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="addUrl", 
            ClearItemsName="clearUrls",
            RemoveItemName="RemoveUrl")]
        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()
        {
            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 UrlConfigElement for the types contained by the 
    // UrlsSection.
    public class UrlConfigElement : ConfigurationElement
    {
        public UrlConfigElement(String name, String url)
        {
            this.Name = name;
            this.Url = url;
        
        
        public UrlConfigElement()
        {
            // Initialize as follows, if no attributed 
            // values are provided.
            // this.Name = "Microsoft";
            // this.Url = "http://www.microsoft.com";
            // this.Port = 0;
        

        [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;
            
        
    
    
    
    class TestingConfigurationCollectionAttribute
    {
        static void ShowUrls()
        {
    
            try
            {
                UrlsSection myUrlsSection =
                   ConfigurationManager.GetSection("MyUrls") as UrlsSection;

                if (myUrlsSection == null)
                    Console.WriteLine("Failed to load UrlsSection.");
                else
                {
                    Console.WriteLine("My URLs:");
                    for (int i = 0; i < myUrlsSection.Urls.Count; i++)
                    {
                        Console.WriteLine("  #{0 {1: {2", i,
                            myUrlsSection.Urls[i].Name,
                            myUrlsSection.Urls[i].Url + " port " +
                            myUrlsSection.Urls[i].Port);
                    
                
            
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            
        

        // Create a custom section.
        // It will contain a nested section as 
        // deined by the UrlsSection (<urls>...</urls>).
        static void CreateSection(string sectionName)
        {
            // Get the current configuration (file).
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            UrlsSection urlsSection;

            // Create an entry in the <configSections>. 
            if (config.Sections[sectionName] == null)
            {
                urlsSection = new UrlsSection();
                config.Sections.Add(sectionName, urlsSection);
                config.Save();
            

            // Create the actual target section and write it to 
            // the configuration file.
            if (config.Sections["/configuration/" + sectionName] == null)
            {
                urlsSection = config.GetSection(sectionName) as UrlsSection;
                urlsSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Full);
            
        

       
        static void Main(string[] args)
        {   
            Console.WriteLine("[Current URLs]");
            CreateSection("MyUrls");
            ShowUrls();
            Console.ReadLine();
        
    


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:
© 2014 Microsoft