配置系统提供的属性类型

from msdn

.NET Framework 配置系统提供的属性类型可在创建自定义配置元素期间使用。属性类型有两种:

  1. 指示 .NET Framework 如何实例化自定义配置元素属性的类型。这些类型包括:

  2. 指示 .NET Framework 如何验证自定义配置元素属性的类型。这些类型包括:

一、ConfigurationCollectionAttribute 类
      
使用 ConfigurationCollectionAttribute 属性修饰 ConfigurationElementCollection 元素。这将指示 .NET Framework 实例化集合并使用您的自定义 ConfigurationElement 值初始化此集合。
      创建自定义配置元素的最简单的方法是使用属性化(声明性)模型。声明这些元素并用 ConfigurationCollectionAttribute 属性修饰它们。对于每个用此属性标记的元素,.NET Framework 使用反射读取修饰参数并创建相关的 ConfigurationElementCollection 实例。您也可以使用编程模型。在这种情况下,您负责声明自定义公共集合,同时还要重写 ConfigurationElementCollection 成员并返回属性集合。 

下面的示例演示如何使用 ConfigurationCollectionAttribute

示例包含四个类。类 TestingConfigurationCollectionAttribute 创建包含元素集合的自定义配置节。其余三个类用于创建自定义节。自定义节类型 UrlsSection 包含 Urls 属性。此属性是类型 UrlsCollection 的自定义集合,包含类型 UrlConfigElement 的自定义元素。请注意,此示例运行的关键是用 ConfigurationCollectionAttribute 修饰的 Urls 属性。

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

以下是部分配置文件,包含在上例中定义的自定义节。

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

二、ConfigurationPropertyAttribute 类

您可以使用 ConfigurationPropertyAttribute 修饰配置属性,此配置属性将会指示 .NET Framework 使用修饰参数的值对该属性进行实例化和初始化。

创建自定义配置元素最简便的方法就是使用属性化(声明性)模型。您可以声明自定义公共属性 (Property),并使用 ConfigurationPropertyAttribute 属性 (Attribute) 来修饰它们。对于每一个标记有此属性 (Attribute) 的属性 (Property),.NET Framework 都使用反射来读取修饰参数,并创建相关的 ConfigurationProperty 实例。也可以使用编程模型,在这种情况下,您将负责声明自定义的公共属性,并返回它们的集合。

如:

下面的示例演示如何使用 ConfigurationPropertyAttribute 属性 (Attribute) 修饰自定义 ConfigurationSection 对象的属性 (Property)。

  
public class SampleSection :
    ConfigurationSection
{
    public SampleSection()
    {
    }

    [ConfigurationProperty("fileName", DefaultValue = "default.txt",
        IsRequired = true, IsKey = false)]
    [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
        MinLength = 1, MaxLength = 60)]
    public string FileName
    {
        get
        {
            return (string)this["fileName"];
        }
        set
        {
            this["fileName"] = value;
        }
    }

    [ConfigurationProperty("maxUsers", DefaultValue = (long)10000, 
        IsRequired=false)]
    [LongValidator(MinValue = 1, MaxValue = 10000000,
        ExcludeRange = false)]
    public long MaxUsers
    {
        get
        {
            return (long)this["maxUsers"];
        }
        set
        {
            this["maxUsers"] = value;
        }
    }

    [ConfigurationProperty("maxIdleTime",
        DefaultValue = "0:10:0",
        IsRequired = false)]
    [TimeSpanValidator(MinValueString = "0:0:30",
        MaxValueString = "5:00:0",
        ExcludeRange = false)]
    public TimeSpan MaxIdleTime
    {
        get
        {
            return (TimeSpan)this["maxIdleTime"];
        }
        set
        {
            this["maxIdleTime"] = value;
        }
    }
}

以下是部分配置文件,包含在上例中定义的自定义节。

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <configSections>
    <section name="custom" type="Samples.AspNet.SampleSection, ConfigurationPropertyAttribute" />
  </configSections>
  <custom fileName="Default.txt"
    maxUsers="2500" maxIdleTime="00:10:00" />
</configuration>

三、IntegerValidatorAttribute 类

[ConfigurationProperty("maxAttempts", DefaultValue = 101,
    IsRequired = true)]
[IntegerValidator(MinValue = 1, MaxValue = 100,
    ExcludeRange = true)]
public int MaxAttempts
{
    get
    {
        return (int)this["maxAttempts"];
    }
    set
    {
        this["maxAttempts"] = value;
    }
}

四、LongValidatorAttribute 类

[ConfigurationProperty("maxUsers", DefaultValue = (long)10000,
    IsRequired = false)]
[LongValidator(MinValue = 1, MaxValue = 10000000,
    ExcludeRange = false)]
public long MaxUsers
{
    get
    {
        return (long)this["maxUsers"];
    }
    set
    {
        this["maxUsers"] = value;
    }
}

五、
RegexStringValidatorAttribute 类

[ConfigurationProperty("alias2", DefaultValue = "alias.txt",
    IsRequired = true, IsKey = false)]
[RegexStringValidator(@"\w+\S*")]
public string Alias2
{
    get
    {
        return (string)this["alias2"];
    }
    set
    {
        this["alias2"] = value;
    }
}

六、StringValidatorAttribute 类

[ConfigurationProperty("fileName", DefaultValue = "default.txt",
    IsRequired = true, IsKey = false)]
[StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
    MinLength = 1, MaxLength = 60)]
public string FileName
{
    get
    {
        return (string)this["fileName"];
    }
    set
    {
        this["fileName"] = value;
    }
}

七、
TimeSpanValidatorAttribute 类

[ConfigurationProperty("maxIdleTime",
    DefaultValue = "0:10:0",
    IsRequired = false)]
[TimeSpanValidator(MinValueString = "0:0:30",
    MaxValueString = "5:00:0",
    ExcludeRange = false)]
public TimeSpan MaxIdleTime
{
    get
    {
        return (TimeSpan)this["maxIdleTime"];
    }
    set
    {
        this["maxIdleTime"] = value;
    }
}

posted on 2008-03-16 18:11  Austin Bai  阅读(592)  评论(0编辑  收藏  举报

导航