config文件自定义节点

来源:互联网 发布:阿里云的产品 编辑:程序博客网 时间:2024/06/02 02:30
 
一: 目标
在app.config或者web.config中自定义节点,效果如下
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  
<configSections>
    
<section name="DataBaseConfig" type="Configuration.Configuration.DataBaseConfigure,Configuration, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
  
</configSections>
  
<DataBaseConfig DefaultConnectionString="mahuiConnecting">
    
<ConnectionStrings>
      
<add name="mahuiConnecting"  ConnectionString="Connecting....1"  Provider="Configuration.Implements.OleDBConnectingProvider,Configuration,Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"></add>
      
<add name="XiaolinConnecting"  ConnectionString="Connecting....2"  Provider="Configuration.Implements.SqlConnectingProvider,Configuration,Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"></add>
      
<add name="Xiaolin2Connecting"  ConnectionString="Connecting....2"  Provider="Configuration.Implements.SqlConnectingProvider,Configuration,Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"></add>
     
     
<!-- <clear></clear>-->
      
<!--<remove name="Xiaolin2Connecting"/>-->
    
</ConnectionStrings>
   
</DataBaseConfig>  
</configuration>

二: 步骤

处理节点的类

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.ComponentModel;
using Configuration.Configuration.Common;

namespace Configuration.Configuration
{
    /// 
<summary>
    /// DataBaseConfig节点
    /// 
</summary>
    public class DataBaseConfigure:ConfigurationSection
    {
        public DataBaseConfigure()
        { 
        }
        [ConfigurationProperty("DefaultConnectionString")]
        public string DefaultConnectionString
        {
            get { return (string)this["DefaultConnectionString"]; }
            set { this["DefaultConnectionString"] = value; }
        }
        /// 
<summary>
        /// 子节点
        /// 
</summary>
        [ConfigurationProperty("ConnectionStrings", IsRequired = true)]
        public ConnectionStrings ConnectionStrings
        {
            get { return (ConnectionStrings)this["ConnectionStrings"]; }
            set { this["ConnectionStrings"] = value; }
        }
        public override string ToString()
        {
            return string.Format("DefaultConnectionString:{0}", this.DefaultConnectionString);
        }
    }
    /// 
<summary>
    /// ConnectionString子节点(允许单个节点)
    /// 
</summary>
    public class ConnectionString : ConfigurationElement
    {
        public ConnectionString()
        { 
        }       
        public ConnectionString(string name)
        {
            Name =name;
        }
        [ConfigurationProperty("ConnectionString", IsRequired = true)]
        public string ConnectingString
        {
            get { return (string)this["ConnectionString"]; }
            set { this["ConnectionString"] = value; }
        }

        [ConfigurationProperty("name",IsRequired=true,IsKey=true)]
        public string Name
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }
        [ConfigurationProperty("Provider", IsRequired = true)]
        [TypeConverter(typeof(AssemblyQualifiedTypeNameConverter))]
        public Type ConnectingProvider
        {
            get { return (Type)this["Provider"]; }
            set { this["Provider"] = value; }
        }

    }

    /// 
<summary>
    /// ConnectionString子节点(允许多个节点)
    /// 
</summary>
    public class ConnectionStrings : ConfigurationElementCollection
    {
        public ConnectionStrings()
        {
        }
        protected override ConfigurationElement CreateNewElement()
        {
            return new ConnectionString();
        }
        protected override ConfigurationElement CreateNewElement(string elementName)
        {
            return new ConnectionString(elementName);
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ConnectionString)element).Name;
        }
        public ConnectionString this[int index]
        {
            get
            { return (ConnectionString)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }
        public int IndexOf(ConnectionString con)
        {
            return BaseIndexOf(con);
        }
        new public ConnectionString this[string name]
        {
            get
            {
                return (ConnectionString)BaseGet(name);
            }
        }
        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.AddRemoveClearMap;
            }
        }

        #region 添加/移除/清除节点
        public new string AddElementName
        {
            get
            {
                return base.AddElementName;
            }

            set
            {
                base.AddElementName = value;
            }
        }

        public void Add(ConnectionString con)
        {
            BaseAdd(con);
        }
        protected override void
            BaseAdd(ConfigurationElement element)
        {
            BaseAdd(element, false);
        }


        public void Remove(ConnectionString con)
        {
            if (BaseIndexOf(con) >= 0)
                BaseRemove(con.Name);
        }
        public void Remove(string name)
        {
            BaseRemove(name);
        }
        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }
        public new string RemoveElementName
        {
            get
            {
                return base.RemoveElementName;
            }
        }

        public new string ClearElementName
        {
            get
            {
                return base.ClearElementName;
            }

            set
            {
                base.AddElementName = value;
            }

        }
        public void Clear()
        {
            BaseClear();
        }

        #endregion
        #region 集合数量
        public new int Count
        {
            get { return base.Count; }
        }
        #endregion     
    }

}

处理Type转换的类

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.ComponentModel;
using Configuration.Properties;

namespace Configuration.Configuration.Common
{
   
public  class AssemblyQualifiedTypeNameConverter : ConfigurationConverterBase
    
{
         
/// <summary>
        
/// Returns the assembly qualified name for the passed in Type.
        
/// </summary>
        
/// <param name="context">The container representing this System.ComponentModel.TypeDescriptor.</param>
        
/// <param name="culture">Culture info for assembly</param>
        
/// <param name="value">Value to convert.</param>
        
/// <param name="destinationType">Type to convert to.</param>
        
/// <returns>Assembly Qualified Name as a string</returns>

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        
{
            Type typeValue 
= value as Type;
            
if (typeValue == null)
            
{
                
throw new Exception("参数错误");
            }


            
if (typeValue != nullreturn (typeValue).AssemblyQualifiedName;
            
return null;
        }


        
/// <summary>
        
/// Returns a type based on the assembly qualified name passed in as data.
        
/// </summary>
        
/// <param name="context">The container representing this System.ComponentModel.TypeDescriptor.</param>
        
/// <param name="culture">Culture info for assembly.</param>
        
/// <param name="value">Data to convert.</param>
        
/// <returns>Type of the data</returns>

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        
{
            
string stringValue = (string)value;
            Type result 
= Type.GetType(stringValue, false);
            
if (result == null)
            
{
                
throw new Exception("参数错误");
            }


            
return result;
        }

    }

}

 配置中用到的两个类和代码中用到的一个接口

    interface ConnectingProvider
    
{
        
string GetDB();
    }

    
class OleDBConnectingProvider:ConnectingProvider
    
{
        
ConnectingProvider Members
    }

    
class SqlConnectingProvider : ConnectingProvider
    
{
        
ConnectingProvider Members
    }