/******************************************************************************* * Copyright(c) 2014 DongkeSoft All rights reserved. / Confidential * 类的信息: * 1.程序名称:Utility.cs * 2.功能描述:系统各种常用函数和方法类 * 3.函数/方法列表: * A.IsNull:判断空值 * B.EnableFormCloseBox:设定窗体的关闭按钮是否有效 * C.IsValidDate:判断是否是合法的日期 * D.ChineseToPinyinCap:根据输入汉字,转化成汉字首字母串 * 编辑履历: * 作者 日期 版本 修改内容 * 欧阳涛 2012/06/07 1.00 新建 * 王文君 2012/07/10 1.00 修改 添加IsUnique方法 * 欧阳涛 2012/07/19 1.00 增加了GetBytesByFilePath()方法, * 根据文件路径返回文件字节流 *******************************************************************************/ using System; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using Dongke.IBOSS.PRD.Basics.BaseResources; namespace Dongke.IBOSS.PRD.Basics.Library { /// /// 系统各种常用函数和方法类 /// public static class Utility { #region IsDirty public static bool IsDirty(DataSet dataSet) { if (dataSet == null) { return false; } foreach (DataTable table in dataSet.Tables) { foreach (DataRow row in table.Rows) { row.EndEdit(); } } DataSet changes = dataSet.GetChanges(); if (changes == null) { return false; } foreach (DataTable table in changes.Tables) { if (IsDirty(table)) { return true; } } return false; } public static bool IsDirty(DataTable table) { if (table == null) { return false; } if (table.GetChanges(DataRowState.Added) != null) { return true; } if (table.GetChanges(DataRowState.Deleted) != null) { return true; } DataTable changes = table.GetChanges(DataRowState.Modified); if (changes != null) { foreach (DataRow row in changes.Rows) { if (IsDirty(row)) { return true; } } } return false; } public static bool IsDirty(DataRow row) { if (row == null) { return false; } if (row.RowState == DataRowState.Added || row.RowState == DataRowState.Deleted) { return true; } if (row.RowState == DataRowState.Modified) { foreach (DataColumn column in row.Table.Columns) { if (column.ReadOnly) { continue; } if (!Utility.Compare(row[column, DataRowVersion.Original], row[column, DataRowVersion.Current])) { return true; } } } return false; } #endregion #region 申明API函数 /// /// 写入INI文件 /// /// 节点名称[如[TypeName]] /// 键 /// 值 /// 文件路径 /// [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filepath); /// /// 读取INI文件 /// /// 节点名称 /// 键 /// 值 /// stringbulider对象 /// 字节大小 /// 文件路径 /// [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath); #endregion #region 成员变量 // 获取屏幕DPI用 private static readonly Control _control; // 图形 private static readonly Graphics _graphics; /// /// 毫米和像素的转换系数 /// private const float MILLIMETER_PER_INCH = 25.4f; /// /// 磅和像素的转换系数 /// private const float POINT_PER_INCH = 72f; /// /// 屏幕的DPI /// private static float SCREEN_DPI; #endregion #region 构造函数 static Utility() { _control = new Control(); _graphics = _control.CreateGraphics(); SCREEN_DPI = _graphics.DpiX; } #endregion #region FindWindow() [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); #endregion #region WakeupWindow() public static bool WakeupWindow(IntPtr hWnd) { if (hWnd == System.IntPtr.Zero) { return false; } if (Win32.IsIconic(hWnd) || !Win32.IsWindowVisible(hWnd)) { Win32.ShowWindowAsync(hWnd, Win32.SW_RESTORE); } Win32.SetForegroundWindow(hWnd); return true; } #endregion #region 基本共通函数 /// /// 空值判断 /// /// 判断对象 /// /// True:是空值 /// False:不是空值 /// public static bool IsNull(object value) { if (value == null || value == DBNull.Value) { return true; } return false; } /// /// 过滤sql语句中非法的字符,并替换 /// /// 替换前的sql语句 /// 替换后的sql语句字符 public static string SelectFilterLike(string value) { if (string.IsNullOrEmpty(value)) { return string.Empty; } return value.Replace(@"'", @"''").Replace(@"[", @"[[]") .Replace(@"_", @"[_]").Replace(@"%", @"[%]").Replace(@"*", @"[*]"); } /// /// 控制窗体的关闭按钮是否能用 /// /// 窗体句柄 /// True:可用 False:不可用 /// /// 设置成功与否 /// public static bool EnableFormCloseBox(IntPtr hWnd, bool bEnable) { if (hWnd == System.IntPtr.Zero) { return false; } IntPtr hMenu = Win32.GetSystemMenu(hWnd, 0); if (hMenu == System.IntPtr.Zero) { return false; } if (bEnable) { Win32.EnableMenuItem(hMenu, Win32.SC_CLOSE, Win32.MF_ENABLED); } else { Win32.EnableMenuItem(hMenu, Win32.SC_CLOSE, Win32.MF_DISABLED | Win32.MF_GRAYED); } return true; } /// /// 判断是否是正确的日期格式 /// /// 被判断的日期 /// 返回被格式化的日期 /// /// True:日期格式 /// False:不是日期格式 /// public static bool IsValidDate(string strDateTime, out DateTime? dateTime) { DateTime returnDatetime; if (DateTime.TryParse(strDateTime, out returnDatetime)) { dateTime = returnDatetime; return true; } else { dateTime = null; return false; } } /// /// 取得显示顺序的最大值 /// /// 数据表 /// 列名 /// /// 该数据表里的最大显示顺序 /// public static int GetMaxValue(DataTable table, string maxValName) { if (table == null) { return -1; } if (table.Columns.Contains(maxValName)) { DataRow[] rows = table.Select("0 <= " + maxValName, maxValName + " DESC"); if (rows == null || rows.Length == 0) { return -1; } object value = rows[0][maxValName]; if (value == null) { return -1; } int maxValue = int.Parse(value.ToString()); if (maxValue == short.MaxValue) { maxValue--; } return maxValue; } else { return -1; //DataRow[] rows = table.Select("0 <= " + maxValName,maxValName + "DESC"); //object value = rows[0][maxValName]; //int maxValue = int.Parse(value.ToString()); //return maxValue; } } /// /// 取得数据表里的最大编码值 /// /// 数据表 /// 列名 /// 该数据表里的最大编码值(string类型) /// /// 2012.07.10 余再伟 创建 /// public static string GetStringMaxValue(DataTable table, string maxValName) { // 表为空时候直接返回空值 if (table == null) { return string.Empty; } // 表中包含该列名的时候返回该数据表的最大编码值 if (table.Columns.Contains(maxValName)) { DataRow[] rows = table.Select("'0' <= " + maxValName, maxValName + " DESC"); if (rows == null || rows.Length == 0) { return string.Empty; } object value = rows[0][maxValName]; if (value == null) { return string.Empty; } string maxValue = value.ToString(); return maxValue; } else { return string.Empty; } } /// /// 校验值是否重复 /// /// 当前Column的值 /// 当前行的行号 /// 所在的DataGridView /// 比较值 /// 是否存在 public static bool IsUnique(string curCellValue, int curRow, DataGridView dataGridView, string uniqueValue) { foreach (DataGridViewRow rowItem in dataGridView.Rows) { if (rowItem.Index == curRow) { continue; } // 字典名称 if (rowItem.Cells[uniqueValue].Value != null) { if (rowItem.Cells[uniqueValue].Value.ToString().Trim(). Equals(curCellValue.Trim())) { return false; } } } return true; } /// /// 根据输入的汉字,返回所有汉字拼音的首字母串 /// /// 输入的汉字 /// 汉字拼音的首字母串 public static string ChineseToPinyinCap(string chineseString) { string pinyinCapString = ""; // 转换后的拼音首字母字符串 // 每个汉字存储需要两个字节 byte[] ZW = new byte[2]; long ChineseStr_int; string CharStr; string ChinaStr = ""; chineseString = ToDBC(chineseString); for (int i = 0; i <= chineseString.Length - 1; i++) { // 取出一个汉字 CharStr = chineseString.Substring(i, 1).ToString(); // 得到汉字的字节表示 ZW = System.Text.Encoding.Default.GetBytes(CharStr); // 得到汉字符的字节数组 if (ZW.Length == 2) { int i1 = (short)(ZW[0]); int i2 = (short)(ZW[1]); ChineseStr_int = i1 * 256 + i2; #region 参数 // table of the constant list // 'A';      //45217..45252 // 'B';      //45253..45760 // 'C';      //45761..46317 // 'D';      //46318..46825 // 'E';      //46826..47009 // 'F';      //47010..47296 // 'G';      //47297..47613 // 'H';      //47614..48118 // 'J';      //48119..49061 // 'K';      //49062..49323 // 'L';      //49324..49895 // 'M';      //49896..50370 // 'N';      //50371..50613 // 'O';      //50614..50621 // 'P';      //50622..50905 // 'Q';      //50906..51386 // 'R';      //51387..51445 // 'S';      //51446..52217 // 'T';      //52218..52697 //没有U,V // 'W';      //52698..52979 // 'X';      //52980..53640 // 'Y';      //53689..54480 // 'Z';      //54481..55289 #endregion if ((ChineseStr_int >= 45217) && (ChineseStr_int <= 45252)) { ChinaStr = "A"; } else if ((ChineseStr_int >= 45253) && (ChineseStr_int <= 45760)) { ChinaStr = "B"; } else if ((ChineseStr_int >= 45761) && (ChineseStr_int <= 46317)) { ChinaStr = "C"; } else if ((ChineseStr_int >= 46318) && (ChineseStr_int <= 46825)) { ChinaStr = "D"; } else if ((ChineseStr_int >= 46826) && (ChineseStr_int <= 47009)) { ChinaStr = "E"; } else if ((ChineseStr_int >= 47010) && (ChineseStr_int <= 47296)) { ChinaStr = "F"; } else if ((ChineseStr_int >= 47297) && (ChineseStr_int <= 47613)) { ChinaStr = "G"; } else if ((ChineseStr_int >= 47614) && (ChineseStr_int <= 48118)) { ChinaStr = "H"; } else if ((ChineseStr_int >= 48119) && (ChineseStr_int <= 49061)) { ChinaStr = "J"; } else if ((ChineseStr_int >= 49062) && (ChineseStr_int <= 49323)) { ChinaStr = "K"; } else if ((ChineseStr_int >= 49324) && (ChineseStr_int <= 49895)) { ChinaStr = "L"; } else if ((ChineseStr_int >= 49896) && (ChineseStr_int <= 50370)) { ChinaStr = "M"; } else if ((ChineseStr_int >= 50371) && (ChineseStr_int <= 50613)) { ChinaStr = "N"; } else if ((ChineseStr_int >= 50614) && (ChineseStr_int <= 50621)) { ChinaStr = "O"; } else if ((ChineseStr_int >= 50622) && (ChineseStr_int <= 50905)) { ChinaStr = "P"; } else if ((ChineseStr_int >= 50906) && (ChineseStr_int <= 51386)) { ChinaStr = "Q"; } else if ((ChineseStr_int >= 51387) && (ChineseStr_int <= 51445)) { ChinaStr = "R"; } else if ((ChineseStr_int >= 51446) && (ChineseStr_int <= 52217)) { ChinaStr = "S"; } else if ((ChineseStr_int >= 52218) && (ChineseStr_int <= 52697)) { ChinaStr = "T"; } else if ((ChineseStr_int >= 52698) && (ChineseStr_int <= 52979)) { ChinaStr = "W"; } else if ((ChineseStr_int >= 52980) && (ChineseStr_int <= 53640)) { ChinaStr = "X"; } else if ((ChineseStr_int >= 53689) && (ChineseStr_int <= 54480)) { ChinaStr = "Y"; } else if ((ChineseStr_int >= 54481) && (ChineseStr_int <= 55289)) { ChinaStr = "Z"; } else { ChinaStr = CharStr; } pinyinCapString = pinyinCapString + ChinaStr; } else { pinyinCapString = pinyinCapString + CharStr.ToUpper(); } } return pinyinCapString; } #endregion #region 半角全角转换 /// /// 转半角的函数(DBC) /// 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 /// 全角空格为12288,半角空格为32 /// /// 任意字符串 /// 半角字符串 public static string ToDBC(string inputString) { char[] c = inputString.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == 12288) { c[i] = (char)32; continue; } if (c[i] > 65280 && c[i] < 65375) { c[i] = (char)(c[i] - 65248); } } return new String(c); } /// /// 转全角的函数(SBC) /// 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 /// 全角空格为12288,半角空格为32 /// /// 任意字符串 /// 全角字符串 public static string ToSBC(string inputString) { // 半角转全角: char[] c = inputString.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == 32) { c[i] = (char)12288; continue; } if (c[i] < 127) c[i] = (char)(c[i] + 65248); } return new String(c); } #endregion #region 正则判断数据合法性 /// /// 验证邮箱格式 /// /// 要验证的邮箱地址 /// /// True:邮箱格式正确 /// False:邮箱格式错误 /// public static bool IsValidEmail(string email) { if (!Regex.IsMatch(email, @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$")) { return false; } else { return true; } } ///// ///// 验证身份证输入是否正确 ///// ///// 要验证的身份证号 ///// ///// True:身份证格式正确 ///// False:身份证格式错误 ///// //public static bool IsIDcard(string IdCard) //{ // bool result = false; // if (IdCard.Length <= 15) // { // result = Regex.IsMatch(IdCard, Constant.IDCARD_STRING15); // } // else // { // result = Regex.IsMatch(IdCard, Constant.IDCARD_STRING); // } // return result; //} /// /// 判断身份证号是否合法(对外部公开) /// /// 身份证号(旧/新) /// false:不合法 true:合法 public static bool IsIDcard(string strCardID) { strCardID = strCardID.ToLower(); // 验证身份证的位数 string strRegex = @"(\d{15}$)|(\d{17}(\d|x)$)"; if (!Regex.IsMatch(strCardID, strRegex)) { return false; } // 身份证数据有效性验证 string strNewCardID = strCardID; if (strCardID.Length == 15) { strNewCardID = Convert15To18(strCardID); } if (!CheckCardIDInfo(strNewCardID)) { return false; } return true; } /// /// 判断身份证号是否合法 /// /// 新身份证号 /// false:不合法 true:合法 private static bool CheckCardIDInfo(string strCardID) { string[] aCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津 ", "河北", "山西", "内蒙古", null, null, null, null, null, "辽宁", "吉林", "黑龙江", null, null, null, null, null, null, null, "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", null, null, null, "河南", "湖北", "湖南", "广东", "广西", "海南", null, null, null, "重庆", "四川", "贵州", "云南", "西藏", null, null, null, null, null, null, "陕西", "甘肃", "青海", "宁夏", "新疆", null, null, null, null, null, "台湾", null, null, null, null, null, null, null, null, null, "香港", "澳门", null, null, null, null, null, null, null, null, "国外" }; strCardID = strCardID.ToLower(); strCardID = strCardID.Replace("x", "a"); try { if (aCity[int.Parse(strCardID.Substring(0, 2))] == null) { return false; } DateTime.Parse(strCardID.Substring(6, 4) + "-" + strCardID.Substring(10, 2) + "-" + strCardID.Substring(12, 2)); } catch { return false; } double iSum = 0; for (int i = 17; i >= 0; i--) { iSum += (System.Math.Pow(2, i) % 11) * int.Parse(strCardID[17 - i].ToString(), System.Globalization.NumberStyles.HexNumber); } if (iSum % 11 != 1) { return false; } return true; } /// /// 从老身份证升位到新身份证 /// /// 老身份证号码 /// 新身份证号码 private static string Convert15To18(string strCardID) { int intN = 0; // 加权因子常数 int[] intW = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 校验码常数 string strLastCode = "10X98765432"; // 新身份证号 string strNewCardID; strNewCardID = strCardID.Substring(0, 6); // 填在第6位及第7位上填上‘1’,‘9’两个数字 strNewCardID += "19"; strNewCardID += strCardID.Substring(6, 9); // 进行加权求和 for (int i = 0; i < 17; i++) { intN += int.Parse(strNewCardID.Substring(i, 1)) * intW[i]; } // 取模运算,得到模值 int intY = intN % 11; // 从strLastCode中取得以模为索引号的值,加到身份证的最后一位,即为新身份证号。 strNewCardID += strLastCode.Substring(intY, 1); return strNewCardID; } /// /// 验证车牌号输入是否正确 /// /// 要验证的车牌号 /// /// True:车牌号格式正确 /// False:车牌号格式错误 /// public static bool IsPlateNumber(string PlateNumber) { return Regex.IsMatch(PlateNumber, Constant.REGEX_PLATENUMBER_STRING); } /// /// 验证车架号输入是否正确 /// /// 要验证的车架号 /// /// True:车架号格式正确 /// False:车架号格式错误 /// public static bool IsVehicleNumber(string VehicleNumber) { return Regex.IsMatch(VehicleNumber, Constant.REGEX_VEHICLENUM_STRING); } /// /// 验证公司网址输入格式是否正确 /// /// 要验证的网址 /// True:网址格式正确 /// False:网址格式错误 /// public static bool IsValidHttp(string http) { if (!Regex.IsMatch(http, Constant.REGEX_HTTP_STRING)) { return false; } else { return true; } } /// /// 验证输入字符串是否为数字类型(包括带小数的数字) /// /// 要验证的字符串 /// /// True:字符串是数字 /// False:字符串不是数字 /// public static bool IsNumeric(string value) { return System.Text.RegularExpressions.Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$"); } /// /// 验证输入字符串是否为合法时间(HH:mm或者HH:mm:ss) /// /// 要验证的字符串 /// /// True:字符串是合法时间(HH:mm或者HH:mm:ss) /// False:字符串不是合法时间(HH:mm或者HH:mm:ss) /// public static bool IsTime(string value) { return System.Text.RegularExpressions.Regex.IsMatch(value, @"^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$"); } /// /// 验证输入字符串是否为合法日期(yyyy-MM-dd) /// /// 要验证的字符串 /// /// True:字符串是合法日期(yyyy-MM-dd) /// False:字符串不是合法日期(yyyy-MM-dd) /// public static bool IsDate(string value) { return System.Text.RegularExpressions.Regex.IsMatch(value, @"^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$"); } #endregion #region 二进制与文件之间转换 /// /// 将文件转换成字节流 /// /// 文件的绝对路径 /// /// 文件的字节流 /// public static byte[] GetBytesByFilePath(string filePath) { // 传入的值非法的情况下,返回NULL if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) { return null; } // 读取文件到字节流中 FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader binaryReader = new BinaryReader(fileStream); byte[] fileBytes = binaryReader.ReadBytes((int)fileStream.Length); fileStream.Flush(); fileStream.Close(); return fileBytes; } /// /// 将二进制转换成文件 /// /// 文件存放的全路径 /// 二进制文件 /// /// True:保存成功 /// False:保存失败 /// public static bool BinaryToFile(string filePath, byte[] fileByte) { if (string.IsNullOrEmpty(filePath) || fileByte == null) { return false; } try { FileStream filestream = File.Create(filePath, fileByte.Length); filestream.Write(fileByte, 0, fileByte.Length); return true; } catch (Exception ex) { throw ex; } } #endregion #region 图片与二进制之间转换 /// /// 将图片文件序列化成二进制流 /// /// 文件路径 /// 二进制流文件 public static MemoryStream ImageToBinary(string imagePath) { if (string.IsNullOrEmpty(imagePath) || !File.Exists(imagePath)) { return null; } try { // 将图片文件序列化成二进制流文件 Image image = new Bitmap(imagePath); MemoryStream memorystream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memorystream, image); return memorystream; } catch (Exception ex) { throw ex; } } /// /// 将二进制流反序列化成图片文件 /// /// 二进制流文件 /// 图片文件 public static Image StreamToImage(MemoryStream memoryStream) { if (memoryStream == null) { return null; } try { // 将流文件反序列化成图片文件 memoryStream.Position = 0; BinaryFormatter formatter = new BinaryFormatter(); return (Image)formatter.Deserialize(memoryStream); } catch (Exception ex) { throw ex; } } /// /// 将二进制转换成图片文件 /// /// 二进制 /// image public static Image BinaryToImage(byte[] imageBinary) { if (imageBinary == null) { return null; } try { MemoryStream memoryStream = new MemoryStream(imageBinary); return Image.FromStream(memoryStream); } catch (Exception ex) { throw ex; } } /// /// 根据Image对象转换成二进制 /// /// image对象 /// /// 二进制数组 /// public static byte[] ImageToByteArray(Image image) { if (image == null) { return null; } try { MemoryStream memoryStream = new MemoryStream(); image.Save(memoryStream, ImageFormat.Jpeg); return memoryStream.ToArray(); } catch (Exception ex) { throw ex; } } #endregion #region Compare比较函数 [Flags] public enum CompareType { None = 0, // DBNull.Value值与null值视为同一值 DBNullAsNull = 1, // string.Empty值null值视为同一值 EmptyAsNull = 2, // 全部都视为同一值 All = DBNullAsNull | EmptyAsNull } /// /// 两个值比较函数 /// /// 值1 /// 值2 /// /// True:两个值相等的情况 /// False:两个值相等的以外情况 /// public static bool Compare(object value1, object value2) { return Compare(value1, value2, CompareType.None); } /// /// 两个值比较函数 /// /// 值1 /// 值2 /// 比较方式 /// /// True:两个值相等的情况 /// False:两个值相等的以外情况 /// public static bool Compare(object value1, object value2, CompareType compareFlag) { bool isNull1 = (value1 == null); bool isNull2 = (value2 == null); if ((compareFlag & CompareType.DBNullAsNull) == CompareType.DBNullAsNull) { if (value1 == DBNull.Value) { isNull1 = true; } if (value2 == DBNull.Value) { isNull2 = true; } } if ((compareFlag & CompareType.EmptyAsNull) == CompareType.EmptyAsNull) { if (string.Empty.Equals(value1)) { isNull1 = true; } if (string.Empty.Equals(value2)) { isNull2 = true; } } if (isNull1 && isNull2) { return true; } if (value1 == null || value2 == null) { return false; } else { return CompareSub(value1, value2); } } /// /// 两个值比较函数 /// /// 值1 /// 值2 /// /// True:两个值相等的情况 /// False:两个值相等的以外情况 /// private static bool CompareSub(object value1, object value2) { // 数据类型不一样的情况下,返回false if (value1.GetType().Equals(value2.GetType()) == false) { return false; } // 枚举比较的情况,不能使用Equals,需单独写方法比较 if (value1 is System.Collections.IEnumerable && value2 is System.Collections.IEnumerable) { return CompareSub((System.Collections.IEnumerable)value1, (System.Collections.IEnumerable)value2); } else { return value1.Equals(value2); } } /// /// 两个枚举类型的比较 /// /// 值1 /// 值2 /// /// True:两个值相等的情况 /// False:两个值相等的以外情况 /// private static bool CompareSub(System.Collections.IEnumerable enumerable1, System.Collections.IEnumerable enumerable2) { System.Collections.IEnumerator e1 = enumerable1.GetEnumerator(); System.Collections.IEnumerator e2 = enumerable2.GetEnumerator(); while (e1.MoveNext()) { if (!e2.MoveNext()) { return false; } if (!e1.Current.Equals(e2.Current)) { return false; } } return !e2.MoveNext(); } #endregion #region 校验数字 /// /// 校验数据是否符合要求 /// /// 待验证的参数 /// 待验证的参数名称 /// 校验的种类 /// 错误信息 /// /// 2012.10.8 周兴 新建 /// public static string IsValidNumber(string number, string numberName, byte type) { try { // 如果第一位是-,表面可能是负号,去掉之后进行校验 if (!string.IsNullOrEmpty(number)) { if (number.IndexOf("-") == 0) { number = number.Substring(1); } } string errorMsg = string.Empty; string maxNumber = string.Empty; string regex = string.Empty; // 验证Numeric(16,6) if (type == 1) { regex = @"^(0|([1-9][0-9]{0,9}))(\.[0-9]{0,6})?$"; maxNumber = "9999999999.999999"; } // 验证Numeric(14,6) else if (type == 2) { regex = @"^(0|([1-9][0-9]{0,7}))(\.[0-9]{0,6})?$"; maxNumber = "99999999.999999"; } // 验证Numeric(12,6) else if (type == 3) { regex = @"^(0|([1-9][0-9]{0,5}))(\.[0-9]{0,6})?$"; maxNumber = "999999.999999"; } // 验证Numeric(5,2) else if (type == 4) { regex = @"^(0|([1-9][0-9]{0,2}))(\.[0-9]{0,2})?$"; maxNumber = "999.99"; } // 验证Numeric(5,2)(采购返利方式的返点率) else if (type == 5) { regex = @"^((0|([1-9][0-9]{0,1}))(\.[0-9]{0,2})?|(100(\.0{0,2})?))$"; maxNumber = "100.00"; } // 验证Numeric(6,2)(系统参数舍零金额限制最大值1000.00) else if (type == 6) { regex = @"^((0|([1-9][0-9]{0,2}))(\.[0-9]{0,2})?|(1000(\.0{0,2})?))$"; maxNumber = "1000.00"; } // 验证Numeric(12,2)(任务策略中任务金额限制) else if (type == 7) { regex = @"^(0|([1-9][0-9]{0,9}))(\.[0-9]{0,2})?$"; maxNumber = "9999999999.99"; } // 验证Numeric(6,2)(商品编码中费用分摊系数) else if (type == 8) { regex = @"^(0|([1-9][0-9]{0,3}))(\.[0-9]{0,2})?$"; maxNumber = "9999.99"; } // 验证Numeric(9,2)(CA员工业绩岗位考核工资基数) else if (type == 9) { regex = @"^(0|([1-9][0-9]{0,6}))(\.[0-9]{0,2})?$"; maxNumber = "9999999.99"; } // 验证Numeric(3,2)(CA员工业绩提成比率) else if (type == 10) { regex = @"^(0|([0-9]))(\.[0-9]{0,2})?$"; maxNumber = "9.99"; } // 验证Numeric(3,1)(CB员工业绩提成比率) else if (type == 11) { regex = @"^(0|([1-9][0-9]{0,1}))(\.[0-9]{0,1})?$"; maxNumber = "99.9"; } // 验证Numeric(7,2)(店长提成策略出库净额递增额) else if (type == 12) { regex = @"^(0|([1-9][0-9]{0,4}))(\.[0-9]{0,2})?$"; maxNumber = "99999.99"; } if (!Regex.IsMatch(number, regex)) { //errorMsg = string.Format(Messages.MESSAGE_W004, numberName, maxNumber); } return errorMsg; } catch (Exception ex) { throw ex; } } #endregion #region 校验电话格式 /// /// 校验电话是否符合格式 /// /// /// public static bool IsValidTelephone(string telephone) { try { /** * 手机号码 * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188 * 联通:130,131,132,152,155,156,185,186 * 电信:133,1349,153,180,181,189 */ string mobile = "^1(3[0-9]|5[0-35-9]|8[012345-9])\\d{8}$"; /** * 大陆地区固话及小灵通 区号和电话之间没有- * 区号:010,020,021,022,023,024,025,027,028,029 * 号码:七位或八位 */ string phs = "^0(10|2[0-5789]|\\d{3})\\d{7,8}$"; if (!Regex.IsMatch(telephone, mobile) && !Regex.IsMatch(telephone, phs)) { return false; } return true; } catch (Exception ex) { throw ex; } } #endregion #region 验证规格是否符合计算面积格式 /// /// 验证规格是否符合计算面积格式 /// /// 规格 /// public static bool IsValidAcreage(string specification) { try { string regex = @"^\d+\*\d+$"; if (Regex.IsMatch(specification, regex)) { return true; } return false; } catch (Exception ex) { throw ex; } } #endregion #region 验证规格是否符合计算体积格式 /// /// 验证规格是否符合计算体积格式 /// /// 规格 /// public static bool IsValidVolume(string specification) { try { string regex = @"^\d+\*\d+\*\d+$"; if (Regex.IsMatch(specification, regex)) { return true; } return false; } catch (Exception ex) { throw ex; } } #endregion #region 长度与像素之间转换 /// /// 1/100 英寸转换为毫米 /// /// /// 表示倍率 100% /// /// 1/100 英寸 /// 毫米 public static float Inch100ToMillimeter(int inch100) { float mm = inch100 * MILLIMETER_PER_INCH / 100; return mm; } /// /// 1/100 英寸转换为毫米 /// /// /// 表示倍率 100% /// /// 1/100 英寸 /// 毫米 public static float Inch100ToMillimeter(float inch100) { float mm = inch100 * MILLIMETER_PER_INCH / 100; return mm; } /// /// 磅转换为毫米 /// /// /// 表示倍率 100% /// /// 磅 /// 毫米 public static float PointToMillimeter(float point) { float mm = point / POINT_PER_INCH * MILLIMETER_PER_INCH; return mm; } /// /// 磅转换为像素 /// /// /// 表示倍率 100% /// /// 磅 /// 像素 public static int PointToPixel(float point) { decimal pixel = System.Convert.ToDecimal(point) / System.Convert.ToDecimal(POINT_PER_INCH) * System.Convert.ToDecimal(SCREEN_DPI); return System.Convert.ToInt32(Math.Round(pixel, 0)); } /// /// 毫米转换为1/100 英寸 /// /// /// 表示倍率 100% /// /// 毫米 /// 1/100 英寸 public static int MillimeterToInch100(float mm) { float inch100 = mm / MILLIMETER_PER_INCH * 100; return System.Convert.ToInt32(Math.Round(inch100, 0)); } /// /// 毫米转换为1/100 英寸 /// /// /// 表示倍率 100% /// /// 毫米 /// 1/100 英寸 public static float MillimeterToInch100Single(float mm) { float inch100 = mm / MILLIMETER_PER_INCH * 100; return inch100; } /// /// 毫米转换为像素 /// /// /// 表示倍率 100% /// /// 毫米 /// 像素 public static int MillimeterToPixel(float mm) { decimal pixel = System.Convert.ToDecimal(mm) / System.Convert.ToDecimal(MILLIMETER_PER_INCH) * System.Convert.ToDecimal(SCREEN_DPI); return System.Convert.ToInt32(Math.Round(pixel, 0)); } /// /// 毫米转换为像素 /// /// 毫米 /// 表示倍率% /// 像素 public static int MillimeterToPixel(float mm, int paperZoom) { if (0 < paperZoom) { decimal pixel = System.Convert.ToDecimal(mm) / System.Convert.ToDecimal(MILLIMETER_PER_INCH) * System.Convert.ToDecimal(SCREEN_DPI) * System.Convert.ToDecimal(paperZoom) / 100m; return System.Convert.ToInt32(Math.Round(pixel, 0)); } else { return 0; } } /// /// 毫米转换为像素 /// /// 毫米 /// 表示倍率% /// 像素 public static int MillimeterToPixel(float mm, double paperZoom) { if (0 < paperZoom) { decimal pixel = System.Convert.ToDecimal(mm) / System.Convert.ToDecimal(MILLIMETER_PER_INCH) * System.Convert.ToDecimal(SCREEN_DPI) * System.Convert.ToDecimal(paperZoom); return System.Convert.ToInt32(Math.Round(pixel, 0)); } else { return 0; } } /// /// 毫米转换为像素 /// /// 毫米 /// 表示倍率% /// 像素 public static float MillimeterToPixelSingle(float mm, int paperZoom) { if (0 < paperZoom) { decimal pixel = System.Convert.ToDecimal(mm) / System.Convert.ToDecimal(MILLIMETER_PER_INCH) * System.Convert.ToDecimal(SCREEN_DPI) * System.Convert.ToDecimal(paperZoom) / 100m; return System.Convert.ToSingle(pixel); } else { return 0f; } } /// /// 像素转换为毫米 /// /// /// 表示倍率 100% /// /// 像素 /// 毫米 public static float PixelToMillimeter(int pixel) { decimal mm = System.Convert.ToDecimal(pixel) * System.Convert.ToDecimal(MILLIMETER_PER_INCH) / System.Convert.ToDecimal(SCREEN_DPI); return System.Convert.ToSingle(mm); } /// /// 像素转换为毫米 /// /// 像素 /// 表示倍率% /// 毫米 public static float PixelToMillimeter(int pixel, int paperZoom) { if (0 < paperZoom) { decimal mm = System.Convert.ToDecimal(pixel) * System.Convert.ToDecimal(MILLIMETER_PER_INCH) / System.Convert.ToDecimal(SCREEN_DPI) / System.Convert.ToDecimal(paperZoom) * 100m; return System.Convert.ToSingle(mm); } else { return 0f; } } /// /// 像素转换为毫米 /// /// 像素 /// 表示倍率% /// DPI /// 毫米 public static float PixelToMillimeter(int pixel, int paperZoom, float dpi) { if (0 < paperZoom) { decimal mm = System.Convert.ToDecimal(pixel) * System.Convert.ToDecimal(MILLIMETER_PER_INCH) / System.Convert.ToDecimal(dpi) / System.Convert.ToDecimal(paperZoom) * 100m; return System.Convert.ToSingle(mm); } else { return 0f; } } /// /// 像素转换为毫米 /// /// 像素 /// 表示倍率% /// 毫米 public static float PixelToMillimeter(int pixel, double paperZoom) { if (0 < paperZoom) { decimal mm = System.Convert.ToDecimal(pixel) * System.Convert.ToDecimal(MILLIMETER_PER_INCH) / System.Convert.ToDecimal(SCREEN_DPI) / System.Convert.ToDecimal(paperZoom); return System.Convert.ToSingle(mm); } else { return 0f; } } /// /// 截断到指定的精度。 /// /// 截断的目标 /// 精度 /// 截断后的数值 public static float Truncate(float value, int digits) { double v = Math.Pow(10, digits); return Convert.ToSingle(Math.Truncate((double)value * v) / v); } /// /// 截断到指定的精度。 /// /// 截断的目标 /// 精度 /// 截断后的数值 public static decimal Truncate(decimal value, int digits) { decimal v = (decimal)Math.Pow(10, digits); return Math.Truncate(value * v) / v; } #endregion #region 字符转成条码图片 /// /// 根据条码生成条码图片 /// /// 条码字符 /// 条码图片的Stream public static Image GetCode39Image(string barcode) { try { byte[] bytes = GetCode39Byte(barcode); MemoryStream ms = new MemoryStream(bytes); Image returnImage = Image.FromStream(ms); return returnImage; } catch (Exception ex) { throw ex; } } /// /// 根据条码生成条码图片 /// /// 条码字符 /// 条码图片的Stream public static Stream GetCode39Stream(string barcode) { try { byte[] bytes = GetCode39Byte(barcode); Stream stream = new MemoryStream(bytes); return stream; } catch (Exception ex) { throw ex; } } /// /// 根据条码生成条码图片 /// /// 条码字符 /// 条码图片的byte[] public static byte[] GetCode39Byte(string barcode) { try { MemoryStream memoryStream = new MemoryStream(); Bitmap barcodeBitmap = GetCode39Bitmap(barcode); barcodeBitmap.Save(memoryStream, ImageFormat.Png); byte[] byteImage = new Byte[memoryStream.Length]; byteImage = memoryStream.ToArray(); return byteImage; } catch (Exception ex) { throw ex; } } /// /// 根据条码生成条码图片 /// /// 条码字符 /// /// Bitmap条码图片 /// public static Bitmap GetCode39Bitmap(string barcode) { try { int x = 5; // 左边界 int y = 0; // 上边界 int WidLength = 2; // 粗BarCode长度 int NarrowLength = 1; // 细BarCode长度 int BarCodeHeight = 50; // BarCode高度 int intSourceLength = barcode.Length; string strEncode = "010010100"; // 编码字符串·初始值为 起始符号 * string AlphaBet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*"; // Code39的字母 string[] Code39 = //Code39的各字母对应码 { /**//* 0 */ "000110100", /**//* 1 */ "100100001", /**//* 2 */ "001100001", /**//* 3 */ "101100000", /**//* 4 */ "000110001", /**//* 5 */ "100110000", /**//* 6 */ "001110000", /**//* 7 */ "000100101", /**//* 8 */ "100100100", /**//* 9 */ "001100100", /**//* A */ "100001001", /**//* B */ "001001001", /**//* C */ "101001000", /**//* D */ "000011001", /**//* E */ "100011000", /**//* F */ "001011000", /**//* G */ "000001101", /**//* H */ "100001100", /**//* I */ "001001100", /**//* J */ "000011100", /**//* K */ "100000011", /**//* L */ "001000011", /**//* M */ "101000010", /**//* N */ "000010011", /**//* O */ "100010010", /**//* P */ "001010010", /**//* Q */ "000000111", /**//* R */ "100000110", /**//* S */ "001000110", /**//* T */ "000010110", /**//* U */ "110000001", /**//* V */ "011000001", /**//* W */ "111000000", /**//* X */ "010010001", /**//* Y */ "110010000", /**//* Z */ "011010000", /**//* - */ "010000101", /**//* . */ "110000100", /**//*' '*/ "011000100", /**//* $ */ "010101000", /**//* / */ "010100010", /**//* + */ "010001010", /**//* % */ "000101010", /**//* * */ "010010100" }; // 条码转成大写 barcode = barcode.ToUpper(); // 做成图片 Bitmap objBitmap = new Bitmap( ((WidLength * 3 + NarrowLength * 7) * (intSourceLength + 2)) + (x * 2), BarCodeHeight + (y * 2)); Graphics objGraphics = Graphics.FromImage(objBitmap); // 底色 objGraphics.FillRectangle(Brushes.White, 0, 0, objBitmap.Width, objBitmap.Height); for (int i = 0; i < intSourceLength; i++) { // 检查是否有非法字符 if (AlphaBet.IndexOf(barcode[i]) == -1 || barcode[i] == '*') { objGraphics.DrawString("含有非法字符", SystemFonts.DefaultFont, Brushes.Red, x, y); return objBitmap; } // 查表编码 strEncode = string.Format("{0}0{1}", strEncode, Code39[AlphaBet.IndexOf(barcode[i])]); } strEncode = string.Format("{0}0010010100", strEncode); // 补充结束符号 * int intEncodeLength = strEncode.Length; // 编码后边的长度 int intBarWidth; for (int i = 0; i < intEncodeLength; i++) // 根据码画出Code39 BarCode { intBarWidth = strEncode[i] == '1' ? WidLength : NarrowLength; objGraphics.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White, x, y, intBarWidth, BarCodeHeight); x += intBarWidth; } return objBitmap; } catch (Exception ex) { throw ex; } } #endregion #region INI文件读写 /// /// 写入INI文件 /// /// 节点名称[如[TypeName]] /// 键 /// 值 /// 文件路径 /// public static long WriteIniFile(string section, string key, string value, string filePath) { try { return WritePrivateProfileString(section, key, value, filePath); } catch (Exception ex) { throw ex; } } /// /// 读取INI文件 /// /// 节点名称 /// 键 /// 文件路径 /// public static string ReadIniFile(string section, string key, string filePath) { try { StringBuilder returnValue = new StringBuilder(1024); GetPrivateProfileString(section, key, "", returnValue, 1024, filePath); return returnValue.ToString(); } catch (Exception ex) { throw ex; } } #endregion #region DataGridView限制 /// /// 设定DataGridView的排序方式 /// /// 需要设置排序的DataGridView /// 排序方式 public static void SetDataGridViewColumnsSortMode(DataGridView dataGridView, DataGridViewColumnSortMode sortMode) { if (dataGridView == null) { return; } for (int i = 0; i < dataGridView.Columns.Count; i++) { dataGridView.Columns[i].SortMode = sortMode; } } #endregion #region 时间字符串转换成DateTime类型 /// /// 时间字符串转换成DateTime类型 /// /// 服务器时间 /// 时间格式字符串 /// public static DateTime ConvertTimeStr(DateTime serverTime, string timeStr) { try { DateTime dateTime = serverTime; string[] times = timeStr.Split(':'); if (times.Length == 3) { dateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, Convert.ToInt16(times[0]), Convert.ToInt16(times[1]), Convert.ToInt16(times[2])); } return dateTime; } catch (Exception ex) { throw ex; } } #endregion public static int? ToNullableInt32(this object obj) { if (obj == null || obj == DBNull.Value) { return null; } return Convert.ToInt32(obj); } } }