浪漫的周末从cnblogs开始。话说,今天和往常的周末一样,韩君躲在被窝里用手机翻阅着园子里的珠玑。一篇《应用XML作为数据库的快速开发框架》的文章在韩君脑子里激起了一波球形闪电。想想上周中刚好完成的一个WinCE小项目,这波久久不能平息。韩君做了一个比马兄更艰难的决定,秒速穿戴衣裤后,开始了那第N次的亲密接触...
一个外传版的XML数据源快速开发框架:XmlFramwork。
PathRoute:路由XML数据文件路径;
ListExtend:为List<T>扩展将实体类集合序列化为XML文档及将XML文档反序列化为实体类集合的方法;
XmlEntity:XML实体类的基类,定义了一个Guid类型的属性(ID);
XmlEntityProcess:对Xml文档进行增、删、改、查等处理。
PathRoute.cs
monospace; width: 100%; border-bottom-style: none; color: black; padding-bottom: 0px; direction: ltr; text-align: left; padding-top: 0px; border-right-style: none; padding-left: 0px; margin: 0em; border-left-style: none; line-height: 12pt; padding-right: 0px; background-color: white">/*
类:PathRoute
描述:路由XML数据文件路径
编 码 人:韩兆新 日期:2014年12月21日
修改记录:
*/
using System.Configuration;
using System.IO;
using System.Reflection;
namespace XmlFramwork
{
static class PathRoute
{
public static readonly string DataFolder = ConfigurationManager.AppSettings["DataFolder"];
public static string GetXmlPath<T>()
{
string dataFolder = DataFolder;
if (string.IsNullOrEmpty(dataFolder))
{
dataFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Data");
}
return Path.ChangeExtension(Path.Combine(dataFolder, Path.Combine(typeof(T).FullName.Split('.'))), ".xml");
}
}
}
ListExtend.cs
/*
类:ListExtend
描述:为List<T>扩展加载XML文档和保存为XML文档的方法
编 码 人:韩兆新 日期:2014年12月21日
修改记录:
*/
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace XmlFramwork
{
public static class ListExtend
{
/// <summary>
/// 加载XML文档返回List集合
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static List<TSource> Load<TSource>(this List<TSource> source)
{
string fileName = PathRoute.GetXmlPath<TSource>();
if (File.Exists(fileName))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<TSource>));
using (Stream reader = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
return xmlSerializer.Deserialize(reader) as List<TSource>;
}
}
else
{
return new List<TSource>();
}
}
/// <summary>
/// 将list集合保存为XML文档
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
public static void Save<TSource>(this List<TSource> source)
{
string fileName = PathRoute.GetXmlPath<TSource>();
FileInfo fileInfo = new FileInfo(fileName);
DirectoryInfo directoryInfo = fileInfo.Directory;
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
XmlSerializer xmlSerializer = new XmlSerializer(source.GetType());
using (Stream writer = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
xmlSerializer.Serialize(writer, source);
}
}
}
}
XmlEntity.cs
/*
类:XmlEntity
描述:Xml实体类基类
编 码 人:韩兆新 日期:2014年12月21日
修改记录:
*/
using System;
namespace XmlFramwork
{
public class XmlEntity
{
public Guid ID{ set; get;}
}
}XmlEntityProcess.cs
/*
类:XmlEntityProcess〈T〉
描述:对Xml文档进行增、删、改、查等处理
编 码 人:韩兆新 日期:2014年12月21日
修改记录:
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace XmlFramwork
{
public static class XmlEntityProcess<T> where T : XmlEntity
{
private static string lastErrMsg;
/// <summary>
/// 获取最后一次错误的信息
/// </summary>
/// <returns></returns>
public static string GetLastErrMsg()
{
return lastErrMsg;
}
/// <summary>
/// 插入XML实体类对象
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public static bool Insert(T entity)
{
try
{
List<T> entityList = new List<T>().Load();
entity.ID = Guid.NewGuid();
entityList.Add(entity);
entityList.Save();
return true;
}
catch (Exception ex)
{
lastErrMsg = ex.Message;
return false;
}
}
/// <summary>
/// 根据ID删除XML实体类对象
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static bool DeleteById(Guid id)
{
try
{
List<T> entityList = new List<T>().Load();
entityList = entityList.Where(entity => entity.ID != id).ToList();
entityList.Save();
return true;
}
catch (Exception ex)
{
lastErrMsg = ex.Message;
return false;
}
}
/// <summary>
/// 更新XML实体类对象
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public static bool Update(T entity)
{
try
{
List<T> entityList = new List<T>().Load();
entityList = entityList.Where(e => e.ID != entity.ID).ToList();
entityList.Add(entity);
entityList.Save();
return true;
}
catch (Exception ex)
{
lastErrMsg = ex.Message;
return false;
}
}
/// <summary>
/// 获取所有的指定类型的XML实体类对象
/// </summary>
/// <returns></returns>
public static List<T> GetAll()
{
try
{
List<T> entityList = new List<T>().Load();
return entityList;
}
catch (Exception ex)
{
lastErrMsg = ex.Message;
return null;
}
}
/// <summary>
/// 根据ID获取指定类型的XML实体类对象
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static T GetById(Guid id)
{
try
{
List<T> entityList = new List<T>().Load();
entityList = entityList.Where(e => e.ID == id).ToList();
if (null == entityList || entityList.Count <= 0)
{
return default(T);
}
else
{
return entityList[0];
}
}
catch (Exception ex)
{
lastErrMsg = ex.Message;
return null;
}
}
}
}
界面:
DemoForm.cs
/*
类:DemoForm
描述:XmlFramwork增、删、改、查演示
编 码 人:韩兆新 日期:2014年12月21日
修改记录:
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using XmlFramwork;
using XmlFramworkDemo.Entity;
using XmlFramworkDemo.Urility;
namespace XmlFramworkDemo
{
public partial class DemoForm : Form
{
public DemoForm()
{
InitializeComponent();
}
/// <summary>
/// DemoForm窗口——加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DemoForm_Load(object sender, EventArgs e)
{
BindGvUserInfo();
}
/// <summary>
/// 添加、修改按钮——单击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOperation_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtName.Text))
{
MessageBox.Show("请输入姓名!");
return;
}
if (string.IsNullOrEmpty(txtAge.Text))
{
MessageBox.Show("请输入年龄!");
return;
}
else if(!ValidateHelper.IsValidUintFormat(txtAge.Text.Trim()))
{
MessageBox.Show("年龄不是合法的格式!");
return;
}
if (btnOperation.Text.Equals("添加"))
{
UserInfo userInfo = new UserInfo();
userInfo.Age = uint.Parse(txtAge.Text.Trim());
userInfo.Name = txtName.Text;
if (!XmlEntityProcess<UserInfo>.Insert(userInfo))
{
MessageBox.Show("插入失败:" + XmlEntityProcess<UserInfo>.GetLastErrMsg());
}
}
else
{
UserInfo userInfo = btnOperation.Tag as UserInfo;
userInfo.Name = txtName.Text;
userInfo.Age = uint.Parse(txtAge.Text.Trim());
if (!XmlEntityProcess<UserInfo>.Update(userInfo))
{
MessageBox.Show("更新失败:" + XmlEntityProcess<UserInfo>.GetLastErrMsg());
}
}
btnOperation.Text = "添加";
BindGvUserInfo();
}
/// <summary>
/// 编辑菜单——单击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 编辑ToolStripMenuItem_Click(object sender, EventArgs e)
{
Guid id =Guid.Parse(gvUserInfo.SelectedRows[0].Cells["ID"].Value.ToString());
UserInfo userInfo = XmlEntityProcess<UserInfo>.GetById(id);
txtName.Text = userInfo.Name;
txtAge.Text = userInfo.Age.ToString();
btnOperation.Tag = userInfo;
btnOperation.Text = "修改";
}
/// <summary>
/// 删除菜单——单击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
{
Guid id = Guid.Parse(gvUserInfo.SelectedRows[0].Cells["ID"].Value.ToString());
XmlEntityProcess<UserInfo>.DeleteById(id);
BindGvUserInfo();
}
/// <summary>
/// 查询按钮——单击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 查询ToolStripMenuItem_Click(object sender, EventArgs e)
{
Guid id =Guid.Parse(gvUserInfo.SelectedRows[0].Cells["ID"].Value.ToString());
UserInfo userInfo = XmlEntityProcess<UserInfo>.GetById(id);
txtName.Text = userInfo.Name;
txtAge.Text = userInfo.Age.ToString();
}
/// <summary>
/// 右键菜单
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void gvUserInfo_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
{
return;
}
if (e.Button == MouseButtons.Right)
{
if (e.RowIndex >= 0)
{
//若行已是选中状态就不再进行设置
if (gvUserInfo.Rows[e.RowIndex].Selected == false)
{
gvUserInfo.ClearSelection();
gvUserInfo.Rows[e.RowIndex].Selected = true;
}
//只选中一行时设置活动单元格
if (gvUserInfo.SelectedRows.Count == 1)
{
gvUserInfo.CurrentCell = gvUserInfo.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
//弹出操作菜单
contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
}
}
}
/// <summary>
/// 绑定GvUserInfo
/// </summary>
private void BindGvUserInfo()
{
List<UserInfo> userInfoList = XmlEntityProcess<UserInfo>.GetAll();
if (null != userInfoList)
{
gvUserInfo.DataSource = userInfoList;
}
else
{
MessageBox.Show("获取数据失败:" + XmlEntityProcess<UserInfo>.GetLastErrMsg());
}
}
}
}
UserInfo.cs
/*
类:UserInfo
描述:XML实体类UserInfo
编 码 人:韩兆新 日期:2014年12月21日
修改记录:
*/
using XmlFramwork;
namespace XmlFramworkDemo.Entity
{
public class UserInfo:XmlEntity
{
public string Name { set; get; }
public uint Age { set; get; }
}
}
ValidateHelper.cs
/*
类:ValidateHelper
描述:用于字符串格式验证
编 码 人:韩兆新 日期:2014年12月21日
修改记录:
*/
using System;
namespace XmlFramworkDemo.Urility
{
public static class ValidateHelper
{
public static bool IsValidUintFormat(string strIn)
{
uint temp;
return UInt32.TryParse(strIn,out temp);
}
}
}
App.config
XmlFramwork源码及演示.zip