創建web.config自定義配置部分

 今天看了一下web.config創建自定義配置部分,雖然大多數常用的應用程序專用的設置可以保存在appsettings元素中,但有時還是需要添加自定義的配置元素,增強可用的配置元素集.即是我們用不到,分析一個自定義的配置部分還是對我們更好的理解如何解析web.config有好處的.
      以下舉例說明,假設我們希望應用程序能夠用acme元素指定自定義元素,acme元素包含在一個新的稱爲acmegroup的部分中,比如有一下元素:font,backgroundColor,underlineLinks,horizontalWidth,verticalWidth.
webconfig代碼如下:

<configuration>

  <configSections>

    <sectionGroup name="acmeGroup">

  <section name="acme"

          type="EssentialAspDotNet.Config.AcmeConfigHandler, AcmeConfigHandler"

  />

    </sectionGroup>

  </configSections>

 

  <myGroup>

    <add key="font" value="Courier New"/>

    <add key="backgroundColor" value="Green"/>

    <add key="underlineLinks" value="true"/>

    <add key="horizontalWidth" value="600"/>

    <add key="verticalWidth" value="800"/>

  </myGroup>

 

  <acmeGroup>

    <acme>

  <font>Courier New</font>

  <backgroundColor>Green</backgroundColor>

      <underlineLinks>true</underlineLinks>

      <horizontalWidth>600</horizontalWidth>

      <verticalWidth>800</verticalWidth>

</acme>

  </acmeGroup>

 

  <appSettings>

    <add key="DSN"

         value="server=localhost;uid=sa;pwd=;database=pubs"

    />

    <add key="bgColor" value="blue" />

  </appSettings>

</configuration>


 自定義配置設置
//AcmeSettings.cs

using System;

namespace EssentialAspDotNet.Config
{
public class AcmeSettings
{
public string Font;
public string BackgroundColor;
public bool UnderlineLinks;
public int HorizontalWidth;
public int VerticalWidth;

public override string ToString()
{
return string.Format("AcmeSettings: Font={0}, BackgroundColor={1}, UnderlineLinks={2}, HorizontalWidth={3}, VerticalWidth={4}",
Font, BackgroundColor, UnderlineLinks, HorizontalWidth, VerticalWidth);
}
}
}


自定義配置部分處理程序
//AcmeConfigHandler.cs
using System;

using System.Xml;

using System.Configuration;

using System.Web;

using System.Web.Configuration;

 

namespace EssentialAspDotNet.Config

{

  public class AcmeConfigHandler : IConfigurationSectionHandler

  {

    public object Create(object parent, object input, XmlNode node)

    {

      AcmeSettings aset = new AcmeSettings();

 

      foreach (XmlNode n in node.ChildNodes)

      {

        switch (n.Name)

        {

          case ("font"):

            aset.Font = n.InnerText;

            break;

          case ("backgroundColor"):

            aset.BackgroundColor = n.InnerText;

            break;

          case ("underlineLinks"):

            aset.UnderlineLinks = bool.Parse(n.InnerText);

            break;

          case ("horizontalWidth"):

            aset.HorizontalWidth = int.Parse(n.InnerText);

            break;

          case ("verticalWidth"):

            aset.VerticalWidth = int.Parse(n.InnerText);

            break;

        }

      }

      return aset;

    }

  }

}

未完待續:訪問自定義配置信息,使用NameValueFileSectionHandler

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章