Export (0) Print
Expand All
5 out of 48 rated this helpful - Rate this topic

ConfigurationElement Class

Represents a configuration element within a configuration file.

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

public abstract class ConfigurationElement
public abstract class ConfigurationElement
public abstract class ConfigurationElement
Not applicable.

The ConfigurationElement is an abstract class, so you cannot create an instance of it. It represents an element within a configuration file.

NoteNote:

An element within a configuration file refers to a basic XML element or a section. The basic element is a simple XML tag with related attributes, if any. In its simplest form, a section coincides with a basic element. Complex sections can contain one or more basic elements, a collection of elements, and other sections.

The ConfigurationElement is used as the base class for the classes representing XML configuration elements, such as ConfigurationSection.

You can extend the ConfigurationElement class to represent a configuration element within a ConfigurationSection section. You can also create a ConfigurationElementCollection collection of ConfigurationElement elements, as shown in the Example section.

Handling Configuration

To handle configuration information using the standard types, use one of the following approaches:

  • Accessing a section. To access configuration information for your application you must use one of the GetSection methods provided by ConfigurationManager and WebConfigurationManager. For special sections such as appSettings and connectionStrings, you use the AppSettings property of the ConfigurationManager class or the AppSettings property of the WebConfigurationManager class, and the ConnectionStrings property of the ConfigurationManager class or the ConnectionStrings property of the WebConfigurationManager class. These methods perform read-only operations, use a single cached instance of the configuration, and are multithread aware.

  • Accessing configuration files. Your application can read and write configuration settings at any level, for itself or for other applications or computers as a whole, locally or remotely. You use one of the open methods provided by the ConfigurationManager class and the WebConfigurationManager class. These methods will return a Configuration object, which in turn provides the required methods and properties to handle the underlying configuration files. These methods perform read or write operations and recreate the configuration data every time a file is opened.

  • Advanced configuration. More advanced configuration handling is provided by the types SectionInformation, PropertyInformation, PropertyInformationCollection, ElementInformation, ContextInformation, ConfigurationSectionGroup, and ConfigurationSectionGroupCollection.

Extending Configuration Standard Types

You can also extend the standard configuration types such as ConfigurationElement, ConfigurationElementCollection, ConfigurationProperty, and ConfigurationSection, using either a programmatic or a declarative (attributed) model. For an example of how to extend a standard configuration type programmatically, see to the ConfigurationSection class. For an example of how to extend a standard configuration type using the attributed mode, see the ConfigurationElement class.

Notes to Implementers: Configuration is the class that allows programmatic access for editing configuration files. You use one of the open methods provided by WebConfigurationManager for Web applications or by ConfigurationManager for client applications. These methods will return a Configuration object, which in turn provides the required methods and properties to handle the underlying configuration files. You can access these files for reading or writing as explained in the following sections:

  • Reading. You use GetSection or GetSectionGroup to read configuration information. Note that the user or process that reads must have the following permissions:

    • Read permission on the configuration file at the current configuration hierarchy level.

    • Read permissions on all the parent configuration files.

    If your application needs read-only access to its own configuration, it is recommended that you use one of the GetSection overloaded methods in the case of Web applications. Or the GetSection method in the case of client applications.

    These methods provide access to the cached configuration values for the current application, which has better performance than the Configuration class.

    NoteNote:

    If you use a static GetSection method that takes a path parameter, the path parameter must refer to the application in which the code is running; otherwise, the parameter is ignored and configuration information for the currently-running application is returned.

  • Writing. You use one of the Save methods to write configuration information. Note that the user or process that writes must have the following permissions:

    • Write permission on the configuration file and directory at the current configuration hierarchy level.

    • Read permissions on all the configuration files.

Notes to Inheritors: Every ConfigurationElement object creates an internal ConfigurationPropertyCollection collection of ConfigurationProperty objects that represents either the element attributes or a collection of child elements. Non-customizable information and functionality is contained by an ElementInformation object provided by the ElementInformation property. You can use either 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 or set its value and add it to the internal property bag of the underlying ConfigurationElement base class.

  • The simpler declarative model, also called the attributed model, allows you to define an element attribute by using a property and then decorate it with attributes. These attributes instruct the ASP.NET configuration system about the property types and their default values. With this information, obtained through reflection, the ASP.NET configuration system creates the element property objects for you and performs the required initialization.

The following code example shows how to implement a custom ConfigurationElement.

This element is used by a custom section to define a custom section or a custom element collection.


using System;
using System.Configuration;
using System.Collections;


namespace Samples.AspNet
{

    // Define the UrlConfigElement.
    public class UrlConfigElement :
        ConfigurationElement
    {

        // Test flag.
        private static bool _displayIt = false;

        public UrlConfigElement(String newName,
            String newUrl, int newPort)
        {
            Name = newName;
            Url = newUrl;
            Port = newPort;

        }

        public UrlConfigElement()
        {

        }

        public UrlConfigElement(string elementName)
        {
            Name = elementName;
        }

        [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;
            }
        }

        protected override void DeserializeElement(
           System.Xml.XmlReader reader, 
            bool serializeCollectionKey)
        {
            base.DeserializeElement(reader, 
                serializeCollectionKey);

            // Enter your custom processing code here.
            if (_displayIt)
            {
                Console.WriteLine(
                   "UrlConfigElement.DeserializeElement({0}, {1}) called",
                   (reader == null) ? "null" : reader.ToString(),
                   serializeCollectionKey.ToString());
            }
        }


        protected override bool SerializeElement(
            System.Xml.XmlWriter writer, 
            bool serializeCollectionKey)
        {
            bool ret = base.SerializeElement(writer, 
                serializeCollectionKey);

            // Enter your custom processing code here.

            if (_displayIt)
            {
                Console.WriteLine(
                    "UrlConfigElement.SerializeElement({0}, {1}) called = {2}",
                    (writer == null) ? "null" : writer.ToString(),
                    serializeCollectionKey.ToString(), ret.ToString());
            }
            return ret;

        }


        protected override bool IsModified()
        {
            bool ret = base.IsModified();

            // Enter your custom processing code here.

            Console.WriteLine("UrlConfigElement.IsModified() called.");

            return ret;
        }


    }
}

The following configuration excerpt is used by the preceding example.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="MyUrls" type="Samples.AspNet.Configuration.UrlsSection, ConfigurationElement, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" />
  </configSections>
  <MyUrls name="MyFavorites" lockAllElementsExcept="urls">
    <simple 
      name="Microsoft" url="http://www.microsoft.com" port="0" />
      <urls>
        <clear />
        <add 
          name="Microsoft" url="http://www.microsoft.com" port="0"
          lockAllAttributesExcept="port" />
        <add 
          name="Contoso" url="http://www.contoso.com/" port="8080"
          lockAllAttributesExcept="port" lockItem="true" />
      </urls>
  </MyUrls>
</configuration>

The following code example shows how to implement a custom ConfigurationElementCollection collection that contains the previously defined element.


using System;
using System.Configuration;
using System.Collections;


namespace Samples.AspNet
{
    // Define the UrlsCollection that contains 
    // UrlsConfigElement elements.
    public class UrlsCollection :
        ConfigurationElementCollection
    {
        public UrlsCollection()
        {
            UrlConfigElement url =
                (UrlConfigElement)CreateNewElement();
            // Add the element to the collection.
            Add(url);
        }

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

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


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


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


        public new string AddElementName
        {
            get
            { return base.AddElementName; }

            set
            { base.AddElementName = value; }

        }

        public new string ClearElementName
        {
            get
            { return base.ClearElementName; }

            set
            { base.AddElementName = value; }

        }

        public new string RemoveElementName
        {
            get
            { return base.RemoveElementName; }


        }

        public new int Count
        {

            get { return base.Count; }

        }


        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);

            // Add custom code here.
        }

        protected override void 
            BaseAdd(ConfigurationElement element)
        {
            BaseAdd(element, false);
            // Add custom code here.
        }

        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();
            // Add custom code here.
        }
    }
}

The following code example shows how to implement a custom ConfigurationSection section that uses the previously defined element.


using System;
using System.Configuration;
using System.Collections;


namespace Samples.AspNet
{

    // Define a custom section containing 
    // a simple element and a collection of 
    // the same element. It uses two custom 
    // types: UrlsCollection and 
    // UrlsConfigElement.
    public class UrlsSection :
        ConfigurationSection
    {

        // Test flag.
        private static bool _displayIt = false;

        // Declare the custom element type.
        // This element will also be part of
        // the custom collection.
        UrlConfigElement url;

        public UrlsSection()
        {
            // Create the element.
            url = new UrlConfigElement();
        }

        [ConfigurationProperty("name", 
            DefaultValue = "MyFavorites",
            IsRequired = true, 
            IsKey = false)]
        [StringValidator(InvalidCharacters = 
            " ~!@#$%^&*()[]{}/;'\"|\\",
            MinLength = 1, MaxLength = 60)]
        public string Name
        {

            get
            {
                return (string)this["name"];
            }
            set
            {
                this["name"] = value;
            }

        }


        // Declare a simple element of the type
        // UrlConfigElement. In the configuration
        // file it corresponds to <simple .... />.
        [ConfigurationProperty("simple")]
        public UrlConfigElement Simple
        {
            get
            {
                UrlConfigElement url =
                (UrlConfigElement)base["simple"];
                return url;
            }
        }

        // 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 UrlsCollection Urls
        {

            get
            {
                UrlsCollection urlsCollection =
                (UrlsCollection)base["urls"];
                return urlsCollection;
            }
        }


        protected override void DeserializeSection(
            System.Xml.XmlReader reader)
        {
            base.DeserializeSection(reader);

            // Enter your custom processing code here.
            if (_displayIt)
            {
                Console.WriteLine(
                    "UrlsSection.DeserializeSection({0}) called",
                    (reader == null) ? "null" : reader.ToString());
            }
        }

        protected override string SerializeSection(
            ConfigurationElement parentElement,
            string name, ConfigurationSaveMode saveMode)
        {
            string s =
                base.SerializeSection(parentElement,
                name, saveMode);

            // Enter your custom processing code here.

            if (_displayIt)
            {
                Console.WriteLine(
                   "UrlsSection.SerializeSection({0}, {1}, {2}) called = {3}",
                   parentElement.ToString(), name,
                   saveMode.ToString(), s);
            }
            return s;
        }

    }
}

System.Object
  System.Configuration.ConfigurationElement
     Derived Classes
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 Server 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 Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 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.