标签:
这段时间一直在修改日志模块,现在基本上写好了,也把注释什么的都加上了,昨天邮件发送给mark的园友一直报失败,老是退回来,真是报歉,如下图所示:
没有办法,只好放这里了,想看源代码的请猛戳这里
如果有什么问题,欢迎跟我交流!
从今天开始写Util模块,这个模块几乎所有的系统项目都需要的,想减少重复代码的编写,就依靠这个模块了.大的模块主要是以下几个方面:
1.加解密
这个我也不多说了,也就是MD5等加密算法:
using System; using System.Security.Cryptography; using System.Text; /// <summary> /// 加解密相关操作类 /// </summary> /// <date>2012-02-20</date> /// <author>xucj</author> public class Cryptography { private const string DefaultKey = "OD"; /// <summary> /// 构造方法 /// </summary> public Cryptography() { } /// <summary> /// 使用缺省密钥字符串加密 /// </summary> /// <param name="original">明文</param> /// <returns>密文</returns> public static string Encrypt(string original) { return Encrypt(original, DefaultKey); } /// <summary> /// 使用缺省密钥解密 /// </summary> /// <param name="original">密文</param> /// <returns>明文</returns> public static string Decrypt(string original) { return Decrypt(original, DefaultKey, System.Text.Encoding.Default); } /// <summary> /// 使用给定密钥解密 /// </summary> /// <param name="original">密文</param> /// <param name="key">密钥</param> /// <returns>明文</returns> public static string Decrypt(string original, string key) { return Decrypt(original, key, System.Text.Encoding.Default); } /// <summary> /// 使用缺省密钥解密,返回指定编码方式明文 /// </summary> /// <param name="original">密文</param> /// <param name="encoding">编码方式</param> /// <returns>明文</returns> public static string Decrypt(string original, Encoding encoding) { return Decrypt(original, DefaultKey, encoding); } /// <summary> /// 使用给定密钥加密 /// </summary> /// <param name="original">原始文字</param> /// <param name="key">密钥</param> /// <returns>密文</returns> public static string Encrypt(string original, string key) { byte[] buff = System.Text.Encoding.Default.GetBytes(original); byte[] kb = System.Text.Encoding.Default.GetBytes(key); return Convert.ToBase64String(Encrypt(buff, kb)); } /// <summary> /// 使用给定密钥解密 /// </summary> /// <param name="encrypted">密文</param> /// <param name="key">密钥</param> /// <param name="encoding">字符编码方案</param> /// <returns>明文</returns> public static string Decrypt(string encrypted, string key, Encoding encoding) { byte[] buff = Convert.FromBase64String(encrypted); byte[] kb = System.Text.Encoding.Default.GetBytes(key); return encoding.GetString(Decrypt(buff, kb)); } /// <summary> /// 生成MD摘要 /// </summary> /// <param name="original">数据源</param> /// <returns>摘要</returns> private static byte[] MakeMD(byte[] original) { MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider(); byte[] keyhash = hashmd.ComputeHash(original); hashmd = null; return keyhash; } /// <summary> /// 使用给定密钥加密 /// </summary> /// <param name="original">明文</param> /// <param name="key">密钥</param> /// <returns>密文</returns> private static byte[] Encrypt(byte[] original, byte[] key) { TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); des.Key = MakeMD(key); des.Mode = CipherMode.ECB; return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length); } /// <summary> /// 使用给定密钥解密数据 /// </summary> /// <param name="encrypted">密文</param> /// <param name="key">密钥</param> /// <returns>明文</returns> private static byte[] Decrypt(byte[] encrypted, byte[] key) { TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); des.Key = MakeMD(key); des.Mode = CipherMode.ECB; return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length); } /// <summary> /// 使用给定密钥加密 /// </summary> /// <param name="original">原始数据</param> /// <returns>密文</returns> private static byte[] Encrypt(byte[] original) { byte[] key = System.Text.Encoding.Default.GetBytes(DefaultKey); return Encrypt(original, key); } /// <summary> /// 使用缺省密钥解密数据 /// </summary> /// <param name="encrypted">密文</param> /// <returns>明文</returns> private static byte[] Decrypt(byte[] encrypted) { byte[] key = System.Text.Encoding.Default.GetBytes(DefaultKey); return Decrypt(encrypted, key); } public static string SimpEncrypt(string str) { StringBuilder asc = new StringBuilder(); for (int i = 0; i < str.Length; i++) { int b = char.Parse(str.Substring(i, 1)) + ‘\x0003‘; asc.Append((char)b); } return asc.ToString(); } public static string SimpUnEncrypt(string str) { StringBuilder asc = new StringBuilder(); for (int i = 0; i < str.Length; i++) { int b = char.Parse(str.Substring(i, 1)) - ‘\x0003‘; asc.Append((char)b); } return asc.ToString(); } }
2.配置文件相关操作
xml,ini配置文件的读写方法:
using System; using System.Text; using System.Runtime.InteropServices; using System.Collections; using System.IO; using System.Collections.Generic; #region 配置文件读写操作类 /// <summary> /// 配置文件读写操作类 /// </summary> /// <date>2012-02-15</date> /// <author>xucj</author> public class IniFileHelper { #region 字段 private string path; #endregion #region 构造函数 public IniFileHelper(string iniFilePath) { path = iniFilePath; } #endregion #region 引用外部库 [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath); #endregion #region 写入INI文件 /// <summary> /// 写入INI文件 /// </summary> /// <param name="section">段名</param> /// <param name="key">键名</param> /// <param name="value">键值</param> public void WriteValue(string section, string key, string value) { WritePrivateProfileString(section, key, value, this.path); } #endregion #region 删除ini配置 /// <summary> /// 删除ini文件下所有段落 /// </summary> public void ClearAllSection() { WriteValue(null, null, null); } /// <summary> /// 删除ini文件下personal段落下的所有键 /// </summary> /// <param name="Section"></param> public void ClearSection(string Section) { WriteValue(Section, null, null); } #endregion #region 读取INI文件 /// <summary> /// 读取INI文件 /// </summary> /// <param name="section"></param> /// <param name="key"></param> /// <returns></returns> public string ReadValue(string section, string key) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(section, key, "", temp, 255, this.path); return temp.ToString(); } private byte[] ReadValues(string section, string key) { byte[] temp = new byte[255]; int i = GetPrivateProfileString(section, key, "", temp, 255, this.path); return temp; } /// <summary> /// 读取ini文件的所有段落名 /// </summary> private string[] ReadValues() { byte[] allSection = ReadValues(null, null); return ByteToString(allSection); } /// <summary> /// 转换byte[]类型为string[]数组类型 /// </summary> /// <param name="sectionByte"></param> /// <returns></returns> private string[] ByteToString(byte[] sectionByte) { ASCIIEncoding ascii = new ASCIIEncoding(); //编码所有key的string类型 string sections = ascii.GetString(sectionByte); //获取key的数组 string[] sectionList = sections.Split(new char[1] { ‘\0‘ }); return sectionList; } /// <summary> /// 读取ini文件的某段落下所有键名 /// </summary> private string[] ReadValues(string section) { byte[] sectionByte = ReadValues(section, null); return ByteToString(sectionByte); } #endregion #region 不使用API方法 private Dictionary<string, string> configInfo = new Dictionary<string,string>(); //* 存放Ini文件配制信息 public int Count { get { return configInfo.Count; } } public string this[string key] { get { if (configInfo.ContainsKey(key)) { return configInfo[key].ToString(); } else { return "No this key-value"; } } } /// <summary> /// 读取指定INI文件中的配置信息 /// </summary> /// <param name="file">配置文件的完整路径名</param> /// <param name="section">配置文件中的节名 "[" + section + "]"形式</param> public IniFileHelper(string file, string section) { string Section = "[" + section + "]"; LoadIniFile(file, Section); } /// <summary> /// 读取ini文件,以HashTable的格式存放 /// </summary> /// <param name="filePath">ini文件路径</param> /// <param name="section">ini读取的段名</param> private void LoadIniFile(string filePath, string section) { try { StreamReader sr = new StreamReader(filePath, System.Text.Encoding.Default); string readLine = null; bool IsReadEnd = false; string[] keys; while ((readLine = sr.ReadLine()) != null) { if (readLine == section) { while ((readLine = sr.ReadLine()) != null) { if(readLine != "") { if (readLine.Substring(0, 1) == "[") { IsReadEnd = true; break; } keys = readLine.Split(‘=‘); configInfo[keys[0].Trim()] = keys[1]; } } } if (IsReadEnd) { break; } } sr.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); configInfo.Clear(); } } #endregion } #endregion
3.序列化
这个主要是可序列化字典:
/// <summary> /// 支持XML序列化的泛型Dictionary类 /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> [XmlRoot("Dictionary")] [Serializable()] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable { #region public SerializableDictionary() : base() { } public SerializableDictionary(IDictionary<TKey, TValue> dictionary) : base(dictionary) { } public SerializableDictionary(IEqualityComparer<TKey> comparer) : base(comparer) { } public SerializableDictionary(int capacity) : base(capacity) { } public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer) : base(capacity, comparer) { } protected SerializableDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion public XmlSchema GetSchema() { throw new NotImplementedException(); } /**/ /// <summary> /// 从对象的XML表示形式生成该对象 /// </summary> /// <param name="reader"></param> public void ReadXml(XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != XmlNodeType.EndElement) { reader.ReadStartElement("Key"); TKey key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("Value"); TValue value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); this.Add(key, value); reader.MoveToContent(); } reader.ReadEndElement(); } /// <summary> /// 将对象转换为其XML表示形式 /// </summary> /// <param name="writer"></param> public void WriteXml(XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("Key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("Value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); } } }
4.字符串
平时用的最多的肯定是字符串了,所以肯定也少了它:
using System; using System.Collections.Generic; using System.Text; public static class StringHelper { /// <summary> /// 将字符串转换为base64编码数据 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ToBase64String(this string str) { byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(str); return Convert.ToBase64String(data); } /// <summary> /// 将base64编码数据转换为字符串 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string FromBase64String(this string str) { byte[] data = Convert.FromBase64String(str); return System.Text.ASCIIEncoding.ASCII.GetString(data); } }
5.汉转英
在系统检索菜品时,要根据拼音,所以这个也不能少,当然这个也有其他的方法,像存储过程或依靠数据库表都可以,下面是纯C#代码的:
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class GetPinYinHelper { /// <summary> /// 获取拼音首字母 /// </summary> /// <param name="strCharacter">要转换的中文汉字字符串</param> /// <returns>拼音缩写</returns> /// <author>xucj</author> /// <date>2011-10-15</date> public static string GetInitialPinYin(string strCharacter) { string tempStr = string.Empty; foreach (char c in strCharacter) { if ((int)c >= 33 && (int)c <= 126 || (int)c == 32) { tempStr += c.ToString(); //字母和符号原样保留、同时空格也保留。 } else { tempStr += GetPYChar(c.ToString()); //累加拼音声母 } } return tempStr; } /// <summary> /// 取单个字符的拼音声母 /// </summary> /// <param name="character">要转换的单个汉字</param> /// <returns>拼音声母</returns> /// <author>xucj</author> /// <date>2011-10-15</date> private static string GetPYChar(string character) { byte[] array = new byte[2]; array = System.Text.Encoding.Default.GetBytes(character); int i = (short)(array[0] - ‘\0‘) * 256 + ((short)(array[1] - ‘\0‘)); if (i < 0xB0A1) return "*"; if (i < 0xB0C5) return "a"; if (i < 0xB2C1) return "b"; if (i < 0xB4EE) return "c"; if (i < 0xB6EA) return "d"; if (i < 0xB7A2) return "e"; if (i < 0xB8C1) return "f"; if (i < 0xB9FE) return "g"; if (i < 0xBBF7) return "h"; if (i < 0xBFA6) return "j"; if (i < 0xC0AC) return "k"; if (i < 0xC2E8) return "l"; if (i < 0xC4C3) return "m"; if (i < 0xC5B6) return "n"; if (i < 0xC5BE) return "o"; if (i < 0xC6DA) return "p"; if (i < 0xC8BB) return "q"; if (i < 0xC8F6) return "r"; if (i < 0xCBFA) return "s"; if (i < 0xCDDA) return "t"; if (i < 0xCEF4) return "w"; if (i < 0xD1B9) return "x"; if (i < 0xD4D1) return "y"; if (i < 0xD7FA) return "z"; return "*"; } }
再加一个获取本机的IP与机器名与MAC地址的方法:
using System.Management; using System.Net; public class NetHelper { /// <summary> /// 取得本机IP /// </summary> public static string GetIP() { string hostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostEntry(hostName); IPAddress[] addr = ipEntry.AddressList; foreach (var item in addr) { if (item.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { continue; } return item.ToString(); } return null; } /// <summary> /// 获取本机MAC地址 /// </summary> /// <returns></returns> public static string GetLocalMACAddress() { string mac = string.Empty; ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration"); ManagementObjectCollection queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { if (mo["IPEnabled"].ToString() == "True") mac = mo["MacAddress"].ToString(); } return mac; } /// <summary> /// 获取本机名 /// </summary> /// <returns></returns> public static string GetHostName() { string hostName = Dns.GetHostName(); return hostName; } }
当然还有很多,等后面需要再慢慢加上来,不相关的就不要了,那样肯定会太杂的,虽然有一些很好很优雅的公共代码,但是如果系统用不上,那也浪费了,那就让它保存在备用库里吧。这些代码来源还是广泛的,所以没有太多好写的,下次写数据库访问模块了。主要实现ORM这个功能,因为通用数据库访问模块网络上也是很多的,时间上应该不会占用太多时间,但是用ORM的话还是能够减少写SQL语句的时间,所以写一个带ORM功能的数据库访问模块。能不用写SQL的地方就靠它了。
当然还有其他代码,就不贴这里了,有需要的就mark下,没人mark的话就...........
标签:
原文地址:http://www.cnblogs.com/cang/p/4249045.html