.NET Framework在web.config或app.config中默认提供了很多种设置,以便能够改变应用程序内嵌组件的行为,例如<connectionStrings>、<httpHandlers>、<sessionState>等等,这对于常规情况下的一般程序员而言是足够用的,也是非常方便的。但是我们越来越多地发现需要自己来控制一系列设置的集合 - 有时是面向组件的(自定义的或第三方提供的),有时是应用程序中使用的一系列值的集合。

  .config虽然默认提供了自定义设置(在<appSettings/>节点下),但是它太弱了,仅仅只支持键值对(key/value)

<add key="myKey" value="myValue"/>

  虽然键值对在大多数情况下也是很有帮助的,但是它对于健壮的组件、复杂的设置而言是不够灵活的,甚至显得过于简单。幸运的是,微软为我们提供了一种以编程的方式来访问自定义的配置/设置。

一、The Configuration Section

  先看如下的配置设置,含义很明确:定义一些rss,有名字、地址、以及是否缓存

  <feedRetriever>
<feeds>
<add name="cnblogs" url="http://www.cnblogs.com/rss/" />
<add name="CoolShell" url="http://coolshell.cn/rss/" cache="false" />
</feeds>
</feedRetriever>

  接下来我们就以代码来展示如何调用

二、Writing the Configuration Handler

1. Representing the <add/> Element

  每一个ConfigurationElement对象都是作为其内部属性(properties)集合的索引器而存在,再通过.NET提供了另一个属性(Attribute)-- 从而使得<add/>(.config中的自定义节点,取名add完全是基于微软是如此命名故为保持一致而为之)节点的attributes与FeedElement的properties进行关联(map),具体代码如下

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web; namespace WebAppCustomConfiguration
{
public class FeedElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
set { }
} [ConfigurationProperty("url", IsRequired = true, DefaultValue = "http://localhost")]
[RegexStringValidator(@"http?\://\S+")]
public string Url
{
get { return (string)this["url"]; }
set { }
} [ConfigurationProperty("cache", IsRequired = false, DefaultValue = true)]
public bool Cache
{
get { return (bool)this["cache"]; }
set { }
}
}
}

The following list is a complete list of possible parameters:

  • DefaultValue – Gets or sets the default value for the decorated property. This parameter is not required.
  • IsDefaultCollection – Gets or a sets a Boolean value indicating whether the property is the default property collection for the decorated property. This parameter is not required, and the default is false.
  • IsKey – Gets or sets a Boolean value indicating whether this property is a key property for the decorated element property. This parameter is not required, and its default value is false.
  • IsRequired – Gets or sets a Boolean value indicating whether the decorated element property is required. This parameter is not required, and its default value is false.

2. Writing an Element Collection Class

  类ConfigurationElementCollection包含有好几个成员,但是只有两个标记为abstract,所以最简单的ConfigurationElementCollection只需实现这两个方法

  • CreateNewElement() – 创建一个新的ConfigurationElement对象(本例而言就是FeedElement);
  • GetElementKey() – 获得指定配置节点的key (本例而言就是FeedElement的Name属性(property).
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web; namespace WebAppCustomConfiguration
{
[ConfigurationCollection(typeof(FeedElement))]
public class FeedElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new FeedElement();
} protected override object GetElementKey(ConfigurationElement element)
{
return ((FeedElement)element).Name;
}
}
}

3. Writing the FeedRetreiverSection Class

  此Class较为简单,只需编程实现能够访问<feeds />节点即可,具体而言就是一属性(Property)

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web; namespace WebAppCustomConfiguration
{
public class FeedRetrieverSection : ConfigurationSection
{
[ConfigurationProperty("feeds", IsDefaultCollection = true)]
public FeedElementCollection Feeds
{
get { return (FeedElementCollection)this["feeds"]; }
set { }
}
}
}

4. Modifying web.config

  下面的配置就不说了

<section name="feedRetriever" type="WebAppCustomConfiguration.FeedRetrieverSection"/>

5. Accessing Configuration Data from Code

  调用的代码如下,简单不解释

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web; namespace WebAppCustomConfiguration
{
public class FeedRetriever
{
public static FeedRetrieverSection _Config = ConfigurationManager.GetSection("feedRetriever") as FeedRetrieverSection; public static void GetFeeds()
{
foreach (FeedElement feedElement in _Config.Feeds)
{
// make request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(feedElement.Url);
WebProxy proxy = new WebProxy("ip address:port", true);
proxy.Credentials = new NetworkCredential("username", "password", "domain");
request.Proxy = proxy;
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK)
{
string feedData = String.Empty; using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
feedData = reader.ReadToEnd();
} if (feedElement.Cache)
{
// filename of cache file
string filename = String.Format("{0}_{1}.xml", feedElement.Name, DateTime.Now.Ticks); // cache file
using (StreamWriter writer = new StreamWriter(@"D:\Deployment\Result\" + filename))
{
writer.Write(feedData);
}
}
}
}
}
}
}

.NET中如何自定义配置节点的更多相关文章

  1. [转]通过继承ConfigurationSection,在web.config中增加自定义配置

    本文转自:http://www.blue1000.com/bkhtml/2008-02/55810.htm 前几天写了一篇使用IConfigurationSectionHandler在web.conf ...

  2. VS2012 常用web.config配置解析之自定义配置节点

    在web.config文件中拥有一个用户自定义配置节点configSections,这个节点可以方便用户在web.config中随意的添加配置节点,让程序更加灵活(主要用于第三方插件的配置使用) 自定 ...

  3. App.config和Web.config配置文件的自定义配置节点

    前言 昨天修改代码发现了一个问题,由于自己要在WCF服务接口中添加了一个方法,那么在相应调用的地方进行更新服务就可以了,不料意外发生了,竟然无法更新.左查右查终于发现了问题.App.config配置文 ...

  4. ASP.NET系列:自定义配置节点的复用

    appSettings太简单,为每个程序自定义配置节点太复杂,因此要解决app.config&web.config自定义配置的复用问题. 1.读取不依赖SectionName,根节点可以定义为 ...

  5. 自定义配置节点configSections的使用

    //App.config <?xml version="1.0" encoding="utf-8" ?><configuration>  ...

  6. asp.net中web.config配置节点大全详解

    最近网上找了一些关于Web.config配置节点的文章,发现很多都写的都比较零散,而且很少有说明各个配置节点的作用和用法.搜索了一下发现有一篇写的不错,这里引用一下 原文地址 http://www.c ...

  7. .Net 配置文件--继承ConfigurationSection实现自定义处理类处理自定义配置节点

    除了使用继承IConfigurationSectionHandler的方法定义处理自定义节点的类,还可以通过继承ConfigurationSection类实现同样效果. 首先说下.Net配置文件中一个 ...

  8. .Net 配置文件——继承ConfigurationSection实现自定义处理类处理自定义配置节点

    除了使用继承IConfigurationSectionHandler的方法定义处理自定义节点的类,还可以通过继承ConfigurationSection类实现同样效果. 首先说下.Net配置文件中一个 ...

  9. asp.net中web.config配置节点大全详解【转】

    web.config 文件查找规则: (1)如果在当前页面所在目录下存在web.config文件,查看是否存在所要查找的结点名称,如果存在返回结果并停止查找. (2)如果当前页面所在目录下不存在web ...

随机推荐

  1. 再看case语句

    再看case语句,case语句只处理单条记录,而不是set 列名的使用,可以当做数值来使用: case when 后面简直是完美的的,什么东西都是能放的,只要是一个逻辑上的true/false的逻辑就 ...

  2. Tomcat 总体结构

    一.Tomcat 总体结构 1.Server(服务器)是Tomcat构成的顶级构成元素,所有一切均包含在Server中,Server的实现类StandardServer可以包含一个到多个Service ...

  3. 计算机网络【8】—— Get和Post请求的区别

    get参数通过url传递,post放在request body中. get请求在url中传递的参数是有长度限制的,而post没有. get比post更不安全,因为参数直接暴露在url中,所以不能用来传 ...

  4. P3223 [HNOI2012]排队

    题目描述 某中学有 n 名男同学,m 名女同学和两名老师要排队参加体检.他们排成一条直线,并且任意两名女同学不能相邻,两名老师也不能相邻,那么一共有多少种排法呢?(注意:任意两个人都是不同的) 输入输 ...

  5. java的break跳出多层循环

    记得大一的时候,语言学的不好,碰到了需要跳出双层循环的时候,就没有了办法.因为老师讲了goto然后说不要用goto...  自己就一直感觉这种跳出多层循环的想法是不可取的(好蠢) 下面用java代码的 ...

  6. 【刷题】BZOJ 2002 [Hnoi2010]Bounce 弹飞绵羊

    Description 某天,Lostmonkey发明了一种超级弹力装置,为了在他的绵羊朋友面前显摆,他邀请小绵羊一起玩个游戏.游戏一开始,Lostmonkey在地上沿着一条直线摆上n个装置,每个装置 ...

  7. iPhone X 的原深感模组

    物理与数字世界正走向融合,我们每天醒来的时间.睡眠时长.心率和步数等数据都会被分享.上传并转化为分析数据.无处不自的 AI.互联互通和软件平台将改变用户对现实的感知. 2018 年的 CES 展(国际 ...

  8. BZOJ 2337 XOR和路径 | 高斯消元 期望 位运算

    BZOJ 2337 XOR和路径 题解 这道题和游走那道题很像,但又不是完全相同. 因为异或,所以我们考虑拆位,分别考虑每一位: 设x[u]是从点u出发.到达点n时这一位异或和是1的概率. 对于所有这 ...

  9. 【uoj125】 NOI2013—书法家

    http://uoj.ac/problem/125 (题目链接) 题意 在网格上写“NOI”,每个格子上有一些权值,要求覆盖的权值最大.书写有一些规则. Solution 将“NOI”分成11个部分, ...

  10. Typhoon-v1.02 靶机入侵

      0x01 前言 Typhoon VM包含多个漏洞和配置错误.Typhoon可用于测试网络服务中的漏洞,配置错误,易受攻击的Web应用程序,密码破解攻击,权限提升攻击,后期利用步骤,信息收集和DNS ...