Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)归海一刀
published in(发表于) 2014/1/30 0:50:49
.NET开发不可不知、不可不用的辅助类(二)_[Asp.Net教程]

.NET开发不可不知、不可不用的辅助类(二)_[Asp.Net教程]

















序列化及反序列化的辅助类SerializeUtil




/**////


/// 序列化及反序列化的辅助类
///

public sealed class SerializeUtil
{
private SerializeUtil()
{
}




序列化操作函数#region 序列化操作函数




/**////


/// 将对象序列化为二进制字节
///

/// 待序列化的对象
///
public static byte[] SerializeToBinary(object obj)
{
byte[] bytes = new byte[2500];
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(memoryStream, obj);
memoryStream.Seek(0, 0);




if (memoryStream.Length > bytes.Length)
{
bytes = new byte[memoryStream.Length];
}
bytes = memoryStream.ToArray();
}
return bytes;
}




/**////


/// 将文件对象序列化到文件中
///

/// 待序列化的对象
/// 文件路径
/// 文件打开模式
public static void SerializeToBinary(object obj, string path, FileMode fileMode)
{
using (FileStream fs = new FileStream(path, fileMode))
{
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, obj);
}
}




/**////


/// 将文件对象序列化到文件中
///

/// 待序列化的对象
/// 文件路径
public static void SerializeToBinary(object obj, string path)
{
SerializeToBinary(obj, path, FileMode.Create);
}





/**////


/// 将对象序列化为Soap字符串
///

/// 待序列化的对象
/// Soap字符串
public static string SerializeToSoap(object obj)
{
string soap = string.Empty;
using (MemoryStream memoryStream = new MemoryStream())
{
SoapFormatter sformatter = new SoapFormatter();
sformatter.Serialize(memoryStream, obj);
memoryStream.Seek(0, 0);
soap = Encoding.ASCII.GetString(memoryStream.ToArray());
}




return soap;
}




/**////


/// 将对象序列化为Soap字符串,并保存到文件中
///

/// 待序列化的对象
/// 文件路径
/// 文件打开模式
public static void SerializeToSoap(object obj, string path, FileMode fileMode)
{
FileStream fs = new FileStream(path, fileMode);




// Construct a BinaryFormatter and use it to serialize the data to the stream.
SoapFormatter formatter = new SoapFormatter();
try
{
formatter.Serialize(fs, obj);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}




/**////


/// 将对象序列化为Soap字符串,并保存到文件中
///

/// 待序列化的对象
/// 文件路径
public static void SerializeToSoap(object obj, string path)
{
SerializeToSoap(obj, path, FileMode.Create);
}





/**////


/// 将对象序列化为XML字符串
///

/// 待序列化的对象
/// XML字符串
public static string SerializeToXml(object obj)
{
string xml = "";
using (MemoryStream memoryStream = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(memoryStream, obj);
memoryStream.Seek(0, 0);
xml = Encoding.ASCII.GetString(memoryStream.ToArray());
}




return xml;
}




/**////


/// 将对象序列化为XML字符串并保存到文件
///

/// 待序列化的对象
/// 保存的文件路径
/// 文件打开模式
public static void SerializeToXmlFile(object obj, string path, FileMode fileMode)
{
using (FileStream fileStream = new FileStream(path, fileMode))
{
// Construct a BinaryFormatter and use it to serialize the data to the stream.
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(fileStream, obj);
}
}




/**////


/// 将对象序列化为XML字符串并保存到文件
///

/// 待序列化的对象
/// 保存的文件路径
public static void SerializeToXmlFile(object obj, string path)
{
SerializeToXmlFile(obj, path, FileMode.Create);
}




#endregion




反序列化操作函数#region 反序列化操作函数




/**////


/// 从XML文件中反序列化为Object对象
///

/// 对象的类型
/// XML文件
/// 反序列化后得到的对象
public static object DeserializeFromXmlFile(Type type, string path)
{
object result = new object();
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(type);
result = serializer.Deserialize(fileStream);
}




return result;
}




/**////


/// 从XML文件中反序列化为对象
///

/// 对象的类型
/// XML字符串
/// 反序列化后得到的对象
public static object DeserializeFromXml(Type type, string xml)
{
object result = new object();
XmlSerializer serializer = new XmlSerializer(type);
result = serializer.Deserialize(new StringReader(xml));




return result;
}




/**////


/// 从Soap字符串中反序列化为对象
///

/// 对象的类型
/// soap字符串
/// 反序列化后得到的对象
public static object DeserializeFromSoap(Type type, string soap)
{
object result = new object();
using (MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(soap)))
{
SoapFormatter serializer = new SoapFormatter();
result = serializer.Deserialize(memoryStream);
}




return result;
}




/**////


/// 从二进制字节中反序列化为对象
///

/// 对象的类型
/// 字节数组
/// 反序列化后得到的对象
public static object DeserializeFromBinary(Type type, byte[] bytes)
{
object result = new object();
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
BinaryFormatter serializer = new BinaryFormatter();
result = serializer.Deserialize(memoryStream);
}




return result;
}




/**////


/// 从二进制文件中反序列化为对象
///

/// 对象的类型
/// 二进制文件路径
/// 反序列化后得到的对象
public static object DeserializeFromBinary(Type type, string path)
{
object result = new object();
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
BinaryFormatter serializer = new BinaryFormatter();
result = serializer.Deserialize(fileStream);
}




return result;
}




#endregion




/**////


/// 获取对象的转换为二进制的字节大小
///

///
///
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;
}




/**////


/// 克隆一个对象
///

/// 待克隆的对象
/// 克隆的一个新的对象
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;
}




/**////


/// 从文件中读取文本内容
///

/// 文件路径
/// 文件的内容
public static string ReadFile(string path)
{
string content = string.Empty;
using (StreamReader reader = new StreamReader(path))
{
content = reader.ReadToEnd();
}




return content;
}




/**////


/// 读取嵌入资源的文本内容
///

/// 包含命名空间的嵌入资源文件名路径
/// 文件中的文本内容
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




/**////


/// 用来转换含有NULL值的字段为合适值的辅助类
///

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;
}

/**////


/// 将DataReader的属性值转化为实体类的属性值,返回实体类
///

/// 有效的DataReader对象
/// 实体类对象
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;
}
}




字符串操作辅助类




/**////


/// 字符串操作辅助类
///

public class StringUtil
{
一些基本的符号常量#region 一些基本的符号常量




/**////


/// 点符号 .
///

public const string Dot = ".";




/**////


/// 下划线 _
///

public const string UnderScore = "_";




/**////


/// 逗号加空格 ,
///

public const string CommaSpace = ", ";




/**////


/// 逗号 ,
///

public const string Comma = ",";




/**////


/// 左括号 (
///

public const string OpenParen = "(";




/**////


/// 右括号 )
///

public const string ClosedParen = ")";




/**////


/// 单引号 '
///

public const string SingleQuote = "\'";




/**////


/// 斜线 \
///

public const string Slash = @"\";




#endregion




private StringUtil()
{
}




/**////


/// 移除空格并首字母小写的Camel样式
///

///
///
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));
}




/**////


/// 移除空格并首字母大写的Pascal样式
///

///
///
public static string ToCapit(string name)
{
string clone = name.TrimStart('_');
return RemoveSpaces(ToProperCase(clone));
}





/**////


/// 移除最后的字符
///

///
///
public static string RemoveFinalChar(string s)
{
if (s.Length > 1)
{
s = s.Substring(0, s.Length - 1);
}
return s;
}




/**////


/// 移除最后的逗号
///

///
///
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;
}




/**////


/// 移除字符中的空格
///

///
///
public static string RemoveSpaces(string s)
{
s = s.Trim();
s = s.Replace(" ", "");
return s;
}




/**////


/// 字符串首字母大写
///

///
///
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;
}




/**////


/// 判断字符是否NULL或者为空
///

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界面层操作的辅助类




/**////


/// Web界面层操作的辅助类
///

public sealed class UIHelper
{
private static ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);




private UIHelper()
{
}




/**////


/// 提示信息,如果异常为HWException类型,则记录到日志
///

/// 当前的页面
/// 异常对象
/// 是否关闭
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);
}
}




/**////


/// 提示信息
///

/// 当前的页面
/// 提示信息
public static void Alerts(Control control, string message)
{
string script = string.Format("", message).Replace("\r\n", "");
control.Page.RegisterStartupScript("", script);
}




/**////


/// 提示信息并关闭窗口
///

/// 当前的页面
/// 提示信息
public static void AlertAndClose(Control control, string message)
{
string script =
string.Format("", message).Replace("\r\n", "");
control.Page.RegisterStartupScript("", script);
}




/**////


/// 将错误信息记录到事件日志中
///

/// 文本信息
public static void LogError(string errorMessage)
{
logger.Error(errorMessage);
}




/**////


/// 将错误信息记录到事件日志中
///

/// 错误对象
public static void LogError(Exception ex)
{
try
{
logger.Error(ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
}
catch
{
}
}




/**////


/// 弹出提示信息
///

/// key
/// 提示信息
/// 当前请求的page
public static void Alert(string key, string message, Page page)
{
string msg = string.Format("", message);




page.RegisterStartupScript(key, msg);
}




/**////


/// 弹出提示信息
///

///
///
public static void Alert(string message, Page page)
{
Alert("message", message, page);
}




/**////


/// 定位到指定的页面
///

/// 目标页面
public static void GoTo(string GoPage)
{
HttpContext.Current.Response.Redirect(GoPage);
}




/**////


/// 定位到指定的页面
///

/// 当前请求的page
/// 目标页面
public static void Location(Control control, string page)
{
string js = "";
control.Page.RegisterStartupScript("", js);
}




/**////


/// 提示信息并定位到指定的页面
///

/// 当前请求的page
/// 目标页面
/// 提示信息
public static void AlertAndLocation(Control control, string page, string message)
{
string js = "";
control.Page.RegisterStartupScript("", js);
}




/**////


/// 关闭页面,并返回指定的值
///

///
///
public static void CloseWin(Control control, string returnValue)
{
string js = "";
control.Page.RegisterStartupScript("", js);
}




/**////


/// 获取Html的锚点
///

///
///
///
public static HtmlAnchor GetHtmlAnchor(string innerText, string href)
{
HtmlAnchor htmlAnchor = new HtmlAnchor();
htmlAnchor.InnerText = innerText;
htmlAnchor.HRef = href;




return htmlAnchor;
}




/**////


/// 判断输入的字符是否为数字
///

///
///
public static bool IsNumerical(string strValue)
{
return Regex.IsMatch(strValue, @"^[0-9]*");
}




/**////


/// 判断字符串是否是NULL或者string.Empty
///

///
///
public static bool IsNullorEmpty(string text)
{
return text == null || text.Trim() == string.Empty;
}




/**////


/// 获取DataGrid控件中选择的项目的ID字符串(要求DataGrid设置datakeyfield="ID")
///

/// 如果没有选择, 那么返回为空字符串, 否则返回逗号分隔的ID字符串(如1,2,3)
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;
}





/**////


/// 设置下列列表控件的SelectedValue
///

/// DropDownList控件
/// SelectedValue的值
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);
}




来源:cnblogs

























If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759