序列化及反序列化的辅助类SerializeUtil
/// <summary>
/// 序列化及反序列化的辅助类
/// </summary>
public sealed class SerializeUtil
{
private SerializeUtil()
{
}
序列化操作函数
反序列化操作函数
/// <summary>
/// 获取对象的转换为二进制的字节大小
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static long GetByteSize(object obj)
{
long result;
BinaryFormatter bFormatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
bFormatter.Serialize(stream, obj);
result = stream.Length;
}
return result;
}
/// <summary>
/// 克隆一个对象
/// </summary>
/// <param name="obj">待克隆的对象</param>
/// <returns>克隆的一个新的对象</returns>
public static object Clone(object obj)
{
object cloned = null;
BinaryFormatter bFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
try
{
bFormatter.Serialize(memoryStream, obj);
memoryStream.Seek(0, SeekOrigin.Begin);
cloned = bFormatter.Deserialize(memoryStream);
}
catch //(Exception e)
{
;
}
}
return cloned;
}
/// <summary>
/// 从文件中读取文本内容
/// </summary>
/// <param name="path">文件路径</param>
/// <returns>文件的内容</returns>
public static string ReadFile(string path)
{
string content = string.Empty;
using (StreamReader reader = new StreamReader(path))
{
content = reader.ReadToEnd();
}
return content;
}
/// <summary>
/// 读取嵌入资源的文本内容
/// </summary>
/// <param name="fileWholeName">包含命名空间的嵌入资源文件名路径</param>
/// <returns>文件中的文本内容</returns>
public static string ReadFileFromEmbedded(string fileWholeName)
{
string result = string.Empty;
Assembly assembly = Assembly.GetEntryAssembly();
using (TextReader reader = new StreamReader(assembly.GetManifestResourceStream(fileWholeName)))
{
result = reader.ReadToEnd();
}
return result;
}
}
序列化及反序列化的辅助类SerializeUtil测试代码
public class TestSerializeUtil
{
public static string Execute()
{
string result = string.Empty;
result += "使用SerializeUtil序列化及反序列化的辅助类:" + "\r\n";
Person person = new Person();
person.Name = "wuhuacong";
person.Age = 20;
byte[] bytes = SerializeUtil.SerializeToBinary(person);
Person person2 = SerializeUtil.DeserializeFromBinary(typeof (Person), bytes) as Person;
result += ReflectionUtil.GetProperties(person2) + "\r\n";
string xml = SerializeUtil.SerializeToXml(person);
Person person3 = SerializeUtil.DeserializeFromXml(typeof (Person), xml) as Person;
result += "person3:\r\n" + ReflectionUtil.GetProperties(person3) + "\r\n";
result += "SerializeUtil.GetByteSize(person3):" + SerializeUtil.GetByteSize(person3) + "\r\n";
Person person4 = SerializeUtil.Clone(person3) as Person;
result += "person4:\r\n" + ReflectionUtil.GetProperties(person4) + "\r\n";
result += "Util.AreObjectsEqual(person3, person4):" + Util.AreObjectsEqual(person3, person4)+ "\r\n";
SerializeUtil.SerializeToXmlFile(person3, Util.CurrentPath + "person3.xml", FileMode.Create);
Person person5 = SerializeUtil.DeserializeFromXmlFile(typeof (Person), Util.CurrentPath + "person3.xml") as Person;
result += "person5:\r\n" + ReflectionUtil.GetProperties(person5) + "\r\n\r\n";
result += SerializeUtil.ReadFile(Util.CurrentPath + "person3.xml") + "\r\n\r\n";
result += SerializeUtil.ReadFileFromEmbedded("TestUtilities.EmbedFile.xml") + "\r\n\r\n";
return result;
}
}
数据库字段NULL值转换辅助类SmartDataReader
/// <summary>
/// 用来转换含有NULL值的字段为合适值的辅助类
/// </summary>
public sealed class SmartDataReader
{
private DateTime defaultDate;
public SmartDataReader(IDataReader reader)
{
defaultDate = Convert.ToDateTime("01/01/1900");
this.reader = reader;
}
public int GetInt32(String column)
{
int data = (reader.IsDBNull(reader.GetOrdinal(column))) ? (int) 0 : (int) reader[column];
return data;
}
public short GetInt16(String column)
{
short data = (reader.IsDBNull(reader.GetOrdinal(column))) ? (short) 0 : (short) reader[column];
return data;
}
public byte GetByte(String column)
{
byte data = (reader.IsDBNull(reader.GetOrdinal(column))) ? (byte) 0 : (byte) reader[column];
return data;
}
public float GetFloat(String column)
{
float data = (reader.IsDBNull(reader.GetOrdinal(column))) ? 0 : float.Parse(reader[column].ToString());
return data;
}
public double GetDouble(String column)
{
double data = (reader.IsDBNull(reader.GetOrdinal(column))) ? 0 : double.Parse(reader[column].ToString());
return data;
}
public decimal GetDecimal(String column)
{
decimal data = (reader.IsDBNull(reader.GetOrdinal(column))) ? 0 : decimal.Parse(reader[column].ToString());
return data;
}
public Single GetSingle(String column)
{
Single data = (reader.IsDBNull(reader.GetOrdinal(column))) ? 0 : Single.Parse(reader[column].ToString());
return data;
}
public bool GetBoolean(String column)
{
bool data = (reader.IsDBNull(reader.GetOrdinal(column))) ? false : (bool) reader[column];
return data;
}
public String GetString(String column)
{
String data = (reader.IsDBNull(reader.GetOrdinal(column))) ? null : reader[column].ToString();
return data;
}
public byte[] GetBytes(String column)
{
String data = (reader.IsDBNull(reader.GetOrdinal(column))) ? null : reader[column].ToString();
return Encoding.UTF8.GetBytes(data);
}
public Guid GetGuid(String column)
{
String data = (reader.IsDBNull(reader.GetOrdinal(column))) ? null : reader[column].ToString();
Guid guid = Guid.Empty;
if (data != null)
{
guid = new Guid(data);
}
return guid;
}
public DateTime GetDateTime(String column)
{
DateTime data = (reader.IsDBNull(reader.GetOrdinal(column))) ? defaultDate : (DateTime) reader[column];
return data;
}
public bool Read()
{
return reader.Read();
}
private IDataReader reader;
}
数据库字段NULL值转换辅助类SmartDataReader测试代码
public class TestSmartDataReader
{
public static string Execute()
{
string result = string.Empty;
result += "使用SmartDataReader辅助类:" + "\r\n";
try
{
TestInfo person = SelectOne();
result += ReflectionUtil.GetProperties(person) + "\r\n \r\n";
}
catch (Exception ex)
{
result += string.Format("发生错误:{0}!\r\n \r\n", ex.Message);
}
return result;
}
/// <summary>
/// 将DataReader的属性值转化为实体类的属性值,返回实体类
/// </summary>
/// <param name="dataReader">有效的DataReader对象</param>
/// <returns>实体类对象</returns>
private static TestInfo DataReaderToEntity(IDataReader dataReader)
{
TestInfo testInfo = new TestInfo();
SmartDataReader reader = new SmartDataReader(dataReader);
testInfo.ID = reader.GetInt32("ID");
testInfo.Name = reader.GetString("Name");
testInfo.Age = reader.GetInt32("Age");
testInfo.Man = reader.GetBoolean("Man");
testInfo.Birthday = reader.GetDateTime("Birthday");
return testInfo;
}
public static TestInfo SelectOne()
{
TestInfo testInfo = null;
string sqlCommand = " Select top 1 * from Test";
string connectionString = "Server=localhost;Database=Test;uid=sa;pwd=123456";
using(SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand com = new SqlCommand(sqlCommand, connection);
using (IDataReader reader = com.ExecuteReader())
{
if (reader.Read())
{
testInfo = DataReaderToEntity(reader);
}
}
}
return testInfo;
}
}
字符串操作辅助类
/// <summary>
/// 字符串操作辅助类
/// </summary>
public class StringUtil
{
一些基本的符号常量
private StringUtil()
{
}
/// <summary>
/// 移除空格并首字母小写的Camel样式
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string ToCamel(string name)
{
string clone = name.TrimStart('_');
clone = RemoveSpaces(ToProperCase(clone));
return String.Format("{0}{1}", Char.ToLower(clone[0]), clone.Substring(1, clone.Length - 1));
}
/// <summary>
/// 移除空格并首字母大写的Pascal样式
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string ToCapit(string name)
{
string clone = name.TrimStart('_');
return RemoveSpaces(ToProperCase(clone));
}
/// <summary>
/// 移除最后的字符
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string RemoveFinalChar(string s)
{
if (s.Length > 1)
{
s = s.Substring(0, s.Length - 1);
}
return s;
}
/// <summary>
/// 移除最后的逗号
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string RemoveFinalComma(string s)
{
if (s.Trim().Length > 0)
{
int c = s.LastIndexOf(",");
if (c > 0)
{
s = s.Substring(0, s.Length - (s.Length - c));
}
}
return s;
}
/// <summary>
/// 移除字符中的空格
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string RemoveSpaces(string s)
{
s = s.Trim();
s = s.Replace(" ", "");
return s;
}
/// <summary>
/// 字符串首字母大写
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string ToProperCase(string s)
{
string revised = "";
if (s.Length > 0)
{
if (s.IndexOf(" ") > 0)
{
revised = Strings.StrConv(s, VbStrConv.ProperCase, 1033);
}
else
{
string firstLetter = s.Substring(0, 1).ToUpper(new CultureInfo("en-US"));
revised = firstLetter + s.Substring(1, s.Length - 1);
}
}
return revised;
}
/// <summary>
/// 判断字符是否NULL或者为空
/// </summary>
public static bool IsNullOrEmpty(string value)
{
if (value == null || value == string.Empty)
{
return true;
}
return false;
}
}
字符串操作辅助类测试代码
public class TestStringUtil
{
public static string Execute()
{
string value = "test String,";
string result = string.Empty;
result += "使用StringUtil字符串操作辅助类:" + "\r\n";
result += "原字符串为:" + value + "\r\n";
result += "StringUtil.IsNullOrEmpty:" + StringUtil.IsNullOrEmpty(value) + "\r\n";
result += "StringUtil.ToCamel:" + StringUtil.ToCamel(value) + "\r\n";
result += "StringUtil.ToCapit:" + StringUtil.ToCapit(value) + "\r\n";
result += "StringUtil.RemoveSpaces:" + StringUtil.RemoveSpaces(value) + "\r\n";
result += "StringUtil.RemoveFinalChar:" + StringUtil.RemoveFinalChar(value) + "\r\n";
result += "StringUtil.ToProperCase:" + StringUtil.ToProperCase(value) + "\r\n";
result += "\r\n\r\n";
return result;
}
Web界面层操作的辅助类
/// <summary>
/// Web界面层操作的辅助类
/// </summary>
public sealed class UIHelper
{
private static ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private UIHelper()
{
}
/// <summary>
/// 提示信息,如果异常为HWException类型,则记录到日志
/// </summary>
/// <param name="page">当前的页面</param>
/// <param name="ex">异常对象</param>
/// <param name="Close">是否关闭</param>
public static void ShowError(Page page, Exception ex, bool Close)
{
logger.Error("Exception:" + page.ID, ex);
string errorMsg = ex.Message;
errorMsg = errorMsg.Replace("\n", " ");
if (Close)
{
AlertAndClose(page, errorMsg);
}
else
{
Alerts(page, errorMsg);
}
}
/// <summary>
/// 提示信息
/// </summary>
/// <param name="control">当前的页面</param>
/// <param name="message">提示信息</param>
public static void Alerts(Control control, string message)
{
string script = string.Format("<script>javascript:alert(\"{0}\");</script>", message).Replace("\r\n", "");
control.Page.RegisterStartupScript("", script);
}
/// <summary>
/// 提示信息并关闭窗口
/// </summary>
/// <param name="control">当前的页面</param>
/// <param name="message">提示信息</param>
public static void AlertAndClose(Control control, string message)
{
string script =
string.Format("<script>javascript:alert(\"{0}\");window.close();</script>", message).Replace("\r\n", "");
control.Page.RegisterStartupScript("", script);
}
/// <summary>
/// 将错误信息记录到事件日志中
/// </summary>
/// <param name="errorMessage">文本信息</param>
public static void LogError(string errorMessage)
{
logger.Error(errorMessage);
}
/// <summary>
/// 将错误信息记录到事件日志中
/// </summary>
/// <param name="ex">错误对象</param>
public static void LogError(Exception ex)
{
try
{
logger.Error(ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
}
catch
{
}
}
/// <summary>
/// 弹出提示信息
/// </summary>
/// <param name="key">key</param>
/// <param name="message">提示信息</param>
/// <param name="page">当前请求的page</param>
public static void Alert(string key, string message, Page page)
{
string msg = string.Format("<script language=\"javascript\">alert(\"{0}\");</script>", message);
page.RegisterStartupScript(key, msg);
}
/// <summary>
/// 弹出提示信息
/// </summary>
/// <param name="message"></param>
/// <param name="page"></param>
public static void Alert(string message, Page page)
{
Alert("message", message, page);
}
/// <summary>
/// 定位到指定的页面
/// </summary>
/// <param name="GoPage">目标页面</param>
public static void GoTo(string GoPage)
{
HttpContext.Current.Response.Redirect(GoPage);
}
/// <summary>
/// 定位到指定的页面
/// </summary>
/// <param name="control">当前请求的page</param>
/// <param name="page">目标页面</param>
public static void Location(Control control, string page)
{
string js = "<script language='JavaScript'>";
js += "top.location='" + page + "'";
js += "</script>";
control.Page.RegisterStartupScript("", js);
}
/// <summary>
/// 提示信息并定位到指定的页面
/// </summary>
/// <param name="control">当前请求的page</param>
/// <param name="page">目标页面</param>
/// <param name="message">提示信息</param>
public static void AlertAndLocation(Control control, string page, string message)
{
string js = "<script language='JavaScript'>";
js += "alert('" + message + "');";
js += "top.location='" + page + "'";
js += "</script>";
control.Page.RegisterStartupScript("", js);
}
/// <summary>
/// 关闭页面,并返回指定的值
/// </summary>
/// <param name="control"></param>
/// <param name="returnValue"></param>
public static void CloseWin(Control control, string returnValue)
{
string js = "<script language='JavaScript'>";
js += "window.parent.returnValue='" + returnValue + "';";
js += "window.close();";
js += "</script>";
control.Page.RegisterStartupScript("", js);
}
/// <summary>
/// 获取Html的锚点
/// </summary>
/// <param name="innerText"></param>
/// <param name="href"></param>
/// <returns></returns>
public static HtmlAnchor GetHtmlAnchor(string innerText, string href)
{
HtmlAnchor htmlAnchor = new HtmlAnchor();
htmlAnchor.InnerText = innerText;
htmlAnchor.HRef = href;
return htmlAnchor;
}
/// <summary>
/// 判断输入的字符是否为数字
/// </summary>
/// <param name="strValue"></param>
/// <returns></returns>
public static bool IsNumerical(string strValue)
{
return Regex.IsMatch(strValue, @"^[0-9]*$");
}
/// <summary>
/// 判断字符串是否是NULL或者string.Empty
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool IsNullorEmpty(string text)
{
return text == null || text.Trim() == string.Empty;
}
/// <summary>
/// 获取DataGrid控件中选择的项目的ID字符串(要求DataGrid设置datakeyfield="ID")
/// </summary>
/// <returns>如果没有选择, 那么返回为空字符串, 否则返回逗号分隔的ID字符串(如1,2,3)</returns>
public static string GetDatagridItems(DataGrid dg)
{
string idstring = string.Empty;
foreach (DataGridItem item in dg.Items)
{
string key = dg.DataKeys[item.ItemIndex].ToString();
bool isSelected = ((CheckBox) item.FindControl("cbxDelete")).Checked;
if (isSelected)
{
idstring += "'" + key + "'" + ","; //前后追加单引号,可以其他非数值的ID
}
}
idstring = idstring.Trim(',');
return idstring;
}
/// <summary>
/// 设置下列列表控件的SelectedValue
/// </summary>
/// <param name="control">DropDownList控件</param>
/// <param name="strValue">SelectedValue的值</param>
public static void SetDropDownListItem(DropDownList control, string strValue)
{
if (!IsNullorEmpty(strValue))
{
control.ClearSelection();
ListItem item = control.Items.FindByValue(strValue);
if (item != null)
{
control.SelectedValue = item.Value;
}
}
}
}
Web界面层操作的辅助类测试代码
private void btnShowError_Click(object sender, EventArgs e)
{
try
{
throw new Exception("测试错误");
}
catch (Exception ex)
{
UIHelper.ShowError(this, ex, false);
return;
}
}
private void btnAlert_Click(object sender, EventArgs e)
{
UIHelper.Alert("这是一个提示信息", this);
}
本文转自博客园伍华聪的博客,原文链接:.NET开发不可不知、不可不用的辅助类(二),如需转载请自行联系原博主。