浪漫的周末從cnblogs開始。話說,今天和往常的周末一樣,韓君躲在被窩裡用手機翻閱著園子裡的珠玑。一篇《應用XML作為數據庫的快速開發框架》的文章在韓君腦子裡激起了一波球形閃電。想想上周中剛好完成的一個WinCE小項目,這波久久不能平息。韓君做了一個比馬兄更艱難的決定,秒速穿戴衣褲後,開始了那第N次的親密接觸...
一個外傳版的XML數據源快速開發框架:XmlFramwork。
PathRoute:路由XML數據文件路徑;
List<T>:XML實體類的泛型集合,對應XML文檔;
ListExtend:為List<T>擴展將實體類集合序列化為XML文檔及將XML文檔反序列化為實體類集合的方法;
XmlEntity:XML實體類的基類,定義了一個Guid類型的屬性(ID);
XmlEntityProcess:對Xml文檔進行增、刪、改、查等處理。
PathRoute.cs
/*
類: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