项目常用解决方案之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 ...
随机推荐
- 【TOJ 3305】Hero In Maze II
描述 500年前,Jesse是我国最卓越的剑客.他英俊潇洒,而且机智过人^_^.突然有一天,Jesse心爱的公主被魔王困在了一个巨大的迷宫中.Jesse听说这个消息已经是两天以后了,他急忙赶到迷宫,开 ...
- oracle约束约束状态和设计习惯
oracle约束状态有几个项目,会让人迷惑,分别是: enable/disable--是否启用/禁用 validate/invalidate--确认/不确认 deferrable/not deferr ...
- docker搭建基于percona-xtradb-cluster方案的mysql集群
一.部署环境 序号 hostname ip 备注 1 manager107 10.0.3.107 centos7;3.10.0-957.1.3.el7.x86_64 2 worker68 10.0.3 ...
- C#下载局域网共享文件夹中的文件
在公司的局域网内部,有个主机,共享了几个文件夹给下面的客户机使用. 想要利用这个文件夹上传最新的winform程序版本,每次运行exe的时候检测局域网的软件版本达到更新exe的目的. 这里有个例子,是 ...
- css实现下拉菜单功能(多中实现方式即原理)
引导思路: 1.需要用到的元素:position hover (z-index) 或(overflow)或(display)等等. 关键点就是div的溢出部分的处理. 2.实现过程: 2.1:就是要 ...
- c#学习笔记《1》——regex类
C#regex是正则表达式类用于string的处理,查找匹配的字符串.1,先看一个例子Regex regex=new Regex(@”OK“)://我们要在目标字符串中找到"OK" ...
- JS 定时器,定时调用PHP
$(function() { var voiceplay=function(){ var site = location.href.split('_cms')[0] + '_cms/'; $.ajax ...
- python构造二维列表以及排序字典
1. 构造二维列表: 比如我现在需要一个100*100的二维列表: a = [] for i in range(100): a.append([]) for j in range(100): a[i] ...
- 学习photoshop心得
简要的学习了ps的三大功能p图,抠图,作图, p图主要是学了换脸这一效果,用到套索工具,把范冰冰的脸接到郭德纲身上, 首先使用套索工具把脸圈起来 然后移动到 另一个人脸上 再然后混合图层,自动混合 差 ...
- python学习——函数
一.在python的世界里什么是函数: 答:函数通常是用来实现某一个功能二被封装成的一个对象,是用来实现代码复用的常用方式 现在有一个需求,假如你在不知道len()方法的情况下,要你计算字符串‘he ...