zoukankan      html  css  js  c++  java
  • .Net 配置文件——继承ConfigurationSection实现自定义处理类处理自定义配置节点

    来源:https://www.php.cn/csharp-article-353442.html

    除了使用继承IConfigurationSectionHandler的方法定义处理自定义节点的类,还可以通过继承ConfigurationSection类实现同样效果。

    首先说下.Net配置文件中一个潜规则

    在配置节点时,对于想要进行存储的参数数据,可以采用两种方式:一种是存储到节点的属性中,另一种是存储在节点的文本中。

    因为一个节点可以有很多属性,但是只要一个innertext,而要在程序中将这两种形式区分开会带来复杂性。 为了避免这个问题,.net的配置文件只是用属性存储而不使用innertext.

    接着,我们来写一个符合这个潜规则的自定义配置文件,方便测试:

    1

    2

    3

    4

    5

    6

    7

    8

    <mailServerGroup provider="www.baidu.com">

        <mailServers>

          <mailServer client="http://blog.csdn.net/lhc1105" address="13232@qq.com" userName="lhc" password="2343254"/>

          <mailServer client="http://blog345.csdn.net/lhc1105" address="132wdfgdsggtaewg32@qq.com" userName="dfshs水田如雅"  password="2334t243的萨芬234254"/>

          <mailServer client="http://blog436.csdn.net/lhc1105" address="132wdgadsfgdtaewg32@qq.com" userName="sdfhdfs水田如雅"  password="23ewrty2343的萨芬234254"/>

          <mailServer client="http://blo345734g.csdn.net/lhc1105" address="132wdgdfagdstaewg32@qq.com" userName="sdfher水田如雅"  password="23erwt43的萨芬234254"/>

        </mailServers>

      </mailServerGroup>

    接着,我们来写相应的处理类,这里我们由内向外来写:

    首先是最内层的mailServer:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

    76

    77

    78

    79

    80

    81

    82

    83

    84

    85

    /// <summary>

       /// Class MailServerElement:用于映射mailServer节点,这里是实际存储数据的地方;

       /// </summary>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:51:57</remarks>

       public sealed class MailServerElement : ConfigurationElement  //配置文件中的配置元素

       {

     

           /// <summary>

           /// Gets or sets the client.

           /// </summary>

           /// <value>The client.</value>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:40</remarks>

           [ConfigurationProperty("client", IsKey = true, IsRequired = true)]  //client是必须的key属性,有点儿主键的意思,例如,如果定义多个client相同的节点,循环读取的话就只读取到最后一个值

           public string Client

           {

               get

               {

                   return this["client"] as string;

               }

               set

               {

                   this["client"] = value;

               }

     

           }

           /// <summary>

           /// Gets or sets the address.

           /// </summary>

           /// <value>The address.</value>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:38</remarks>

           [ConfigurationProperty("address")]

           public string Address

           {

               get

               {

                   return this["address"] as string;

               }

               set

               {

                   this["address"] = value;

               }

     

           }

           /// <summary>

           /// Gets or sets the name of the user.

           /// </summary>

           /// <value>The name of the user.</value>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:35</remarks>

           [ConfigurationProperty("userName")]

           public string UserName

           {

     

               get

               {

                   return this["userName"] as string;

               }

               set

               {

                   this["userName"] = value;

               }

     

           }

           /// <summary>

           /// Gets or sets the password.

           /// </summary>

           /// <value>The password.</value>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:33</remarks>

           [ConfigurationProperty("password")]

           public string Password

           {

     

               get

               {

                   return this["password"] as string;

               }

               set

               {

                   this["password"] = value;

               }

     

           }

     

     

     

       }

    接着是mailServers,它是一个mailServer的集合:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

    76

    77

    78

    79

    80

    81

    82

    83

    84

    85

    86

    87

    88

    89

    90

    91

    92

    93

    94

    95

    96

    97

    98

    99

    100

    101

    102

    103

    104

    105

    106

    107

    108

    109

    110

    111

    112

    113

    114

    115

    116

    117

    118

    119

    120

    121

    122

    123

    124

    125

    126

    127

    128

    129

    130

    131

    132

    133

    134

    135

    136

    137

    138

    139

    140

    141

    142

    143

    144

    145

    146

    147

    148

    149

    150

    151

    152

    153

    154

    155

    156

    157

    158

    159

    160

    161

    162

    163

    164

    165

    /// <summary>

       /// Class MailServerCollection:映射mailServers节点,为一个集合类,另外还包含了很多对节点的操作方法,大部分继承自ConfigurationElementCollection

       /// </summary>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:52:00</remarks>

       public sealed class MailServerCollection : ConfigurationElementCollection

       {

           /// <summary>

           /// 获取 <see cref="T:System.Configuration.ConfigurationElementCollection" /> 的类型。

           /// </summary>

           /// <value>The type of the collection.</value>

           /// <returns>此集合的 <see cref="T:System.Configuration.ConfigurationElementCollectionType" />。</returns>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:08</remarks>

           public override ConfigurationElementCollectionType CollectionType

           {

               get

               {

                   return ConfigurationElementCollectionType.BasicMap;

               }

             

           }

     

     

           /// <summary>

           /// 当在派生的类中重写时,创建一个新的 <see cref="T:System.Configuration.ConfigurationElement" />。

           /// </summary>

           /// <returns>新的 <see cref="T:System.Configuration.ConfigurationElement" />。</returns>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:03</remarks>

           protected override ConfigurationElement CreateNewElement()

           {

               return new MailServerElement();

           }

     

           /// <summary>

           /// 在派生类中重写时获取指定配置元素的元素键。

           /// </summary>

           /// <param name="element">要为其返回键的 <see cref="T:System.Configuration.ConfigurationElement" />。</param>

           /// <returns>一个 <see cref="T:System.Object" />,用作指定 <see cref="T:System.Configuration.ConfigurationElement" /> 的键。</returns>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:04:51</remarks>

           protected override object GetElementKey(ConfigurationElement element)

           {

               return (element as MailServerElement).Client;

           }

     

           /// <summary>

           /// 获取在派生的类中重写时用于标识配置文件中此元素集合的名称。

           /// </summary>

           /// <value>The name of the element.</value>

           /// <returns>集合的名称;否则为空字符串。默认值为空字符串。</returns>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 23:41:40</remarks>

           protected override string ElementName

           {

               get

               {

                   return "mailServer";

               }

           }

     

     

           /// <summary>

           /// 获取集合中的元素数。

           /// </summary>

           /// <value>The count.</value>

           /// <returns>集合中的元素数。</returns>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:08:24</remarks>

           public new int Count

           {

               get { return base.Count; }

           }

     

           /// <summary>

           /// 获取或设置此配置元素的属性、特性或子元素。

           /// </summary>

           /// <param name="index">The index.</param>

           /// <returns>MailServerElement.</returns>

           /// <remarks>Editor:v-liuhch</remarks>

           public MailServerElement this[int index]

           {

     

               get { return BaseGet(index) as MailServerElement; }

               set

               {

                   if (BaseGet(index) != null)

                   {

                       BaseRemoveAt(index);

                   }

                   BaseAdd(index, value);

               }

     

           }

     

           /// <summary>

           /// 获取或设置此配置元素的属性、特性或子元素。

           /// </summary>

           /// <param name="Name">The name.</param>

           /// <returns>MailServerElement.</returns>

           /// <remarks>Editor:v-liuhch</remarks>

           new public MailServerElement this[string Name]

           {

               get { return BaseGet(Name) as MailServerElement; }

           }

     

           /// <summary>

           /// Indexes the of.

           /// </summary>

           /// <param name="element">The element.</param>

           /// <returns>System.Int32.</returns>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:24:16</remarks>

           public int IndexOf(MailServerElement element)

           {

     

               return BaseIndexOf(element);

           }

     

           /// <summary>

           /// Adds the specified element.

           /// </summary>

           /// <param name="element">The element.</param>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:26:06</remarks>

           public void Add(MailServerElement element)

           {

               BaseAdd(element);

           }

     

           /// <summary>

           /// Removes the specified element.

           /// </summary>

           /// <param name="element">The element.</param>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:27:01</remarks>

           public void Remove(MailServerElement element)

           {

               if (BaseIndexOf(element) > 0)

               {

                   BaseRemove(element.Client);

               }

           }

     

           /// <summary>

           /// Removes at.

           /// </summary>

           /// <param name="index">The index.</param>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:33:29</remarks>

           public void RemoveAt(int index)

           {

               BaseRemoveAt(index);

           }

     

           /// <summary>

           /// Removes the specified client.

           /// </summary>

           /// <param name="client">The client.</param>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:34:04</remarks>

           public void Remove(string client)

           {

               BaseRemove(client);

           }

     

           /// <summary>

           /// Clears this instance.

           /// </summary>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:34:29</remarks>

           public void Clear()

           {

               BaseClear();

           }

       }

    最后是最外层的group:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    /// <summary>

       /// Class MailServerSection 为入口:

       /// </summary>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:41:02</remarks>

       public class MailServerSection : ConfigurationSection   //继承配置文件中节

       {

           /// <summary>

           /// Gets the provider.:映射mailServerGroup节点的provider

           /// </summary>

           /// <value>The provider.</value>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:59</remarks>

           [ConfigurationProperty("provider", IsKey = true)]

           public string provider { get { return this["provider"] as string; } }

     

           /// <summary>

           /// Gets or sets the mail servers.:映射新添加的节点mailServers节点;这个节点下还包含了若干个mailServer节点,因此它是一个集合类

           /// </summary>

           /// <value>The mail servers.</value>

           /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:56</remarks>

           [ConfigurationProperty("mailServers", IsDefaultCollection = false)]

           public MailServerCollection MailServers

           {

               get

               {

                   return this["mailServers"] as MailServerCollection;

               }

               set

               {

                   this["mailServers"] = value;

               }

     

           }

       }

    同样,关联处理类和节点:

    注意,GetSection方法读取的是configSections节点,这个节点在web.config配置文件中,它比较特殊,必须放置于首节点,也就是说,在它之前不能有其它类型的节点。

    1

    2

    <configSections>

    <section name="mailServerGroup" type="命名空间.MailServerSection,命名空间"/>  

    </configSections>

    示例:

     1 <?xml version="1.0" encoding="utf-8" ?>
     2 <configuration>
     3   
     4   <configSections>
     5     <section name="webUrlGroup" type="WebCefSharp.WebUrlSection,WebCefSharp"/>
     6   </configSections>
     7 
     8   <webUrlGroup webAtt1="webAtt123">
     9     <webUrls>
    10       <!-- 网页地址1 -->
    11       <webUrl name="web1" url="http://www.mytm3.com/yhdata/view.html?id=4" att1="1" att2="2" />
    12 
    13       <!-- 网页地址2 -->
    14       <webUrl name="web2" url="http://www.baidu.com" att1="3" att2="4" />
    15 
    16       <!-- 网页地址3 -->
    17       <webUrl name="web3" url="https://www.163.com/" att1="1" att2="2" />
    18     </webUrls>
    19   </webUrlGroup>
    20   
    21   <startup>
    22     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    23   </startup>
    24   
    25   <appSettings>
    26     <!--软件唯一编码(由开发商提供)-->
    27     <add key="ExeCode" value="010010101011"/>
    28   </appSettings>
    29 
    30   
    31 </configuration>

    之后做个测试:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    class Program

        {

            static void Main(string[] args)

            {

                Test();

     

            }

     

            /// <summary>

            /// Tests this instance.:读取节点值示例

            /// </summary>

            /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 23:04:53</remarks>

            private static void Test() {

     

                MailServerSection mailSection = (MailServerSection)ConfigurationManager.GetSection("mailServerGroup");

                Console.WriteLine("MailServerSection 的provider属性值:"+mailSection.provider);

                foreach (MailServerElement config in mailSection.MailServers)

                {

                    Console.WriteLine("----------------------------------");

                    Console.WriteLine("client值为:"+config.Client);

                    Console.WriteLine("address值为:"+config.Address);

                    Console.WriteLine("username值为:"+config.UserName);

                    Console.WriteLine("password值为:"+config.Password);

                    Console.WriteLine("----------------------------------");

                }

     

                Console.ReadKey();

     

            }

     

        }

    以上就是.Net 配置文件——继承ConfigurationSection实现自定义处理类处理自定义配置节点 的内容

    ---------------------------------------------------------------------------------------------------------------

    ---------------------------------------------------------------------------------------------------------------

    ---------------------------------------------------------------------------------------------------------------

    C# 创建自定义配置节点1

    转载:https://www.cnblogs.com/geduocoding/p/9279064.html

    转载:http://www.educity.cn/develop/495003.html

          在.Net应用程序中我们经常看到VS为我们生成的项目工程中都会含有app.config或者web.connfig这样的文件.这个文件就是我们所说的应用程序配置文件.在这个文件里面记述着一些与我们的应用程序相关的信息如数据库连接认证模式等我们在程序中可以利用ConfigurationManager的ConnectionStrings属性方便的获取配置文件中的数据库连接字符串信息。

    可是有时候我们需要对它进行一些扩展加入一些自定义的元素而不是仅仅使用默认的配置.例如我们可能需要在程序启动时动态的加载某个类并对其进行初始化,而这个类或者初始化数据是我们在程序设计的时候所不知道的.相信大家都碰到过这样的问题,这里就不做过多的解释了.最好的办法无非就是把这些可能会改变的东西写进配置文件里面,到你能够确定的时候你只需要修改配置文件就Ok了,而不是产品马上上线的时候还用秒钟打开VS去改代码。

    添加一些自定义的元素到配置文件中是很容易的只需要两步就能搞定:

       1、 在<configSections>节点中注册你所要定义的节点名称及用于处理该节点的配置节处理程序代码如下:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="dbFactory"  type ="DbFactory.Configuration.DbFactorySection,DbFactory.Configuration" />
      </configSections>
    </configuration>

     

      2、 在适当的位置添加自定义的节点代码如下:

    复制代码
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="dbFactory" type ="DbFactory.Configuration.DbFactorySection,DbFactory.Configuration" />
      </configSections>
      <dbFactory >
        <default factory="sql"></default>
        <factorys>
          <add name="sql"  assembly="HelloData"  class="SqlDbFactory" />
          <add name="oracle" assembly="HelloData" class="OracleDbFactory" />        
        </factorys>      
      </dbFactory>
    </configuration>
    复制代码
        
     自定义节点算是添加完了,可是我们怎么在程序里面获取这些配置信息呢?相信大家很多都是玩XML的高手,用SystemXml下的一些类写个XML的解析类把我们自定义的节点信息解析出来不就得到我们想要的东西了吗?的确是这样大牛果然是大牛小弟实在是佩服!可是如果用这种方式来实现的话小弟就实在没有必要写这篇博文了。

    Net框架为我们实现了很多的配置API来简化我们对配置文件的操作。在第一个步骤中我们提到了配置节处理程序这个程序就是用来读写我们自定义的节点信息的。那么我们又如何来实现一个配置节处理程序呢?首先我们来了解一下相关的类和概念。

    ConfigurationSection:自定义节点都要继承该类以提供对自定义配置节的自定义处理和编程访问。

    ConfigurationElement:它表示配置文件内的一个元素。

    ConfigurationElementCollection:它表示包含一个子元素集合的配置元素。

    有了这些类我们可以归纳起来配置文件中有两种类型的配置元素。

    第一:单一型配置元素即继承于ConfigurationElement的元素它不包含任何子元素。

    第二:集合型配置元素即继承于ConfigurationElementCollection的元素它包含一个子元素集合。

    概念往往都比较抽象,要搞清楚这些东西我们还是结合我们上面给的例子来具体说明一下。

    在<dbFactory> 配置节中有两个元素,即<default>和<factorys>而<factorys>元素又包含了两个子元素。那么在这里<default>就是单一型配置元素,而<factorys>就是集合型配置元素我们需要分别实现与这些元素相对应的类及其属性。

    <default>元素它是一个单一型的元素,所以我们继承ConfigurationElement该元素中有一个factory属性那么我们在类中进行相应的定义代码如下:

    代码

    复制代码
            public class DefaultElement : ConfigurationElement
            {
                [ConfigurationProperty("factory")]
                public string Factory
                {
                    get { return this["factory"] as string; }
                    set { this["factory"] = value; }
                }
            }
    复制代码

    注意在属性定义上面我们需要注册该属性的ConfigurationProperty特性。

    <factorys>子元素

    代码:

    复制代码
    public class FactoryElement : ConfigurationElement
            {
                [ConfigurationProperty("name")]
                public string Name
                {
                    get
                    {
                        return this["name"] as string;
                    }
                    set
                    {
                        this["name"] = value;
                    }
                }
                [ConfigurationProperty("assembly")]
                public string Assembly
                {
                    get
                    {
                        return this["assembly"] as string;
                    }
                    set
                    {
                        this["assembly"] = value;
                    }
                }
                [ConfigurationProperty("class")]
                public string Class
                {
                    get
                    {
                        return this["class"] as string;
                    }
                    set
                    {
                        this["class"] = value;
                    }
                }
            }
        }
    复制代码

    <factorys>元素是集合型元素继承ConfigurationElementCollection

    代码:

    复制代码
      public class FactoryElements : ConfigurationElementCollection
            {
                protected override ConfigurationElement CreateNewElement()
                {
                    return new FactoryElement();
                }
                protected override object GetElementKey(ConfigurationElement element)
                {
                    return ((FactoryElement)element).Name;
                }
                public FactoryElement this[string name]
                {
                    get
                    {
                        return BaseGet(name) as FactoryElement;
                    }
                }
            }
    复制代码

        ConfigurationElementCollection类是个抽象类,你应该显示的实现它的CreateNewElement方法和GetElementKey方法。

    <dbFactory>节点继承于ConfigurationSection

    代码

     

    复制代码
            public class DbFactorySection : ConfigurationSection
            {
                [ConfigurationProperty("default")]
                public DefaultElement DefaultFactory
                {
                    get { return this["default"] as DefaultElement; }
                    set { this["default"] = value; }
                }
                [ConfigurationProperty("factorys")]
    
                public FactoryElements Factorys
                {
                    get
                    {
                        return this["factorys"] as FactoryElements;
                    }
                    set
                    {
                        this["factorys"] = value;
                    }
                }
    
    
            }
    复制代码
         配置节处理程序终于写完了。把这四个类放在同一个工程目录下,编译成一个DLL,在你需要获取配置信息的地方引用这个DLL,用DbFactorySection section = ConfigurationManager.GetSection( “dbFactory”) as DbFactorySection;试试section是不是你想要的东西呢?
  • 相关阅读:
    ibatis 中isNull, isNotNull与isEmpty, isNotEmpty区别
    关于异常Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
    php 利用fsockopen GET/POST 提交表单及上传文件
    php发送get、post请求获取内容的几种方法
    修改WampServer的默认端口
    SQL Server2008附加数据库之后显示为只读时解决方法
    Linux一键安装web环境全攻略(阿里云服务器)
    如何从Windows远程上传文件到Linux(例如CentOS 7)
    在CentOS上搭建PHP服务器环境
    linux(系统centos6.5)常用命令总结
  • 原文地址:https://www.cnblogs.com/zouhao/p/13092697.html
Copyright © 2011-2022 走看看