包含集合的自定义配置部分 [英] Custom config section containing collection

查看:20
本文介绍了包含集合的自定义配置部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用自定义配置部分.这是我从网上得到的一些代码,试图更好地理解这个领域,并使我能够最终到达我想要的地方,我自己的自定义配置部分.

I'm having trouble getting a custom config section to work. It's some code I got from the web in an effort to try to understand this area a little better and enable me to get to where I want to ultimatly be, my own custom config section.

在控制台应用程序中运行代码时出现的错误是'无法识别的属性扩展".请注意,属性名称区分大小写.'

The error I get when I run the code in a console app is ' Unrecognized attribute 'extension'. Note that attribute names are case-sensitive.'

主应用程序中的代码是

var conf = ConfigurationManager.GetSection("uploadDirector");

这就是异常出现的地方.

and this is where the exception appears.

这是我希望/试图实现的配置部分

This is the config section I am hoping/trying to achieve

<AuthorisedClients>
    <AuthorisedClient name="Client">
      <Queue id="1" />
      <Queue id="7" />
    </AuthorisedClient>
    <AuthorisedClient name="Client2">
      <Queue id="3" />
      <Queue id="4" />
    </AuthorisedClient>
  </AuthorisedClients>

这是我从网上得到的代码

Here's the code I have got from the web

.config 文件

<uploadDirector>
    <filegroup name="documents" defaultDirectory="/documents/">
      <clear/>
      <add extension="pdf" mime="application/pdf" maxsize="100"/>
      <add extension="doc" mime="application/word" maxsize="500"/>
    </filegroup>
    <filegroup name="images">
      <clear/>
      <add extension="gif" mime="image/gif" maxsize="100"/>
    </filegroup>
  </uploadDirector>

UploadDirectorConfigSection.cs

public class UploadDirectorConfigSection : ConfigurationSection {

        private string _rootPath;

        public UploadDirectorConfigSection() {

        }

        [ConfigurationProperty("rootpath", DefaultValue="/", IsRequired=false, IsKey=false)]
        [StringValidator(InvalidCharacters=@"~!.@#$%^&*()[]{};'\|\\")]
        public string RootPath {
            get { return _rootPath; }
            set { _rootPath = value; }
        }

        [ConfigurationProperty("", IsRequired = true, IsKey = false, IsDefaultCollection = true)]
        public FileGroupCollection FileGroups {
            get { return (FileGroupCollection) base[""]; }
            set { base[""] = value; }
        }
    }

FileGroupCollection.cs

public class FileGroupCollection : ConfigurationElementCollection {
        protected override ConfigurationElement CreateNewElement() {
            return new FileGroupElement();
        }

        protected override object GetElementKey(ConfigurationElement element) {
            return ((FileGroupElement) element).Name;
        }

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

        protected override string ElementName {
            get {
                return "filegroup";
            }
        }

        protected override bool IsElementName(string elementName) {
            if (string.IsNullOrWhiteSpace(elementName) || elementName != "filegroup")
                return false;
            return true;
        }

        public FileGroupElement this[int index] {
            get { return (FileGroupElement) BaseGet(index); }
            set {
                if(BaseGet(index) != null)
                    BaseRemoveAt(index);
                BaseAdd(index, value);
            }
        }
    }

FileGroupElement.cs

public class FileGroupElement : ConfigurationElement {

        [ConfigurationProperty("name", IsKey=true, IsRequired = true)]
        [StringValidator(InvalidCharacters = @" ~.!@#$%^&*()[]{}/;'""|\")]
        public string Name {
            get { return (string) base["name"]; }
            set { base["name"] = value; }
        }

        [ConfigurationProperty("defaultDirectory", DefaultValue = ".")]
        public string DefaultDirectory {
            get { return (string) base["Path"]; }
            set { base["Path"] = value; }
        }

        [ConfigurationProperty("", IsDefaultCollection = true, IsRequired = true)]
        public FileInfoCollection Files {
            get { return (FileInfoCollection) base[""]; }
        }
    }

FileInfoCollection.cs

public class FileInfoCollection : ConfigurationElementCollection {
        protected override ConfigurationElement CreateNewElement() {
            return new FileInfoCollection();
        }

        protected override object GetElementKey(ConfigurationElement element) {
            return ((FileInfoElement) element).Extension;
        }
    }

FileInfoElement.cs

public class FileInfoElement : ConfigurationElement {

        public FileInfoElement() {
            Extension = "txt";
            Mime = "text/plain";
            MaxSize = 0;
        }

        [ConfigurationProperty("extension", IsKey = true, IsRequired = true)]
        public string Extension {
            get { return (string)base["extension"]; }
            set { base["extension"] = value; }
        }

        [ConfigurationProperty("mime", DefaultValue = "text/plain")]
        public string Mime {
            get { return (string) base["mime"]; }
            set { base["mime"] = value; }
        }

        [ConfigurationProperty("maxsize", DefaultValue = 0)]
        public int MaxSize {
            get { return (int) base["maxsize"]; }
            set { base["maxsize"] = value; }
        }
    }

推荐答案

在您定义的 FileInfoCollection 方法中 CreateNewElement 您创建 FileInfoCollection这是错误的.重写的 CreateNewElement 应该返回新的集合元素,而不是新的集合:

In your definition of FileInfoCollection in the method CreateNewElement you create FileInfoCollection which is wrong. Overridden CreateNewElement should return new collection element, not the new collection:

public class FileInfoCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new FileInfoElement();
    }

    protected override object GetElementKey (ConfigurationElement element)
    {
        return ((FileInfoElement)element).Extension;
    }
}

关于您想要的配置,最简单的实现可能如下所示:

Regarding your desired configuration, probably the simplest implementation will look like:

public class AuthorisedClientsSection : ConfigurationSection {
    [ConfigurationProperty("", IsDefaultCollection = true)]
    public AuthorisedClientElementCollection Elements {
        get { return (AuthorisedClientElementCollection)base[""];}
    }
}

public class AuthorisedClientElementCollection : ConfigurationElementCollection {
    const string ELEMENT_NAME = "AuthorisedClient";

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

    protected override string ElementName {
        get { return ELEMENT_NAME; }
    }

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

    protected override object GetElementKey(ConfigurationElement element) {
        return ((AuthorisedClientElement)element).Name;
    }
}

public class AuthorisedClientElement : ConfigurationElement {
    const string NAME = "name";

    [ConfigurationProperty(NAME, IsRequired = true)]
    public string Name {
        get { return (string)base[NAME]; }
    }

    [ConfigurationProperty("", IsDefaultCollection = true)]
    public QueueElementCollection Elements {
        get { return (QueueElementCollection)base[""]; }
    }
}

public class QueueElementCollection : ConfigurationElementCollection {
    const string ELEMENT_NAME = "Queue";

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

    protected override string ElementName {
        get { return ELEMENT_NAME; }
    }

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

    protected override object GetElementKey(ConfigurationElement element) {
        return ((QueueElement)element).Id;
    }
}

public class QueueElement : ConfigurationElement {
    const string ID = "id";

    [ConfigurationProperty(ID, IsRequired = true)]
    public int Id {
        get { return (int)base[ID]; }
    }
}

和测试:

var authorisedClientsSection = ConfigurationManager.GetSection("AuthorisedClients")
    as AuthorisedClientsSection;

foreach (AuthorisedClientElement client in authorisedClientsSection.Elements) {
    Console.WriteLine("Client: {0}", client.Name);

    foreach (QueueElement queue in client.Elements) {
        Console.WriteLine("\tQueue: {0}", queue.Id);
    }
}

这篇关于包含集合的自定义配置部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆