项目常用解决方案之SystemSetting.xml文件的修改与读取
Winform及WPF项目中经常会用到类似SystemSetting.xml等类似的文件用于保存CLIENT的数据,比如登录过的用户名或密码以及其他设置。所以就想到一个解决方法,可以用到所有有此需求的项目中去,避免重复写代码。
1.创建一个Attribute类,用于指定属性在XML文件中的Path
public class NodePathAttribute : Attribute
{
public string NodePath
{
get;
set;
} public string DefaultValue
{
get;
set;
} public NodePathAttribute(string nodePath)
{
NodePath = nodePath;
} public NodePathAttribute(string nodePath,string defaultValue)
:this(nodePath)
{
DefaultValue = defaultValue;
}
}
2.SystemSetting类用于定义要读取和保存的属性,SystemSetting继续XMLSettingBase
namespace ConsoleApplication2
{
public class SystemSetting : XMLSettingBase
{
#region Property #region HostLocationSetting /// <summary>
/// host wcf service location
/// </summary>
[NodePath("/Settings/HostLocationSetting/HostLocation")]
public string HostLocation { get; set; } /// <summary>
/// host wcf service port
/// </summary>
[NodePath("/Settings/HostLocationSetting/HostPort")]
public int? HostPort { get; set; } #endregion #region SystemFolderSetting /// <summary>
/// NiceLable sdk niceengine5wr.dll path
/// </summary>
[NodePath("/Settings/SystemFolderSetting/NiceEngineFolderPath")]
public string NiceEngineFolderPath
{
get;
set;
} #endregion #region SearchSetting /// <summary>
/// Main program
/// </summary>
[NodePath("/Settings/SearchSetting/MainProgram")]
public string MainProgram
{
get;
set;
} /// <summary>
/// Sub program
/// </summary>
[NodePath("/Settings/SearchSetting/SubProgram")]
public string SubProgram
{
get;
set;
} /// <summary>
/// Get/Set Date Range to auto setting and search condition
/// </summary>
[NodePath("/Settings/SearchSetting/DateRange")]
public int? DateRange
{
get;
set;
} /// <summary>
/// Get/Set Date Range unit 0:days;1:weeks;2:months;3:years
/// </summary>
[NodePath("/Settings/SearchSetting/DateRangeUnit")]
public int? DateRangeUnit
{
get;
set;
} /// <summary>
/// search status
/// </summary>
[NodePath("/Settings/SearchSetting/Status")]
public FileStatus? Status
{
get;
set;
} /// <summary>
/// Skip printed order
/// </summary>
[NodePath("/Settings/SearchSetting/SkipPrintedOrder")]
public bool? SkipPrintedOrder
{
get;
set;
} #endregion #region PrintSetting [NodePath("/Settings/PrintSetting/ReturnQCResult")]
public bool? ReturnQCResult { get; set; } [NodePath("/Settings/PrintSetting/ActualPrintQuantity")]
public bool? ActualPrintQuantity { get; set; } [NodePath("/Settings/PrintSetting/MOSeperator")]
public bool? MOSeperator { get; set; } [NodePath("/Settings/PrintSetting/SKUSeperator")]
public string SKUSeperator { get; set; } #endregion #region LoginSetting [NodePath("/Settings/LoginSetting/UserName")]
public string UserName { get; set; } [NodePath("/Settings/LoginSetting/Password")]
public string Password { get; set; } [NodePath("/Settings/LoginSetting/Language")]
public string Language { get; set; } #endregion #endregion #region Ctor public SystemSetting(string filePath)
:base(filePath)
{ } #endregion
}
}
public class XMLSettingBase
{
#region Field protected string _filePath = null;
protected XmlDocument _xmlDocument = null; public delegate void SettingChange(); #endregion #region Ctor public XMLSettingBase(string filePath)
{
_filePath = filePath;
_xmlDocument = new XmlDocument();
_xmlDocument.Load(filePath);
} #endregion #region Event public event SettingChange OnSettingChangeEvent; #endregion #region Method /// <summary>
/// init system setting
/// </summary>
public void LoadData()
{
PropertyInfo[] propertyInfoes = this.GetType().GetProperties();
if (propertyInfoes == null && propertyInfoes.Length == ) { return; } //load each setting value
foreach (var propertyInfo in propertyInfoes)
{
NodePathAttribute customerAttribute = propertyInfo.GetCustomAttribute<NodePathAttribute>(); if (customerAttribute == null) { continue; } string propertyValue = string.Empty;
if (_xmlDocument.SelectSingleNode(customerAttribute.NodePath) != null)
{
propertyValue = GetXmlNodeValue(customerAttribute.NodePath);
}
else
{
CreateNode(customerAttribute.NodePath); propertyValue = customerAttribute.DefaultValue;
} //whether need to decrypt value
EncryptAttribute encryptAttribute = propertyInfo.GetCustomAttribute<EncryptAttribute>();
if (encryptAttribute == null)
{
SetPropertyInfoValue(propertyInfo, this, propertyValue);
}
else
{
SetPropertyInfoValue(propertyInfo, this, Decrypt(propertyValue, encryptAttribute.EncryptPassword));
} } LoadExtendData();
} public virtual void LoadExtendData()
{
return;
} /// <summary>
/// save data to xml file.
/// </summary>
public void SaveData()
{
PropertyInfo[] propertyInfoes = this.GetType().GetProperties();
if (propertyInfoes == null && propertyInfoes.Length == ) { return; } //load each setting value
foreach (var propertyInfo in propertyInfoes)
{
NodePathAttribute customerAttribute = propertyInfo.GetCustomAttribute<NodePathAttribute>(); if (customerAttribute == null) { continue; } object propertyValue = propertyInfo.GetValue(this); //whether need to decrypt value
EncryptAttribute encryptAttribute = propertyInfo.GetCustomAttribute<EncryptAttribute>();
if (encryptAttribute == null)
{
SetXmlNodeValue(customerAttribute.NodePath, propertyValue != null ? propertyValue.ToString() : string.Empty);
}
else
{
SetXmlNodeValue(customerAttribute.NodePath, propertyValue != null ? Encrypt(propertyValue.ToString(), encryptAttribute.EncryptPassword) : string.Empty);
}
} _xmlDocument.Save(_filePath);
} /// <summary>
/// refresh system setting
/// </summary>
public void Refresh()
{
//save data
SaveData();
//reload the data.
LoadData();
//triggering event
if (OnSettingChangeEvent != null)
{
OnSettingChangeEvent();
}
} public string GetXmlNodeValue(string strNode)
{
try
{
XmlNode xmlNode = _xmlDocument.SelectSingleNode(strNode);
return xmlNode.InnerText;
}
catch (Exception ex)
{
throw ex;
}
} public void SetXmlNodeValue(string strNode, string value)
{
try
{
XmlNode xmlNode = _xmlDocument.SelectSingleNode(strNode);
xmlNode.InnerText = value;
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// convert the datatable to list
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private void SetPropertyInfoValue(PropertyInfo propertyInfo, object obj, object value)
{
//check value
if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
{
return;
} string strValue = value.ToString(); if (propertyInfo.PropertyType.IsEnum)
{
propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType, strValue), null);
}
else
{
string propertyTypeName = propertyInfo.PropertyType.Name;
switch (propertyTypeName)
{
case "Int32":
case "Int64":
case "Int":
int intValue;
int.TryParse(strValue, out intValue);
propertyInfo.SetValue(obj, intValue, null);
break;
case "Long":
long longValue;
long.TryParse(strValue, out longValue);
propertyInfo.SetValue(obj, longValue, null);
break;
case "DateTime":
DateTime dateTime;
DateTime.TryParse(strValue, out dateTime);
propertyInfo.SetValue(obj, dateTime, null);
break;
case "Boolean":
Boolean bv = false;
if ("".Equals(value) || "true".Equals(strValue.ToLower()))
{
bv = true;
}
propertyInfo.SetValue(obj, bv, null);
break;
case "Nullable`1":
if (propertyInfo.PropertyType.GenericTypeArguments[].IsEnum)
{
propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType.GenericTypeArguments[], strValue), null);
}
else
{
switch (propertyInfo.PropertyType.GenericTypeArguments[].FullName)
{
case "System.Int32":
case "System.Int64":
case "System.Int":
int intV;
int.TryParse(strValue, out intV);
propertyInfo.SetValue(obj, intV, null);
break;
case "System.DateTime":
DateTime dtime;
DateTime.TryParse(strValue, out dtime);
propertyInfo.SetValue(obj, dtime, null);
break;
case "System.Boolean":
Boolean boolv = false;
if ("".Equals(value) || "true".Equals(strValue.ToLower()))
{
boolv = true;
}
propertyInfo.SetValue(obj, boolv, null);
break;
default:
propertyInfo.SetValue(obj, strValue, null);
break;
}
}
break;
default:
propertyInfo.SetValue(obj, strValue, null);
break;
} }
} /// <summary>
/// Decrypt text
/// </summary>
/// <param name="value"></param>
/// <param name="password"></param>
/// <returns></returns>
private string Decrypt(string value, string password)
{
Encryption encryption = new Encryption();
string outMsg = null;
//Decrypt
if (!string.IsNullOrEmpty(value))
{
encryption.DesDecrypt(value, password, out outMsg);
} return outMsg; } /// <summary>
/// Enctypr text
/// </summary>
/// <param name="value"></param>
/// <param name="password"></param>
/// <returns></returns>
private string Encrypt(string value, string password)
{
Encryption encryption = new Encryption();
string outMsg = null; if (encryption.DesEncrypt(value, password, out outMsg))
{
return outMsg;
}
else
{
return string.Empty;
} } public void CreateNode(string strNode)
{
string[] nodes = strNode.Split(new[] { @"/" }, StringSplitOptions.RemoveEmptyEntries); var tempNode = new StringBuilder();
for (int i = ; i < nodes.Length; i++)
{
string parentNodePath = tempNode.ToString(); tempNode.Append(@"/"); tempNode.Append(nodes[i]); //此节点不存在,则创建此结点
if (_xmlDocument.SelectSingleNode(tempNode.ToString()) == null)
{
XmlNode newNode = _xmlDocument.CreateElement(nodes[i]); //寻找父结点
XmlNode parentNode = _xmlDocument.SelectSingleNode(parentNodePath); if (parentNode != null)
{
parentNode.AppendChild(newNode);
}
}
} _xmlDocument.Save(_filePath);
} #endregion }
3.测试用类
这是需要操作的文件
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<HostLocationSetting>
<HostLocation></HostLocation>
<HostPort></HostPort>
</HostLocationSetting>
<SystemFolderSetting>
<NiceEngineFolderPath></NiceEngineFolderPath>
</SystemFolderSetting>
<SearchSetting>
<MainProgram></MainProgram>
<SubProgram></SubProgram>
<Status></Status>
<SkipPrintedOrder>true</SkipPrintedOrder>
<DateRange></DateRange>
<DateRangeUnit></DateRangeUnit>
</SearchSetting>
<PrintSetting>
<ReturnQCResult>false</ReturnQCResult>
<ActualPrintQuantity></ActualPrintQuantity>
<MOSeperator>true</MOSeperator>
<SKUSeperator></SKUSeperator>
</PrintSetting>
<LoginSetting>
<UserName></UserName>
<Password></Password>
<Language></Language>
</LoginSetting> </Settings> 测试代码如下
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
SystemSetting systemSetting = new SystemSetting(@"Config/SystemSetting.xml"); systemSetting.LoadData(); Console.WriteLine(systemSetting.HostLocation);
Console.WriteLine(systemSetting.Status);
Console.WriteLine(systemSetting.SkipPrintedOrder); systemSetting.HostLocation = "192.168.15.171";
systemSetting.Status = FileStatus.PARTIAL_PRINTED;
systemSetting.SkipPrintedOrder = true; systemSetting.Refresh(); systemSetting.LoadData(); Console.WriteLine(systemSetting.HostLocation);
Console.WriteLine(systemSetting.Status);
Console.WriteLine(systemSetting.SkipPrintedOrder); Console.ReadKey(); }
}
}
项目常用解决方案之SystemSetting.xml文件的修改与读取的更多相关文章
- .net操作xml文件(新增.修改,删除,读取) 转
今天有个需求需要操作xml节点.突然见遗忘了许多.上网看了些资料.才整出来.脑袋真不够用.在这里把我找到的资料共享一下.方便以后使用.本文属于网摘/ 1 一.简单介绍2 using System.Xm ...
- .net操作xml文件(新增.修改,删除,读取)---datagridview与xml文件
参考网址: http://www.cnblogs.com/liguanghui/archive/2011/11/10/2244199.html 很详细的,相信能给你一定的帮助.
- 安装时后的idea,项目不能运行,pom.xml文件不能下载到本地仓库,maven配置是正确的
安装时后的idea,项目不能运行,pom.xml文件不能下载到本地仓库,maven配置是正确的 项目上传到svn后,同事下载项目后,没有识别出来mavn中的pom.xml文件,导致idea不能自动下载 ...
- 解析xml文件,修改Jenkins的配置
最近因为服务器移动,在Jenkins中配置的一些地址之类的,都要改变,如图,我因为使用插件Sidebar Links增加一个链接地址,现在地址变了,所以在Jenkins中配置就需要改动link url ...
- Eclipse使用之将Git项目转为Maven项目, ( 注意: 最后没有pom.xml文件的, 要转化下 )
Eclipse使用之将Git项目转为Maven项目(全图解) 2017年08月11日 09:24:31 阅读数:427 1.打开Eclipse,File->Import 2.Git->Pr ...
- 【java项目实战】dom4j解析xml文件,连接Oracle数据库
简单介绍 dom4j是由dom4j.org出品的一个开源XML解析包.这句话太官方.我们还是看一下官方给出的解释.例如以下图: dom4j是一个易于使用的.开源的,用于解析XML,XPath和XSLT ...
- 创建maven web项目时,没有web.xml文件
1.问题:创建maven项目时,选择的是创建web-app项目,但是结果配置之后,却没有web.xml文件. 2.解决办法: ------------------------------------- ...
- Eclipse建立Web项目,手动生成web.xml文件
相关文章:https://blog.csdn.net/ys_code/article/details/79156188(Web项目建立,手动生成web.xml文件
- SpringBoot项目编译后没有xxxmapper.xml文件解决方法
在pom.xml文件中添加如下代码 <build> <plugins> <plugin> <groupId>org.springframework.bo ...
随机推荐
- Mybaties保存后自动获取主键ID
<!-- 插入记录 --> <insert id="saveTvTypeBatch" useGeneratedKeys="true" keyP ...
- mac 开启mysql日志
step1: 进入终端进入mysql: step2 : 开启mysql日志 step3 : 查看mysql的日志文件所在位置 step4 : 在终端中用tail -f 命令打开该日志文件:
- JavaScript实现快速排序(Quicksort)
目前,最常见的排序算法大概有七八种,其中"快速排序"(Quicksort)使用得最广泛,速度也较快.它是图灵奖得主 东尼·霍尔(C. A. R. Hoare)于1960时提出来的. ...
- 【Nowcoder 上海五校赛】二数(模拟)
题目描述: 我们把十进制下每一位都是偶数的数字叫做“二数”. 小埃表示自己很聪明,最近他不仅能够从小数到大:2,3,4,5....,也学会了从大数到小:100,99,98...,他想知道从一个数开始数 ...
- poj_1091_跳蚤
Z城市居住着很多只跳蚤.在Z城市周六生活频道有一个娱乐节目.一只跳蚤将被请上一个高空钢丝的正中央.钢丝很长,可以看作是无限长.节目主持人会给该跳蚤发一张卡片.卡片上写有N+1个自然数.其中最后一个是M ...
- ansible服务的部署与使用
简介: ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet.cfengine.chef.func.fabric)的优点,实现了批量系统配置.批量程序 ...
- 通过Ambari2.2.2部署HDP大数据服务
node1 amari-server node2 amari-agent namenode1,datanode,resourcemanager,zk node3 amari-agent namen ...
- javaScript 字符串与unicode码之间的相互转换,函数的封装
在我们的开发过程中,有时在对数据进行储存的时候,我们需要将字符串转成unicode. 比如,在jsp开发时,前端使用页面间传值时,将传值参数先存入cookie中,然后在使用的时候,再从ookie中取出 ...
- SQL优化之语句优化
昨天与大家分享了SQL优化中的索引优化,今天给大家聊一下,在开发过程中高质量的代码也是会带来优化的 网上关于SQL优化的教程很多,但是比较杂乱.整理了一下,写出来跟大家分享一下,其中有错误和不足的地方 ...
- tp5多条件查询
->where('m.user_nickname|w.nickname|c.companyname','like','%'.$search.'%')\