1. 用於獲取或設置Web.config/*.exe.config中節點數據的輔助類
/**//// <summary>
/// 用於獲取或設置Web.config/*.exe.config中節點數據的輔助類
/// </summary>
public sealed class AppConfig
{
private string filePath;
/**//// <summary>
/// 從當前目錄中按順序檢索Web.Config和*.App.Config文件。
/// 如果找到一個,則使用它作爲配置文件;否則會拋出一個ArgumentNullException異常。
/// </summary>
public AppConfig()
{
string webconfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web.Config");
string appConfig = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile.Replace(".vshost", "");
if (File.Exists(webconfig))
{
filePath = webconfig;
}
else if (File.Exists(appConfig))
{
filePath = appConfig;
}
else
{
throw new ArgumentNullException("沒有找到Web.Config文件或者應用程序配置文件, 請指定配置文件");
}
}
/**//// <summary>
/// 用戶指定具體的配置文件路徑
/// </summary>
/// <param name="configFilePath">配置文件路徑(絕對路徑)</param>
public AppConfig(string configFilePath)
{
filePath = configFilePath;
}
/**//// <summary>
/// 設置程序的config文件
/// </summary>
/// <param name="keyName">鍵名</param>
/// <param name="keyValue">鍵值</param>
public void AppConfigSet(string keyName, string keyValue)
{
//由於存在多個Add鍵值,使得訪問appSetting的操作不成功,故註釋下面語句,改用新的方式
/**//*
string xpath = "//add[@key='" + keyName + "']";
xmlDocument document = new XmlDocument();
document.Load(filePath);
xmlNode node = document.SelectSingleNode(xpath);
node.Attributes["value"].Value = keyValue;
document.Save(filePath);
*/
xmlDocument document = new XmlDocument();
document.Load(filePath);
xmlNodeList nodes = document.GetElementsByTagName("add");
for (int i = 0; i < nodes.Count; i++)
{
//獲得將當前元素的key屬性
xmlAttribute attribute = nodes[i].Attributes["key"];
//根據元素的第一個屬性來判斷當前的元素是不是目標元素
if (attribute != null && (attribute.Value == keyName))
{
attribute = nodes[i].Attributes["value"];
//對目標元素中的第二個屬性賦值
if (attribute != null)
{
attribute.Value = keyValue;
break;
}
}
}
document.Save(filePath);
}
/**//// <summary>
/// 讀取程序的config文件的鍵值。
/// 如果鍵名不存在,返回空
/// </summary>
/// <param name="keyName">鍵名</param>
/// <returns></returns>
public string AppConfigGet(string keyName)
{
string strReturn = string.Empty;
try
{
xmlDocument document = new XmlDocument();
document.Load(filePath);
xmlNodeList nodes = document.GetElementsByTagName("add");
for (int i = 0; i < nodes.Count; i++)
{
//獲得將當前元素的key屬性
xmlAttribute attribute = nodes[i].Attributes["key"];
//根據元素的第一個屬性來判斷當前的元素是不是目標元素
if (attribute != null && (attribute.Value == keyName))
{
attribute = nodes[i].Attributes["value"];
if (attribute != null)
{
strReturn = attribute.Value;
break;
}
}
}
}
catch
{
;
}
return strReturn;
}
/**//// <summary>
/// 獲取指定鍵名中的子項的值
/// </summary>
/// <param name="keyName">鍵名</param>
/// <param name="subKeyName">以分號(;)爲分隔符的子項名稱</param>
/// <returns>對應子項名稱的值(即是=號後面的值)</returns>
public string GetSubValue(string keyName, string subKeyName)
{
string connectionString = AppConfigGet(keyName).ToLower();
string[] item = connectionString.Split(new char[] {';'});
for (int i = 0; i < item.Length; i++)
{
string itemValue = item[i].ToLower();
if (itemValue.IndexOf(subKeyName.ToLower()) >= 0) //如果含有指定的關鍵字
{
int startIndex = item[i].IndexOf("="); //等號開始的位置
return item[i].Substring(startIndex + 1); //獲取等號後面的值即爲Value
}
}
return string.Empty;
}
}
AppConfig測試代碼:
public class TestAppConfig
{
public static string Execute()
{
string result = string.Empty;
//讀取Web.Config的
AppConfig config = new AppConfig();
result += "讀取Web.Config中的配置信息:" + "/r/n";
result += config.AppName + "/r/n";
result += config.AppConfigGet("WebConfig") + "/r/n";
config.AppConfigSet("WebConfig", DateTime.Now.ToString("hh:mm:ss"));
result += config.AppConfigGet("WebConfig") + "/r/n/r/n";
//讀取*.App.Config的
config = new AppConfig("TestUtilities.exe.config");
result += "讀取TestUtilities.exe.config中的配置信息:" + "/r/n";
result += config.AppName + "/r/n";
result += config.AppConfigGet("AppConfig") + "/r/n";
config.AppConfigSet("AppConfig", DateTime.Now.ToString("hh:mm:ss"));
result += config.AppConfigGet("AppConfig") + "/r/n/r/n";
return result;
}
}
2. 反射操作輔助類ReflectionUtil
/**//// <summary>
/// 反射操作輔助類
/// </summary>
public sealed class ReflectionUtil
{
private ReflectionUtil()
{
}
private static BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
/**//// <summary>
/// 執行某個方法
/// </summary>
/// <param name="obj">指定的對象</param>
/// <param name="methodName">對象方法名稱</param>
/// <param name="args">參數</param>
/// <returns></returns>
public static object InvokeMethod(object obj, string methodName, object[] args)
{
object objResult = null;
Type type = obj.GetType();
objResult = type.InvokeMember(methodName, bindingFlags | BindingFlags.InvokeMethod, null, obj, args);
return objResult;
}
/**//// <summary>
/// 設置對象字段的值
/// </summary>
public static void SetField(object obj, string name, object value)
{
FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
object objValue = Convert.ChangeType(value, fieldInfo.FieldType);
fieldInfo.SetValue(objValue, value);
}
/**//// <summary>
/// 獲取對象字段的值
/// </summary>
public static object GetField(object obj, string name)
{
FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
return fieldInfo.GetValue(obj);
}
/**//// <summary>
/// 設置對象屬性的值
/// </summary>
public static void SetProperty(object obj, string name, object value)
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
object objValue = Convert.ChangeType(value, propertyInfo.PropertyType);
propertyInfo.SetValue(obj, objValue, null);
}
/**//// <summary>
/// 獲取對象屬性的值
/// </summary>
public static object GetProperty(object obj, string name)
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
return propertyInfo.GetValue(obj, null);
}
/**//// <summary>
/// 獲取對象屬性信息(組裝成字符串輸出)
/// </summary>
public static string GetProperties(object obj)
{
StringBuilder strBuilder = new StringBuilder();
PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bindingFlags);
foreach (PropertyInfo property in propertyInfos)
{
strBuilder.Append(property.Name);
strBuilder.Append(":");
strBuilder.Append(property.GetValue(obj, null));
strBuilder.Append("/r/n");
}
return strBuilder.ToString();
}
}
反射操作輔助類ReflectionUtil測試代碼:
public class TestReflectionUtil
{
public static string Execute()
{
string result = string.Empty;
result += "使用ReflectionUtil反射操作輔助類:" + "/r/n";
try
{
Person person = new Person();
person.Name = "wuhuacong";
person.Age = 20;
result += DecriptPerson(person);
person.Name = "Wade Wu";
person.Age = 99;
result += DecriptPerson(person);
}
catch (Exception ex)
{
result += string.Format("發生錯誤:{0}!/r/n /r/n", ex.Message);
}
return result;
}
public static string DecriptPerson(Person person)
{
string result = string.Empty;
result += "name:" + ReflectionUtil.GetField(person, "name") + "/r/n";
result += "age" + ReflectionUtil.GetField(person, "age") + "/r/n";
result += "Name:" + ReflectionUtil.GetProperty(person, "Name") + "/r/n";
result += "Age:" + ReflectionUtil.GetProperty(person, "Age") + "/r/n";
result += "Say:" + ReflectionUtil.InvokeMethod(person, "Say", new object[] {}) + "/r/n";
result += "操作完成!/r/n /r/n";
return result;
}
}
3. 註冊表訪問輔助類RegistryHelper
/**//// <summary>
/// 註冊表訪問輔助類
/// </summary>
public sealed class RegistryHelper
{
private string softwareKey = string.Empty;
private RegistryKey rootRegistry = Registry.CurrentUser;
/**//// <summary>
/// 使用註冊表鍵構造,默認從Registry.CurrentUser開始。
/// </summary>
/// <param name="softwareKey">註冊表鍵,格式如"SOFTWARE//Huaweisoft//EDNMS"的字符串</param>
public RegistryHelper(string softwareKey) : this(softwareKey, Registry.CurrentUser)
{
}
/**//// <summary>
/// 指定註冊表鍵及開始的根節點查詢
/// </summary>
/// <param name="softwareKey">註冊表鍵</param>
/// <param name="rootRegistry">開始的根節點(Registry.CurrentUser或者Registry.LocalMachine等)</param>
public RegistryHelper(string softwareKey, RegistryKey rootRegistry)
{
this.softwareKey = softwareKey;
this.rootRegistry = rootRegistry;
}
/**//// <summary>
/// 根據註冊表的鍵獲取鍵值。
/// 如果註冊表的鍵不存在,返回空字符串。
/// </summary>
/// <param name="key">註冊表的鍵</param>
/// <returns>鍵值</returns>
public string GetValue(string key)
{
const string parameter = "key";
if (null == key)
{
throw new ArgumentNullException(parameter);
}
string result = string.Empty;
try
{
RegistryKey registryKey = rootRegistry.OpenSubKey(softwareKey);
result = registryKey.GetValue(key).ToString();
}
catch
{
;
}
return result;
}
/**//// <summary>
/// 保存註冊表的鍵值
/// </summary>
/// <param name="key">註冊表的鍵</param>
/// <param name="value">鍵值</param>
/// <returns>成功返回true,否則返回false.</returns>
public bool SaveValue(string key, string value)
{
const string parameter1 = "key";
const string parameter2 = "value";
if (null == key)
{
throw new ArgumentNullException(parameter1);
}
if (null == value)
{
throw new ArgumentNullException(parameter2);
}
RegistryKey registryKey = rootRegistry.OpenSubKey(softwareKey, true);
if (null == registryKey)
{
registryKey = rootRegistry.CreateSubKey(softwareKey);
}
registryKey.SetValue(key, value);
return true;
}
}
註冊表訪問輔助類RegistryHelper測試代碼:
public class TestRegistryHelper
{
public static string Execute()
{
string result = string.Empty;
result += "使用RegistryHelper註冊表訪問輔助類:" + "/r/n";
RegistryHelper registry = new RegistryHelper("SoftWare//HuaweiSoft//EDNMS");
bool sucess = registry.SaveValue("Test", DateTime.Now.ToString("hh:mm:ss"));
if (sucess)
{
result += registry.GetValue("Test");
}
return result;
}
}
4. 壓縮/解壓縮輔助類ZipUtil
/**//// <summary>
/// 壓縮/解壓縮輔助類
/// </summary>
public sealed class ZipUtil
{
private ZipUtil()
{
}
/**//// <summary>
/// 壓縮文件操作
/// </summary>
/// <param name="fileToZip">待壓縮文件名</param>
/// <param name="zipedFile">壓縮後的文件名</param>
/// <param name="compressionLevel">0~9,表示壓縮的程度,9表示最高壓縮</param>
/// <param name="blockSize">緩衝塊大小</param>
public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
{
if (! File.Exists(fileToZip))
{
throw new FileNotFoundException("文件 " + fileToZip + " 沒有找到,取消壓縮。");
}
using (FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
{
FileStream fileStream = File.Create(zipedFile);
using (ZipOutputStream zipStream = new ZipOutputStream(fileStream))
{
ZipEntry zipEntry = new ZipEntry(fileToZip);
zipStream.PutNextEntry(zipEntry);
zipStream.SetLevel(compressionLevel);
byte[] buffer = new byte[blockSize];
Int32 size = streamToZip.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, size);
try
{
while (size < streamToZip.Length)
{
int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, sizeRead);
size += sizeRead;
}
}
catch (Exception ex)
{
throw ex;
}
zipStream.Finish();
}
}
}
/**//// <summary>
/// 打開sourceZipPath的壓縮文件,解壓到destPath目錄中
/// </summary>
/// <param name="sourceZipPath">待解壓的文件路徑</param>
/// <param name="destPath">解壓後的文件路徑</param>
public static void UnZipFile(string sourceZipPath, string destPath)
{
if (!destPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
destPath = destPath + Path.DirectorySeparatorChar;
}
using (ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(sourceZipPath)))
{
ZipEntry theEntry;
while ((theEntry = zipInputStream.GetNextEntry()) != null)
{
string fileName = destPath + Path.GetDirectoryName(theEntry.Name) +
Path.DirectorySeparatorChar + Path.GetFileName(theEntry.Name);
//create directory for file (if necessary)
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
if (!theEntry.IsDirectory)
{
using (FileStream streamWriter = File.Create(fileName))
{
int size = 2048;
byte[] data = new byte[size];
try
{
while (true)
{
size = zipInputStream.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
catch
{
}
}
}
}
}
}
}
壓縮/解壓縮輔助類ZipUtil測試代碼:
public class TestZipUtil
{
public static string Execute()
{
string result = string.Empty;
result += "使用ZipUtil壓縮/解壓縮輔助類:" + "/r/n";
try
{
ZipUtil.ZipFile("Web.Config", "Test.Zip", 6, 512);
ZipUtil.UnZipFile("Test.Zip", "Test");
result += "操作完成!/r/n /r/n";
}
catch (Exception ex)
{
result += string.Format("發生錯誤:{0}!/r/n /r/n", ex.Message);
}
return result;
}
}
序列化及反序列化的輔助類SerializeUtil
/**//// <summary>
/// 序列化及反序列化的輔助類
/// </summary>
public sealed class SerializeUtil
{
private SerializeUtil()
{
}
序列化操作函數#region 序列化操作函數
/**//// <summary>
/// 將對象序列化爲二進制字節
/// </summary>
/// <param name="obj">待序列化的對象</param>
/// <returns></returns>
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;
}
/**//// <summary>
/// 將文件對象序列化到文件中
/// </summary>
/// <param name="obj">待序列化的對象</param>
/// <param name="path">文件路徑</param>
/// <param name="fileMode">文件打開模式</param>
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);
}
}
/**//// <summary>
/// 將文件對象序列化到文件中
/// </summary>
/// <param name="obj">待序列化的對象</param>
/// <param name="path">文件路徑</param>
public static void SerializeToBinary(object obj, string path)
{
SerializeToBinary(obj, path, FileMode.Create);
}
/**//// <summary>
/// 將對象序列化爲Soap字符串
/// </summary>
/// <param name="obj">待序列化的對象</param>
/// <returns>Soap字符串</returns>
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;
}
/**//// <summary>
/// 將對象序列化爲Soap字符串,並保存到文件中
/// </summary>
/// <param name="obj">待序列化的對象</param>
/// <param name="path">文件路徑</param>
/// <param name="fileMode">文件打開模式</param>
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();
}
}
/**//// <summary>
/// 將對象序列化爲Soap字符串,並保存到文件中
/// </summary>
/// <param name="obj">待序列化的對象</param>
/// <param name="path">文件路徑</param>
public static void SerializeToSoap(object obj, string path)
{
SerializeToSoap(obj, path, FileMode.Create);
}
/**//// <summary>
/// 將對象序列化爲xml字符串
/// </summary>
/// <param name="obj">待序列化的對象</param>
/// <returns>xml字符串</returns>
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;
}
/**//// <summary>
/// 將對象序列化爲xml字符串並保存到文件
/// </summary>
/// <param name="obj">待序列化的對象</param>
/// <param name="path">保存的文件路徑</param>
/// <param name="fileMode">文件打開模式</param>
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);
}
}
1.2
/**//// <summary>
/// 將對象序列化爲xml字符串並保存到文件
/// </summary>
/// <param name="obj">待序列化的對象</param>
/// <param name="path">保存的文件路徑</param>
public static void SerializeToxmlFile(object obj, string path)
{
SerializeToxmlFile(obj, path, FileMode.Create);
}
#endregion
反序列化操作函數#region 反序列化操作函數
/**//// <summary>
/// 從xml文件中反序列化爲Object對象
/// </summary>
/// <param name="type">對象的類型</param>
/// <param name="path">xml文件</param>
/// <returns>反序列化後得到的對象</returns>
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;
}
/**//// <summary>
/// 從xml文件中反序列化爲對象
/// </summary>
/// <param name="type">對象的類型</param>
/// <param name="xml">XML字符串</param>
/// <returns>反序列化後得到的對象</returns>
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;
}
/**//// <summary>
/// 從Soap字符串中反序列化爲對象
/// </summary>
/// <param name="type">對象的類型</param>
/// <param name="soap">soap字符串</param>
/// <returns>反序列化後得到的對象</returns>
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;
}
/**//// <summary>
/// 從二進制字節中反序列化爲對象
/// </summary>
/// <param name="type">對象的類型</param>
/// <param name="bytes">字節數組</param>
/// <returns>反序列化後得到的對象</returns>
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;
}
/**//// <summary>
/// 從二進制文件中反序列化爲對象
/// </summary>
/// <param name="type">對象的類型</param>
/// <param name="path">二進制文件路徑</param>
/// <returns>反序列化後得到的對象</returns>
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
/**//// <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
{
一些基本的符號常量#region 一些基本的符號常量
/**//// <summary>
/// 點符號 .
/// </summary>
public const string Dot = ".";
/**//// <summary>
/// 下劃線 _
/// </summary>
public const string UnderScore = "_";
/**//// <summary>
/// 逗號加空格 ,
/// </summary>
public const string CommaSpace = ", ";
/**//// <summary>
/// 逗號 ,
/// </summary>
public const string Comma = ",";
/**//// <summary>
/// 左括號 (
/// </summary>
public const string OpenParen = "(";
/**//// <summary>
/// 右括號 )
/// </summary>
public const string ClosedParen = ")";
/**//// <summary>
/// 單引號 '
/// </summary>
public const string SingleQuote = "/'";
/**//// <summary>
/// 斜線 /
/// </summary>
public const string Slash = @"/";
#endregion
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);
}