Asp.net 序列化应用实例(转载)
原文作者:寻梦E.net
原文地址:http://www.cnblogs.com/lsmsky/archive/2008/01/15/1040190.html
原文地址:http://www.cnblogs.com/lsmsky/archive/2008/01/15/1040190.html
这是本人这几天学习序列化的几个例子,源代码下载:https://files.cnblogs.com/lsmsky/serializetest.rar
实体类User
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Specialized;
using System.Collections;
namespace test
{
/// <summary>
/// 用户类
/// User 的摘要说明。
/// </summary>
public class User
{
//数据表有的字段
private int userID ;
private string username;
private string password;
private string nickname;
private string email;
private NameValueCollection extendedAttributes = new NameValueCollection();
public int UserID
{
get{return this.userID;}
set{this.userID = value;}
}
public string UserName
{
get{return this.username;}
set{this.username = value;}
}
public string Password
{
get{return this.password;}
set{this.password = value;}
}
public string Nickname
{
get{return this.nickname;}
set{this.nickname = value;}
}
public string Email
{
get{return this.email;}
set{this.email = value;}
}
/// <summary>
/// 以下三个字段为数据表没有的字段
/// </summary>
public String QQ
{
get { return GetExtendedAttribute("qq"); }
set { SetExtendedAttribute("qq", value); }
}
public String Homepage
{
get { return GetExtendedAttribute("homepage"); }
set { SetExtendedAttribute("homepage", value); }
}
public String Phone
{
get { return GetExtendedAttribute("phone"); }
set { SetExtendedAttribute("phone", value); }
}
public string GetExtendedAttribute(string name)
{
string returnValue = extendedAttributes[name];
if (returnValue == null)
return string.Empty;
else
return returnValue;
}
public void SetExtendedAttribute(string name, string value)
{
extendedAttributes[name] = value;
}
//序列化extendedAttributes集合
public byte[] SerializeExtendedAttributes()
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
byte[] b;
binaryFormatter.Serialize(ms, extendedAttributes);
ms.Position = 0;
b = new Byte[ms.Length];
ms.Read(b, 0, b.Length);
ms.Close();
return b;
}
//反序列化extendedAttributes集合
public void DeserializeExtendedAttributes(byte[] serializedExtendedAttributes)
{
if (serializedExtendedAttributes.Length == 0)
return;
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
ms.Write(serializedExtendedAttributes, 0, serializedExtendedAttributes.Length);
ms.Position = 0;
extendedAttributes = (NameValueCollection) binaryFormatter.Deserialize(ms);
ms.Close();
}
catch
{
}
}
}
}
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Specialized;
using System.Collections;
namespace test
{
/// <summary>
/// 用户类
/// User 的摘要说明。
/// </summary>
public class User
{
//数据表有的字段
private int userID ;
private string username;
private string password;
private string nickname;
private string email;
private NameValueCollection extendedAttributes = new NameValueCollection();
public int UserID
{
get{return this.userID;}
set{this.userID = value;}
}
public string UserName
{
get{return this.username;}
set{this.username = value;}
}
public string Password
{
get{return this.password;}
set{this.password = value;}
}
public string Nickname
{
get{return this.nickname;}
set{this.nickname = value;}
}
public string Email
{
get{return this.email;}
set{this.email = value;}
}
/// <summary>
/// 以下三个字段为数据表没有的字段
/// </summary>
public String QQ
{
get { return GetExtendedAttribute("qq"); }
set { SetExtendedAttribute("qq", value); }
}
public String Homepage
{
get { return GetExtendedAttribute("homepage"); }
set { SetExtendedAttribute("homepage", value); }
}
public String Phone
{
get { return GetExtendedAttribute("phone"); }
set { SetExtendedAttribute("phone", value); }
}
public string GetExtendedAttribute(string name)
{
string returnValue = extendedAttributes[name];
if (returnValue == null)
return string.Empty;
else
return returnValue;
}
public void SetExtendedAttribute(string name, string value)
{
extendedAttributes[name] = value;
}
//序列化extendedAttributes集合
public byte[] SerializeExtendedAttributes()
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
byte[] b;
binaryFormatter.Serialize(ms, extendedAttributes);
ms.Position = 0;
b = new Byte[ms.Length];
ms.Read(b, 0, b.Length);
ms.Close();
return b;
}
//反序列化extendedAttributes集合
public void DeserializeExtendedAttributes(byte[] serializedExtendedAttributes)
{
if (serializedExtendedAttributes.Length == 0)
return;
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
ms.Write(serializedExtendedAttributes, 0, serializedExtendedAttributes.Length);
ms.Position = 0;
extendedAttributes = (NameValueCollection) binaryFormatter.Deserialize(ms);
ms.Close();
}
catch
{
}
}
}
}
前端代码:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using EmanUtils;
using System.Data.SqlClient;
namespace test
{
/// <summary>
/// Serialize1 的摘要说明。
/// </summary>
public class Serialize1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox txtUserName;
protected System.Web.UI.WebControls.TextBox txtPws;
protected System.Web.UI.WebControls.TextBox txtQQ;
protected System.Web.UI.WebControls.TextBox txtHomepage;
protected System.Web.UI.WebControls.Label lbMsg;
protected System.Web.UI.WebControls.TextBox txtNick;
protected System.Web.UI.WebControls.TextBox txtEmail;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected System.Web.UI.WebControls.Panel Panel1;
protected System.Web.UI.WebControls.TextBox txtTel;
protected System.Web.UI.HtmlControls.HtmlInputHidden hiduserid;
protected System.Web.UI.WebControls.Button btnAction;
private void Page_Load(object sender, System.EventArgs e)
{
if(! this.IsPostBack)
BindData();
}
Web 窗体设计器生成的代码
private void BindData()
{
DataGrid1.DataSource = GetUserList();
DataGrid1.DataBind();
}
private void btnAction_Click(object sender, System.EventArgs e)
{
User _user = new User();
_user.UserName = txtUserName.Text;
_user.Password = txtPws.Text;
_user.Nickname = txtNick.Text;
_user.Email = txtEmail.Text;
_user.QQ = txtQQ.Text;
_user.Homepage = txtHomepage.Text;
_user.Phone = txtTel.Text;
if(btnAction.Text =="新增")
{
AddUser(_user);
lbMsg.Text = "新增成功";
}
if(btnAction.Text =="修改")
{
int userID = 0;
string hidUserID = hiduserid.Value;
if(hidUserID != string.Empty || hidUserID != null )
{
userID = Convert.ToInt32(hiduserid.Value);
_user.UserID = userID ;
UpdateUser(_user);
lbMsg.Text = "修改成功";
}
else
{
lbMsg.Text = "参数userID为空";
}
}
BindData();
}
private void BindUserInfo(User user)
{
txtUserName.Text = user.UserName;
txtPws.Text = user.Password;
txtNick.Text = user.Nickname;
txtEmail.Text = user.Email;
txtQQ.Text = user.QQ;
txtHomepage.Text = user.Homepage;
txtTel.Text = user.Phone;
hiduserid.Value = user.UserID.ToString();
}
private void ClearBind()
{
txtUserName.Text = "";
txtPws.Text = "";
txtNick.Text = "";
txtEmail.Text = "";
txtQQ.Text = "";
txtHomepage.Text = "";
txtTel.Text = "";
}
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if(e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
int id = Convert.ToInt32(DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
if(e.CommandName == "Update")
{
User user = GetUserInfo(id);
BindUserInfo(user);
btnAction.Text = "修改";
}
if(e.CommandName == "Add")
{
ClearBind();
btnAction.Text = "新增";
}
}
}
//新增用户
private void AddUser(User user)
{
string sql = "Insert into UserInfo([UserPws],[UserName],[Nickname],[Email],[ExtendInfo]) Values";
sql += "(@Password,@UserName,@Nickname,@Email,@ExtendInfo)";
SqlParameter[] prams =
{
Database.MakeInParam("@UserName",SqlDbType.NVarChar,50,user.UserName),
Database.MakeInParam("@Password",SqlDbType.NVarChar,50,user.Password),
Database.MakeInParam("@Nickname",SqlDbType.NVarChar,50,user.Nickname),
Database.MakeInParam("@Email",SqlDbType.NVarChar,50,user.Email),
Database.MakeInParam("@ExtendInfo",SqlDbType.VarBinary,7000,user.SerializeExtendedAttributes())
};
Database.ExecuteNonQuery(CommandType.Text,sql,prams);
}
//更新用户
private void UpdateUser(User user)
{
string sql = "UPDATE UserInfo SET UserPws = @Password,UserName =@UserName,Nickname =@Nickname,Email =@Email,";
sql += "ExtendInfo =@ExtendInfo WHERE UserID = @UserID";
SqlParameter[] prams = {
Database.MakeInParam("@UserID",SqlDbType.Int,4,user.UserID),
Database.MakeInParam("@UserName",SqlDbType.NVarChar,50,user.UserName),
Database.MakeInParam("@Password",SqlDbType.NVarChar,50,user.Password),
Database.MakeInParam("@Nickname",SqlDbType.NVarChar,50,user.Nickname),
Database.MakeInParam("@Email",SqlDbType.NVarChar,50,user.Email),
Database.MakeInParam("@ExtendInfo",SqlDbType.VarBinary,7000,user.SerializeExtendedAttributes())
};
Database.ExecuteNonQuery(CommandType.Text,sql,prams);
}
private User GetUserInfo(int userid)
{
string sql = "select * from UserInfo where UserID=@UserID";
SqlParameter[] prams = {
Database.MakeInParam("@UserID",SqlDbType.Int,4,userid)
};
SqlDataReader dr = Database.ExecuteReader(CommandType.Text,sql,prams);
User user = new User();
if(dr.Read())
{
user.UserID = Convert.ToInt32(dr["UserID"]);
user.UserName = Convert.ToString(dr["UserName"]);
user.Password = Convert.ToString(dr["UserPws"]);
user.Nickname = Convert.ToString(dr["Nickname"]);
user.Email = Convert.ToString(dr["Email"]);
user.DeserializeExtendedAttributes((byte[])dr["ExtendInfo"]);
}
return user;
}
private ArrayList GetUserList()
{
ArrayList userslist = new ArrayList();
string sql = "select * from UserInfo";
SqlDataReader dr = Database.ExecuteReader(CommandType.Text,sql);
while( dr.Read())
userslist.Add(UserDataReader(dr));
return userslist;
}
public static User UserDataReader(IDataReader dr)
{
User user = new User();
user.UserID = Convert.ToInt32(dr["UserID"]);
user.UserName = Convert.ToString(dr["UserName"]);
user.Password = Convert.ToString(dr["UserPws"]);
user.Nickname = Convert.ToString(dr["Nickname"]);
user.Email = Convert.ToString(dr["Email"]);
user.DeserializeExtendedAttributes((byte[])dr["ExtendInfo"]);
return user;
}
}
}
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using EmanUtils;
using System.Data.SqlClient;
namespace test
{
/// <summary>
/// Serialize1 的摘要说明。
/// </summary>
public class Serialize1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox txtUserName;
protected System.Web.UI.WebControls.TextBox txtPws;
protected System.Web.UI.WebControls.TextBox txtQQ;
protected System.Web.UI.WebControls.TextBox txtHomepage;
protected System.Web.UI.WebControls.Label lbMsg;
protected System.Web.UI.WebControls.TextBox txtNick;
protected System.Web.UI.WebControls.TextBox txtEmail;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected System.Web.UI.WebControls.Panel Panel1;
protected System.Web.UI.WebControls.TextBox txtTel;
protected System.Web.UI.HtmlControls.HtmlInputHidden hiduserid;
protected System.Web.UI.WebControls.Button btnAction;
private void Page_Load(object sender, System.EventArgs e)
{
if(! this.IsPostBack)
BindData();
}
Web 窗体设计器生成的代码
private void BindData()
{
DataGrid1.DataSource = GetUserList();
DataGrid1.DataBind();
}
private void btnAction_Click(object sender, System.EventArgs e)
{
User _user = new User();
_user.UserName = txtUserName.Text;
_user.Password = txtPws.Text;
_user.Nickname = txtNick.Text;
_user.Email = txtEmail.Text;
_user.QQ = txtQQ.Text;
_user.Homepage = txtHomepage.Text;
_user.Phone = txtTel.Text;
if(btnAction.Text =="新增")
{
AddUser(_user);
lbMsg.Text = "新增成功";
}
if(btnAction.Text =="修改")
{
int userID = 0;
string hidUserID = hiduserid.Value;
if(hidUserID != string.Empty || hidUserID != null )
{
userID = Convert.ToInt32(hiduserid.Value);
_user.UserID = userID ;
UpdateUser(_user);
lbMsg.Text = "修改成功";
}
else
{
lbMsg.Text = "参数userID为空";
}
}
BindData();
}
private void BindUserInfo(User user)
{
txtUserName.Text = user.UserName;
txtPws.Text = user.Password;
txtNick.Text = user.Nickname;
txtEmail.Text = user.Email;
txtQQ.Text = user.QQ;
txtHomepage.Text = user.Homepage;
txtTel.Text = user.Phone;
hiduserid.Value = user.UserID.ToString();
}
private void ClearBind()
{
txtUserName.Text = "";
txtPws.Text = "";
txtNick.Text = "";
txtEmail.Text = "";
txtQQ.Text = "";
txtHomepage.Text = "";
txtTel.Text = "";
}
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if(e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
int id = Convert.ToInt32(DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
if(e.CommandName == "Update")
{
User user = GetUserInfo(id);
BindUserInfo(user);
btnAction.Text = "修改";
}
if(e.CommandName == "Add")
{
ClearBind();
btnAction.Text = "新增";
}
}
}
//新增用户
private void AddUser(User user)
{
string sql = "Insert into UserInfo([UserPws],[UserName],[Nickname],[Email],[ExtendInfo]) Values";
sql += "(@Password,@UserName,@Nickname,@Email,@ExtendInfo)";
SqlParameter[] prams =
{
Database.MakeInParam("@UserName",SqlDbType.NVarChar,50,user.UserName),
Database.MakeInParam("@Password",SqlDbType.NVarChar,50,user.Password),
Database.MakeInParam("@Nickname",SqlDbType.NVarChar,50,user.Nickname),
Database.MakeInParam("@Email",SqlDbType.NVarChar,50,user.Email),
Database.MakeInParam("@ExtendInfo",SqlDbType.VarBinary,7000,user.SerializeExtendedAttributes())
};
Database.ExecuteNonQuery(CommandType.Text,sql,prams);
}
//更新用户
private void UpdateUser(User user)
{
string sql = "UPDATE UserInfo SET UserPws = @Password,UserName =@UserName,Nickname =@Nickname,Email =@Email,";
sql += "ExtendInfo =@ExtendInfo WHERE UserID = @UserID";
SqlParameter[] prams = {
Database.MakeInParam("@UserID",SqlDbType.Int,4,user.UserID),
Database.MakeInParam("@UserName",SqlDbType.NVarChar,50,user.UserName),
Database.MakeInParam("@Password",SqlDbType.NVarChar,50,user.Password),
Database.MakeInParam("@Nickname",SqlDbType.NVarChar,50,user.Nickname),
Database.MakeInParam("@Email",SqlDbType.NVarChar,50,user.Email),
Database.MakeInParam("@ExtendInfo",SqlDbType.VarBinary,7000,user.SerializeExtendedAttributes())
};
Database.ExecuteNonQuery(CommandType.Text,sql,prams);
}
private User GetUserInfo(int userid)
{
string sql = "select * from UserInfo where UserID=@UserID";
SqlParameter[] prams = {
Database.MakeInParam("@UserID",SqlDbType.Int,4,userid)
};
SqlDataReader dr = Database.ExecuteReader(CommandType.Text,sql,prams);
User user = new User();
if(dr.Read())
{
user.UserID = Convert.ToInt32(dr["UserID"]);
user.UserName = Convert.ToString(dr["UserName"]);
user.Password = Convert.ToString(dr["UserPws"]);
user.Nickname = Convert.ToString(dr["Nickname"]);
user.Email = Convert.ToString(dr["Email"]);
user.DeserializeExtendedAttributes((byte[])dr["ExtendInfo"]);
}
return user;
}
private ArrayList GetUserList()
{
ArrayList userslist = new ArrayList();
string sql = "select * from UserInfo";
SqlDataReader dr = Database.ExecuteReader(CommandType.Text,sql);
while( dr.Read())
userslist.Add(UserDataReader(dr));
return userslist;
}
public static User UserDataReader(IDataReader dr)
{
User user = new User();
user.UserID = Convert.ToInt32(dr["UserID"]);
user.UserName = Convert.ToString(dr["UserName"]);
user.Password = Convert.ToString(dr["UserPws"]);
user.Nickname = Convert.ToString(dr["Nickname"]);
user.Email = Convert.ToString(dr["Email"]);
user.DeserializeExtendedAttributes((byte[])dr["ExtendInfo"]);
return user;
}
}
}