程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> step by step 之餐飲管理系統五(Util模塊)------附上篇日志模塊源碼,餐飲管理系統util

step by step 之餐飲管理系統五(Util模塊)------附上篇日志模塊源碼,餐飲管理系統util

編輯:C#入門知識

step by step 之餐飲管理系統五(Util模塊)------附上篇日志模塊源碼,餐飲管理系統util


  這段時間一直在修改日志模塊,現在基本上寫好了,也把注釋什麼的都加上了,昨天郵件發送給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的話就...........

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved