.Net Web應用程序提供了很強大的 Web.Config功能,我們很多的系統可能已經習慣在Web.Config中進行配置,可是使用Web.Config進行一些配置,會有一些不太順暢的特性,比如:修改Web.Config 後,Web應用程序會出現錯誤頁面並且需要重新登錄,Web.Config配置過程不是很方便,即使通過安裝包進行Web.Config的設置,.Net 安裝嚮導能提供的入口也是有限的。。。。。
通過Cache機制實現一個通用的配置管理模塊
設計目標:
1、 高速讀取配置信息
2、 統一的配置維護管理方便進行配置
3、 新的配置模塊及維護不需要再進行二次開發
大致設計思路
1、 通過Cache機制對配置文件的內容進行緩存,緩存的失效依賴於配置文件
2、 在開發基礎組件庫中實現一個 CacheHelper 類統一讀取配置信息
3、 根據配置文件自動生成配置維護界面,實現統一的配置維護
代碼參考:
CacheHelper.cs 統一讀取配置信息的一個類, 打開配置文件,讀取相關的配置信息到HashTable ,並保存到 Cache中,Cache中存在則直接取Cache中的內容,否則重新讀取文件,這樣做到高速讀取。
using System;
using System.Collections;
using System.Web;
using System.Web.Caching;
using System.Xml;
namespace Epower.DevBase.BaseTools
{
/// <summary>
/// ConfigHelper 的摘要說明。
/// 自定義的系統參數配置文件的讀取工具類
/// </summary>
public class ConfigHelper
{
/// <summary>
/// 取~/Config/CommonConfig.xml中某個參數名對應的參數值
/// </summary>
/// <param name="ParameterName">參數名</param>
/// <returns>參數值</returns>
public static string GetParameterValue(string ParameterName)
{
return GetParameterValue("EpowerConfig", ParameterName);
}
/// <summary>
/// 取某個參數配置文件中某個參數名對應的參數值
/// 參數配置文件
/// 1、必須存放於"~/Config/"目錄下面,以.xml爲後綴
/// 2、配置格式參見~/Config/CommonConfig.xml
/// </summary>
/// <param name="ConfigName">配置文件的文件名,不要後綴</param>
/// <param name="ParameterName">參數名</param>
/// <returns>參數值</returns>
public static string GetParameterValue(string ConfigName, string ParameterName)
{
Hashtable CommonConfig = GetConfigCache(ConfigName);
if (CommonConfig.ContainsKey(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 = HttpRuntime.Cache;
if (cache[CacheName] == null)
{
string ConfigPath = null;
#region 取應用程序根物理路徑
try
{
ConfigPath = HttpRuntime.AppDomainAppPath;
}
catch (System.ArgumentException ex)
{
}
if (ConfigPath == null) throw new Exception("系統異常,取不到應用程序所在根物理路徑!");
#endregion
string ConfigFile = ConfigPath + "Config//" + ConfigName + ".xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(ConfigFile);
XmlNode oNode = xmlDoc.DocumentElement;
if (oNode.HasChildNodes)
{
XmlNodeList oList = oNode.ChildNodes;
for (int i = 0; i < oList.Count; i++)
{
CommonConfig.Add(oList[i].Attributes["Name"].Value, oList[i].Attributes["Value"].Value);
}
}
cache.Insert(CacheName, CommonConfig, new CacheDependency(ConfigFile));
}
else
CommonConfig = (Hashtable) cache[CacheName];
return CommonConfig;
}
}
}
代碼參考:
frmConfigSet.aspx 以配置文件名爲參數,根據配置文件自動生成維護界面,並進行維護,保存。
HtmlTable tab = new HtmlTable();
tab.ID = "tDynamic";
tab.Attributes.Add("width", "80%");
tab.Attributes.Add("class", "tablebody");
HtmlTableRow tr = new HtmlTableRow();
HtmlTableCell tc = new HtmlTableCell();
XmlNodeList nodes = xmldoc.DocumentElement.SelectNodes("Item");
string sConfigContent = "";
if (xmldoc.DocumentElement.Attributes["ConfigContent"] != null)
sConfigContent = xmldoc.DocumentElement.Attributes["ConfigContent"].Value;
string sItemDesc = "";
int iRow = 0;
foreach (XmlNode node in nodes)
{
iRow++;
tr = new HtmlTableRow();
tr.ID = "tDynamicRow" + iRow;
AddControlByNode(node,iRow,ref tr);
AddControl(tab, tr);
sItemDesc = "";
if (node.Attributes["ItemContent"] != null)
sItemDesc = node.Attributes["ItemContent"].Value;
if (sItemDesc.Length > 0)
{
//添加描述行
iRow++;
tr = new HtmlTableRow();
tr.ID = "tDyContectRow" + iRow;
tc = new HtmlTableCell();
tc.ID = "tDyContectTD_" + iRow;
tc.InnerText = sItemDesc;
tc.Attributes.Add("class", "list");
tc.Attributes.Add("colspan", "2");
AddControl(tr, tc);
AddControl(tab, tr);
}
}
/// <summary>
/// 獲取設置的控件
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private Control GetSettingControl(XmlNode node)
{
string strCtrlType = node.Attributes["ControlType"].Value;
string strValue = node.Attributes["Value"].Value;
Control control;
switch (strCtrlType.ToLower())
{
case "text":
control = new TextBox();
control.ID = "tDynamic" + "_txt_" + node.Attributes["Name"].Value;
((TextBox)control).Width = new Unit("70%");
((TextBox)control).Attributes.Add("Tag", node.Attributes["Name"].Value);
((TextBox)control).Text = strValue;
break;
case "checkbox":
control = new CheckBox();
control.ID = "tDynamic" + "_chk_" + node.Attributes["Name"].Value;
((CheckBox)control).Attributes.Add("Tag", node.Attributes["Name"].Value);
((CheckBox)control).Text = node.Attributes["Desc"].Value;
if (strValue.ToLower() == "false")
{
((CheckBox)control).Checked = false;
}
else
{
((CheckBox)control).Checked = true;
}
break;
case "droplist":
control = new DropDownList();
control.ID = "tDynamic" + "_drp_" + node.Attributes["Name"].Value;
((DropDownList)control).Attributes.Add("Tag", node.Attributes["Name"].Value);
((DropDownList)control).Width = new Unit("70%");
string[] sItems = node.Attributes["Dict"].Value.Split(",".ToCharArray());
for (int i = 0; i < sItems.Length; i++)
{
string[] arr = sItems[i].Split("|".ToCharArray());
((DropDownList)control).Items.Add(new ListItem(arr[1], arr[0]));
}
((DropDownList)control).SelectedValue = strValue;
break;
case "datetime":
control = (Epower.ITSM.Web.Controls.CtrDateAndTime)LoadControl("~/controls/ctrdateandtime.ascx");
((Epower.ITSM.Web.Controls.CtrDateAndTime)control).ShowTime = false;
control.ID = "tDynamic" + "_date_" + node.Attributes["Name"].Value;
((Epower.ITSM.Web.Controls.CtrDateAndTime)control).Attributes.Add("Tag", node.Attributes["Name"].Value);
break;
default:
control = null;
break;
}
return control;
}
配置文件範例:
<?xml version="1.0" encoding="utf-8"?>
<EmailConfig Title="郵件服務設置" ConfigContent="郵件服務器設置,服務器設置,.服務器設置,.服務器設置,.服務器設置,.服務器設置,.服務器設置,.">
<Item Name="smtpserver" Value="smtp.vip.sina.com" Desc="郵件SMTP服務器" ControlType="TEXT" ItemContent="設置郵件SMTP服務器的地址,格式:smtp.vip.sina.com">
</Item>
<Item Name="smtpfrom" Value="[email protected]" Desc="郵件地址" ControlType="TEXT" ValidationExpression="^/w+((-/w+)|(/./w+))*/@[A-Za-z0-9]+((/.|-)[A-Za-z0-9]+)*/.[A-Za-z0-9]+$">
</Item>
<Item Name="smtpUserName" Value="cancankf" Desc="帳戶" ControlType="TEXT">
</Item>
<Item Name="smtppsd" Value="123456" Desc="密碼" ControlType="TEXT">
</Item>
<Item Name="smtpSSL" Value="false" Desc="是否SSL" ControlType="CHECKBOX">
</Item>
<Item Name="smtpPort" Value="0" Desc="端口" ControlType="TEXT" ValidationExpression="/d{0,9}">
</Item>
<Item Name="smtpDateTest" Value="2008-07-21" Desc="測試日期" ControlType="DATETIME">
</Item>
<Item Name="smtpListTest" Value="0" Desc="測試列表" ControlType="DROPLIST" Dict="0|值1,1|值2,2|值3">
</Item>
</EmailConfig>
讀取配置信息範例
string sSmtpServer = ConfigHelper.GetParameterValue("EmailConfig","smtpserver");
E8.Net開源架構提供了這一功能的全部代碼。用戶可以直接使用或參考,並在此基礎上更加的完善。
E8.Net工作流架構大量節約用戶的開發成本爲企業應用開發提供起點,提升軟件生產力,歡迎訪問:http://www.feifanit.com.cn