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