熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

通過Cache實現通用的配置管理

2022-06-13   來源: .NET編程 

  Net Web應用程序提供了很強大的 WebConfig功能我們很多的系統可能已經習慣在WebConfig中進行配置可是使用WebConfig進行一些配置會有一些不太順暢的特性比如修改WebConfig 後Web應用程序會出現錯誤頁面並且需要重新登錄WebConfig配置過程不是很方便即使通過安裝包進行WebConfig的設置Net 安裝向導能提供的入口也是有限的

  通過Cache機制實現一個通用的配置管理模塊

  設計目標

   高速讀取配置信息

   統一的配置維護管理方便進行配置

   新的配置模塊及維護不需要再進行二次開發

  大致設計思路

   通過Cache機制對配置文件的內容進行緩存緩存的失效依賴於配置文件

   在開發基礎組件庫中實現一個 CacheHelper 類統一讀取配置信息

   根據配置文件自動生成配置維護界面實現統一的配置維護

  代碼參考

  CacheHelpercs  統一讀取配置信息的一個類 打開配置文件讀取相關的配置信息到HashTable 並保存到 Cache中Cache中存在則直接取Cache中的內容否則重新讀取文件這樣做到高速讀取

    using System;
using SystemCollections;
using SystemWeb;
using SystemWebCaching;
using SystemXml;

namespace EpowerDevBaseBaseTools
{
    /// <summary>
    /// ConfigHelper 的摘要說明
    /// 自定義的系統參數配置文件的讀取工具類
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        /// 取~/Config/CommonConfigxml中某個參數名對應的參數值
        /// </summary>
        /// <param name=ParameterName>參數名</param>
        /// <returns>參數值</returns>
        public static string GetParameterValue(string ParameterName)
        {
            return GetParameterValue(EpowerConfig ParameterName);
        }

        /// <summary>
        /// 取某個參數配置文件中某個參數名對應的參數值
        /// 參數配置文件
        ///        必須存放於~/Config/目錄下面xml為後綴
        ///        配置格式參見~/Config/CommonConfigxml
        /// </summary>
        /// <param name=ConfigName>配置文件的文件名不要後綴</param>
        /// <param name=ParameterName>參數名</param>
        /// <returns>參數值</returns>
        public static string GetParameterValue(string ConfigName string ParameterName)
        {
            Hashtable CommonConfig = GetConfigCache(ConfigName);

            if (CommonConfigContainsKey(ParameterName))
                return CommonConfig[ParameterName]ToString();
            else
                throw new Exception(參數( + ParameterName + )沒有定義請檢查配置文件!);
        }

        /// <summary>
        /// 將配置的參數轉換成Hashtable並存入緩存配置文件修改後自動更新緩存
        /// </summary>
        /// <param name=ConfigName></param>
        /// <returns></returns>
        private static Hashtable GetConfigCache(string ConfigName)
        {
            string CacheName = Config_ + ConfigName;

            Hashtable CommonConfig = new Hashtable();
            Cache cache = HttpRuntimeCache;

            if (cache[CacheName] == null)
            {
                string ConfigPath = null;

                #region 取應用程序根物理路徑
                try
                {
                    ConfigPath = HttpRuntimeAppDomainAppPath;
                }
                catch (SystemArgumentException ex)
                {
                }

                if (ConfigPath == null) throw new Exception(系統異常取不到應用程序所在根物理路徑!);
                #endregion

                string ConfigFile = ConfigPath + Config\\ + ConfigName + xml;

                XmlDocument xmlDoc = new XmlDocument();
                xmlDocLoad(ConfigFile);

                XmlNode oNode = xmlDocDocumentElement;

                if (oNodeHasChildNodes)
                {
                    XmlNodeList oList = oNodeChildNodes;

                    for (int i = ; i < oListCount; i++)
                    {
                        CommonConfigAdd(oList[i]Attributes[Name]Value oList[i]Attributes[Value]Value);
                    }
                }

                cacheInsert(CacheName CommonConfig new CacheDependency(ConfigFile));
            }
            else
                CommonConfig = (Hashtable) cache[CacheName];

            return CommonConfig;
        }
    }
}

  代碼參考

  frmConfigSetaspx 以配置文件名為參數根據配置文件自動生成維護界面並進行維護保存

    HtmlTable tab = new HtmlTable();
            tabID = tDynamic;
            tabAttributesAdd(width %);
            tabAttributesAdd(class tablebody);
            HtmlTableRow tr = new HtmlTableRow();
            HtmlTableCell tc = new HtmlTableCell();

            XmlNodeList nodes = xmldocDocumentElementSelectNodes(Item);

            string sConfigContent = ;
            if (xmldocDocumentElementAttributes[ConfigContent] != null)
                sConfigContent = xmldocDocumentElementAttributes[ConfigContent]Value;


            string sItemDesc = ;
          
            int iRow = ;
            foreach (XmlNode node in nodes)
            {
                iRow++;
                tr = new HtmlTableRow();
                trID = tDynamicRow + iRow;
                AddControlByNode(nodeiRowref tr);

                AddControl(tab tr);

                sItemDesc = ;
                if (nodeAttributes[ItemContent] != null)
                    sItemDesc = nodeAttributes[ItemContent]Value;

                if (sItemDescLength > )
                {
                    //添加描述行
                    iRow++;
                    tr = new HtmlTableRow();
                    trID = tDyContectRow + iRow;

                    tc = new HtmlTableCell();
                    tcID = tDyContectTD_ + iRow;
                    tcInnerText = sItemDesc;
                    tcAttributesAdd(class list);
                    tcAttributesAdd(colspan );

                    AddControl(tr tc);

                    AddControl(tab tr);
                }

            }

    /// <summary>
        ///  獲取設置的控件
        /// </summary>
        /// <param name=node></param>
        /// <returns></returns>
        private Control GetSettingControl(XmlNode node)
        {
            string strCtrlType = nodeAttributes[ControlType]Value;
            string strValue = nodeAttributes[Value]Value;
            Control control;
            switch (strCtrlTypeToLower())
            {
                case text:
                    control = new TextBox();
                    controlID = tDynamic + _txt_ + nodeAttributes[Name]Value;
                    ((TextBox)control)Width = new Unit(%);
                    ((TextBox)control)AttributesAdd(Tag nodeAttributes[Name]Value);
                    ((TextBox)control)Text = strValue;
                    break;
                case checkbox:
                    control = new CheckBox();
                    controlID = tDynamic + _chk_ + nodeAttributes[Name]Value;
                    ((CheckBox)control)AttributesAdd(Tag nodeAttributes[Name]Value);
                    ((CheckBox)control)Text =  nodeAttributes[Desc]Value;
                    if (strValueToLower() == false)
                    {
                        ((CheckBox)control)Checked = false;
                    }
                    else
                    {
                        ((CheckBox)control)Checked = true;
                    }
                    break;
                case droplist:
                    control = new DropDownList();
                    controlID = tDynamic + _drp_ + nodeAttributes[Name]Value;
                    ((DropDownList)control)AttributesAdd(Tag nodeAttributes[Name]Value);
                    ((DropDownList)control)Width = new Unit(%);
                    string[] sItems = nodeAttributes[Dict]ValueSplit(ToCharArray());
                    for (int i = ; i < sItemsLength; i++)
                    {
                        string[] arr = sItems[i]Split(|ToCharArray());
                        ((DropDownList)control)ItemsAdd(new ListItem(arr[] arr[]));
                    }
                    ((DropDownList)control)SelectedValue = strValue;
                    break;
                case datetime:

                    control = (EpowerITSMWebControlsCtrDateAndTime)LoadControl(~/controls/ctrdateandtimeascx);
                   ((EpowerITSMWebControlsCtrDateAndTime)control)ShowTime = false;
                    controlID = tDynamic + _date_ + nodeAttributes[Name]Value;

                    ((EpowerITSMWebControlsCtrDateAndTime)control)AttributesAdd(Tag nodeAttributes[Name]Value);
                    break;
                default:
                    control = null;
                    break;

            }

            return control;

        }

  配置文件范例

  讀取配置信息范例
 
 string sSmtpServer = ConfigHelperGetParameterValue(EmailConfigsmtpserver);

    <?xml version= encoding=utf?>
<EmailConfig Title=郵件服務設置 ConfigContent=郵件服務器設置服務器設置服務器設置服務器設置服務器設置服務器設置服務器設置>
  <Item Name=smtpserver Value= Desc=郵件SMTP服務器 ControlType=TEXT ItemContent=設置郵件SMTP服務器的地址格式:>
  </Item>
  <Item Name=smtpfrom Value=c Desc=郵件地址 ControlType=TEXT ValidationExpression=^\w+((\w+)|(\\w+))*\@[AZaz]+((\|)[AZaz]+)*\[AZaz]+$>
  </Item>
  <Item Name=smtpUserName Value=cancankf Desc=帳戶 ControlType=TEXT>
  </Item>
  <Item Name=smtppsd Value= Desc=密碼 ControlType=TEXT>
  </Item>
  <Item Name=smtpSSL Value=false Desc=是否SSL ControlType=CHECKBOX>
  </Item>
  <Item Name=smtpPort Value= Desc=端口 ControlType=TEXT ValidationExpression=\d{}>
  </Item>
  <Item Name=smtpDateTest Value= Desc=測試日期 ControlType=DATETIME>
  </Item>
  <Item Name=smtpListTest Value= Desc=測試列表 ControlType=DROPLIST Dict=|值|值|值>
  </Item>
</EmailConfig>

  


From:http://tw.wingwit.com/Article/program/net/201311/13658.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.