【问题标题】:How to search custom config section by key如何按键搜索自定义配置部分
【发布时间】:2014-03-01 23:58:07
【问题描述】:

我有自定义配置部分,例如

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="DBConfiguration" type="NewSQLExecuter.DBConfigurationSection, NewSQLExecuter"/>
    </configSections>

    <DBConfiguration>
        <Items>
            <add servername="192.168.50.2\db1" dbname="test1" userid="sa" password="2222m@n" countrycode="GB" />
            <add servername="192.168.60.2\db2" dbname="test2" userid="sa" password="22222n" countrycode="US" />
            <add servername="192.168.70.2\db3" dbname="test3" userid="sa" password="3333" countrycode="DE" />
        </Items>
    </DBConfiguration>

</configuration>

我已经编写了一个从自定义配置部分读取数据的类...类代码如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace NewSQLExecuter
{

    public class DBConfigurationSection : ConfigurationSection
    {
        [ConfigurationProperty("Items")]
        public ItemsCollection Items
        {
            get { return ((ItemsCollection)(base["Items"])); }
        }
    }

    [ConfigurationCollection(typeof(ItemsElement))]
    public class ItemsCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ItemsElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ItemsElement)(element)).CountryCode;
        }

        public ItemsElement this[int idx]
        {
            get
            {
                return (ItemsElement)BaseGet(idx);
            }
        }
    }

    public class ItemsElement : ConfigurationElement
    {
        [ConfigurationProperty("servername", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string ServerName
        {
            get
            {
                return ((string)(base["servername"]));
            }
            set
            {
                base["servername"] = value;
            }
        }

        [ConfigurationProperty("dbname", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string DBName
        {
            get
            {
                return ((string)(base["dbname"]));
            }
            set
            {
                base["dbname"] = value;
            }
        }

        [ConfigurationProperty("userid", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string UserID
        {
            get
            {
                return ((string)(base["userid"]));
            }
            set
            {
                base["userid"] = value;
            }
        }

        [ConfigurationProperty("password", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string Password
        {
            get
            {
                return ((string)(base["password"]));
            }
            set
            {
                base["password"] = value;
            }
        }

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

这样我迭代自定义配置数据并获取值

DBConfigurationSection section = (DBConfigurationSection)ConfigurationManager.GetSection("DBConfiguration");

if (section != null)
{
    DateTime satrt = DateTime.Now;

    for (int i = 0; i <= section.Items.Count - 1; i++)
    {
        var country = section.Items[i].CountryCode; ;
        var constring = string.Format("{0}{1}{2}{3}", "UID=" + section.Items[i].UserID, ";PWD=" + section.Items[i].Password, 
                                    ";Server=" + section.Items[i].ServerName, ";Database=" + section.Items[i].DBName); 
        dicList.Add(country, constring);
    }
}

代码运行良好,但我想再添加一项功能,例如通过任何键值搜索任何配置数据,例如

if(section.key.userid=="joy")
{
    string pwd=section.key.password
}

所以请指导我如何将搜索功能添加到我的课程中。如果我可以使用 LINQ 搜索任何自定义配置数据,那就太好了。所以请指导我谢谢。

在 app.config 文件中处理两个自定义配置部分时出错

我的 app.config 文件看起来像

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="DBConfiguration" type="CSRAssistant.DBConfigurationSection, CSRAssistant"/>
        <section name="LoginConfiguration" type="CSRAssistant.LoginConfigurationSection, CSRAssistant"/>
    </configSections>

    <DBConfiguration>
        <add servername="dbname" dbname="BBAJobBoardForGB" userid="sa" password="222" countrycode="GBR" />
        <add servername="db2" dbname="BBAJobBoardForUS" userid="sa" password="swww" countrycode="USA" />

    </DBConfiguration>

    <LoginConfiguration>
        <add UserName="ww" Pwd="ww" Country="GBR"/>
        <add UserName="ss" Pwd="ss"  Country="USA"/>
        <add UserName="dd" Pwd="dd"  Country="CAD"/>
    </LoginConfiguration>
    <appSettings>
        <add key="MailID" value="tridip@bba-reman.com" />
    </appSettings>

    <startup useLegacyV2RuntimeActivationPolicy="true">
        <supportedRuntime version="v4.0"/>
        <requiredRuntime version="v4.0.20506"/>
    </startup>

</configuration>

要处理两个部分,我的代码如下

namespace CSRAssistant
{

    public class DBConfigurationSection : ConfigurationSection
    {
        //[ConfigurationProperty("Items")]
        //public ItemsCollection Items
        //{
        //    get { return ((ItemsCollection)(base["Items"])); }
        //}

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

    [ConfigurationCollection(typeof(ItemsElement))]
    public class ItemsCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ItemsElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ItemsElement)(element)).CountryCode;
        }

        public ItemsElement this[int idx]
        {
            get
            {
                return (ItemsElement)BaseGet(idx);
            }
        }
    }

    public class ItemsElement : ConfigurationElement
    {
        [ConfigurationProperty("servername", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string ServerName
        {
            get
            {
                return ((string)(base["servername"]));
            }
            set
            {
                base["servername"] = value;
            }
        }

        [ConfigurationProperty("dbname", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string DBName
        {
            get
            {
                return ((string)(base["dbname"]));
            }
            set
            {
                base["dbname"] = value;
            }
        }

        [ConfigurationProperty("userid", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string UserID
        {
            get
            {
                return ((string)(base["userid"]));
            }
            set
            {
                base["userid"] = value;
            }
        }

        [ConfigurationProperty("password", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string Password
        {
            get
            {
                return ((string)(base["password"]));
            }
            set
            {
                base["password"] = value;
            }
        }

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

    public class LoginConfigurationSection : ConfigurationSection
    {
        //[ConfigurationProperty("Items")]
        //public ItemsCollection Items
        //{
        //    get { return ((ItemsCollection)(base["Items"])); }
        //}

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


    public class LoginElement : ConfigurationElement
    {
        [ConfigurationProperty("UserName", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string UserName
        {
            get
            {
                return ((string)(base["UserName"]));
            }
            set
            {
                base["UserName"] = value;
            }
        }

        [ConfigurationProperty("Pwd", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string Pwd
        {
            get
            {
                return ((string)(base["Pwd"]));
            }
            set
            {
                base["Pwd"] = value;
            }
        }

        [ConfigurationProperty("Country", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string Country
        {
            get
            {
                return ((string)(base["Country"]));
            }
            set
            {
                base["Country"] = value;
            }
        }

    }
}

这样读取两个自定义配置设置

string joyPassword = "";
            LoginConfigurationSection LoginConfigurationSection = (LoginConfigurationSection)ConfigurationManager.GetSection("LoginConfiguration");
            if (LoginConfigurationSection != null)
            {
                var UserCredentials = LoginConfigurationSection.Items
                                    .Cast<LoginElement>()
                                    .FirstOrDefault(_element => _element.UserName == "razi");

                if (UserCredentials != null)
                    joyPassword = UserCredentials.Country;



                DBConfigurationSection section = (DBConfigurationSection)ConfigurationManager.GetSection("DBConfiguration");
                if (section != null)
                {
                    var DbConnection = section.Items
                                        .Cast<ItemsElement>()
                                        .FirstOrDefault(_element => _element.CountryCode.ToUpper() == joyPassword.ToUpper());

                    if (DbConnection != null)
                        joyPassword = DbConnection.ServerName;
                }
            }

现在我在运行时遇到错误 无法识别的属性“用户名”。请注意,属性名称区分大小写。

为什么无法识别的属性“用户名”只是不明白....如果可能,请指导我。谢谢

【问题讨论】:

  • 我知道这不是您正在寻找的答案,但您为什么不直接将配置文件作为 xml 读取呢?我的意思是这样做要容易得多,使用 XDocument 你可以找到任何东西。
  • @Alex 我不同意这一点。我认为自定义配置系统比加载随机xml文件更友好,更容易使用。它集成在 app/web.config 工作流程中并且可以以标准方式加载并且仍然通过configSource 包含在外部文件中的事实是一个杀手级功能。在我看来,他的示例非常适合自定义部分,我也会这样做。
  • 鉴于这个问题,在我看来,OP 正在为一些 LINQ 功能而死。因此,将所有内容加载到 XDoc 中,然后使用 foo = 'bar' 获取孩子似乎是一笔不错的交易。同样,这只是一种观点,就工作流程而言,我同意你的看法。是搜索部分吸收了自定义配置。
  • @Alex 我相信这与我建议使用 linq 搜索项目并没有太大不同。请注意,由于项目集合仍然是 IEnumerable,因此您可以相对轻松地在其上使用 linq。即使您采用纯 XML 路线,我仍然建议使用类型化模型并将 xml 反序列化到其中。无论如何,它最终会与配置部分非常相似,就像我之前所说的那样,它会与默认工作流程断开连接。我同意虽然配置部分并不总是答案,例如如果您已经拥有 xml 和模型。
  • 如果有人使用模型:) ...我很少为这类事情做。因此,配置类的额外麻烦使它成为一个更加麻烦的解决方案。但你是对的,从长远来看,配置类是最好的方法。对于非懒惰的开发者来说。

标签: c# linq custom-configuration


【解决方案1】:

你也许可以这样做:

var joyUserElement = section.Items
    .Cast<ItemsElement>()
    .FirstOrDefault(_element => _element.UserID == "joy");

if (joyUserElement != null)
    string joyPassword = joyUserElement.Password;

这对你有意义吗?由于未经测试,我可能在这里遗漏了一些东西,但它应该可以正常工作。

我看到你也在使用普通的for 而不是foreach。请记住,集合是 IEnumerable,因此您可以使用带有显式类型的 foreach,如下所示:

foreach(ItemElement element in section.Items)

我想补充两点:

  • 我建议您重命名元素类以反映它的实际含义,例如 DbConfigurationElement 而不是 ItemElement。从长远来看,这将使代码更加清晰。

  • 如果&lt;Items&gt; 没有特殊含义,您可以在那里“隐藏”xml 中的标记(似乎是这种情况)。如果你像这样注释你的集合属性

.

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

然后你可以这样写你的部分:

<DBConfiguration>
    <add servername="192.168.50.2\db1" dbname="test1" userid="sa" password="2222m@n" countrycode="GB" />
    <add servername="192.168.60.2\db2" dbname="test2" userid="sa" password="22222n" countrycode="US" />
    <add servername="192.168.70.2\db3" dbname="test3" userid="sa" password="3333" countrycode="DE" />
</DBConfiguration>

这对于像您这样的小型单一集合配置部分非常有用。

【讨论】:

  • 你能指导我如何编辑自定义配置数据...因为读取成功谢谢
  • 我在 app.config 中又添加了一个部分,但没有编写任何代码来处理它。所以我收到一个名为“配置系统初始化失败”的错误,所以我需要做些什么来修复这个错误。请指导我。谢谢
  • 在运行时修改配置系统上的值是非常少见的,但可以像this article suggests 那样完成。至于第二点,我不确定我是否理解您的要求。如果您在configSections 中添加配置部分声明,则需要该部分出现在配置xml 的其余部分中,即使它是空的。如果这不是您所看到的,请详细说明,如果不相关,请提出另一个问题。
  • 我做了,现在我收到名为“无法识别的属性'用户名'的错误。请注意,属性名称区分大小写。”请我更新我的问题并提供完整的源代码。如果可能的话,请看看并告诉我我在哪里犯了错误。谢谢
  • 嗯,这个错误很简单。请注意,您对两个配置部分使用相同的 ItemCollection。系统试图从LoginSection 的内部文本中解析ItemElement,但显然失败了,因为它是LoginElement。您必须创建另一个集合,类似于第一个集合,其中包含LoginElements。这就是为什么我建议您更改该集合的名称,您现在看到它带来的混乱。如果它被显式命名以表示它是一个 DbConfiguration 集合,那么您可能不会犯这个错误。
【解决方案2】:

你好,这样你就可以做到。

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="DBConfiguration" type="CSRAssistant.DBConfigurationSection, CSRAssistant"/>
        <section name="LoginConfiguration" type="CSRAssistant.LoginConfigurationSection, CSRAssistant"/>
      </configSections>

      <DBConfiguration>
        <add servername="192.168.88.2\bbareman" dbname="BBAJobBoardForGB" userid="sa" password="8B@R5m@n" countrycode="GBR" />
        <add servername="192.168.1.2\bbareman" dbname="BBAJobBoardForUS" userid="sa" password="8B@R5m@n" countrycode="USA" />
        <add servername="192.168.2.2\bbareman" dbname="BBAJobBoardForDE" userid="sa" password="8B@R5m@n" countrycode="DEU" />
        <add servername="192.168.77.10\bbareman" dbname="BBAJobBoardForFR" userid="sa" password="8B@R5m@n" countrycode="FRA" />
        <add servername="192.168.3.2\bbareman" dbname="BBAJobBoardForIT" userid="sa" password="8B@R5m@n" countrycode="ITA" />
        <add servername="192.168.4.2\bbareman" dbname="BBAJobBoardForCA" userid="sa" password="8B@R5m@n" countrycode="CAD" />
        <add servername="192.168.55.10\bbareman" dbname="BBAJobBoardForES" userid="sa" password="8B@R5m@n" countrycode="ESP" />
      </DBConfiguration>

      <LoginConfiguration>
        <add ID="1" UserName="suanguite" Pwd="gguite" Country="GBR"/>
        <add ID="2" UserName="sujoy" Pwd="sujoyUS"  Country="USA"/>
        <add ID="3" UserName="sujoy" Pwd="sujoyCA"  Country="CAD"/>
        <add ID="4" UserName="pjasu" Pwd="pjasuDE"  Country="DEU"/>
        <add ID="5" UserName="kankana" Pwd="kankana123"  Country="ITA"/>
        <add ID="6" UserName="test" Pwd="test"  Country="IND"/>
        <add ID="7" UserName="biswajit" Pwd="biswajitES"  Country="ESP"/>
        <add ID="8" UserName="suparna" Pwd="suparna"  Country="CAD"/>
        <add ID="9" UserName="razi" Pwd="raziFR"  Country="FRA"/>
        <add ID="10" UserName="tridip" Pwd="tridip"  Country="GBR"/>
        <add ID="11" UserName="tridip" Pwd="tridip"  Country="ESP"/>
        <add ID="12" UserName="tridip" Pwd="tridip"  Country="FRA"/>
      </LoginConfiguration>
      <appSettings>
        <add key="MailID" value="tridip@bba-reman.com" />
      </appSettings>

      <startup useLegacyV2RuntimeActivationPolicy="true">
        <supportedRuntime version="v4.0"/>
        <requiredRuntime version="v4.0.20506"/>
      </startup>

    </configuration>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace CSRAssistant
{
    public class DBConfigurationSection : ConfigurationSection
    {
        //[ConfigurationProperty("Items")]
        //public ItemsCollection Items
        //{
        //    get { return ((ItemsCollection)(base["Items"])); }
        //}

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

    [ConfigurationCollection(typeof(ItemsElement))]
    public class ItemsCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ItemsElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ItemsElement)(element)).CountryCode;
        }

        public ItemsElement this[int idx]
        {
            get
            {
                return (ItemsElement)BaseGet(idx);
            }
        }
    }

    public class ItemsElement : ConfigurationElement
    {
        [ConfigurationProperty("servername", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string ServerName
        {
            get
            {
                return ((string)(base["servername"]));
            }
            set
            {
                base["servername"] = value;
            }
        }

        [ConfigurationProperty("dbname", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string DBName
        {
            get
            {
                return ((string)(base["dbname"]));
            }
            set
            {
                base["dbname"] = value;
            }
        }

        [ConfigurationProperty("userid", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string UserID
        {
            get
            {
                return ((string)(base["userid"]));
            }
            set
            {
                base["userid"] = value;
            }
        }

        [ConfigurationProperty("password", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string Password
        {
            get
            {
                return ((string)(base["password"]));
            }
            set
            {
                base["password"] = value;
            }
        }

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


}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace CSRAssistant
{
    //****login config

    public class LoginConfigurationSection : ConfigurationSection
    {
        //[ConfigurationProperty("Items")]
        //public ItemsCollection Items
        //{
        //    get { return ((ItemsCollection)(base["Items"])); }
        //}

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

    [ConfigurationCollection(typeof(LoginElement))]
    public class LoginCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new LoginElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((LoginElement)(element)).ID;
        }

        public LoginElement this[int idx]
        {
            get
            {
                return (LoginElement)BaseGet(idx);
            }
        }
    }
    public class LoginElement : ConfigurationElement
    {
        [ConfigurationProperty("UserName", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string UserName
        {
            get
            {
                return ((string)(base["UserName"]));
            }
            set
            {
                base["UserName"] = value;
            }
        }

        [ConfigurationProperty("Pwd", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string Pwd
        {
            get
            {
                return ((string)(base["Pwd"]));
            }
            set
            {
                base["Pwd"] = value;
            }
        }

        [ConfigurationProperty("Country", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string Country
        {
            get
            {
                return ((string)(base["Country"]));
            }
            set
            {
                base["Country"] = value;
            }
        }

        [ConfigurationProperty("ID", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string ID
        {
            get
            {
                return ((string)(base["ID"]));
            }
            set
            {
                base["ID"] = value;
            }
        }
    }
}

调用方式

private void button1_Click_1(object sender, EventArgs e)
        {
            string _country = "";
            string _ServerName = "";
            LoginConfigurationSection LoginConfigurationSection = (LoginConfigurationSection)ConfigurationManager.GetSection("LoginConfiguration");
            if (LoginConfigurationSection != null)
            {
                var UserCredentials = LoginConfigurationSection.Items
                                    .Cast<LoginElement>()
                                    .FirstOrDefault(_element => _element.UserName == "razi");

                if (UserCredentials != null)
                    _country = UserCredentials.Country;



                DBConfigurationSection section = (DBConfigurationSection)ConfigurationManager.GetSection("DBConfiguration");
                if (section != null)
                {
                    var DbConnection = section.Items
                                        .Cast<ItemsElement>()
                                        .FirstOrDefault(_element => _element.CountryCode.ToUpper() == _country.ToUpper());

                    if (DbConnection != null)
                        _ServerName = DbConnection.ServerName;
                }
            }
        }

【讨论】:

    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 2023-03-22
    • 2010-10-25
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    相关资源
    最近更新 更多