using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.UI; using System.Configuration; using System.Text.RegularExpressions; using System.Security.Cryptography; using System.IO; using System.Web; namespace Bowin.Common.Utility { public static class Function { /// /// 过滤sql注入 /// /// /// public static string FilterSQLStr(string htmlStr) { htmlStr = htmlStr.Replace(";", "").Replace("&", "&").Replace(" having ", "").Replace(" and ", "").Replace("+and+", "").Replace("and%20", "").Replace("exec ", "").Replace("select ", "").Replace("delete ", "").Replace("update ", "").Replace("count ", ""); htmlStr = htmlStr.Replace("chr ", "").Replace("mid ", "").Replace("master ", "").Replace("truncate ", "").Replace("char ", "").Replace("declare ", ""); htmlStr = htmlStr.Replace("or ", "").Replace("*", "*").Replace("%", "%").Replace("$", "$"); htmlStr = htmlStr.Replace("-", "-").Replace("+", "+").Replace(",", ",").Replace("'", "'").Replace("\\ ", "").Replace("\\' ", ""); htmlStr = htmlStr.Replace("\\\"", "").Replace("=", "=").Replace("\"", "\").Replace("/", "/").Replace("(", "(").Replace(")", ")"); htmlStr = htmlStr.Replace("<", "<").Replace(">", ">"); htmlStr = htmlStr.Replace("@", "@"); return htmlStr; } public static bool TryParse(this T1 source, out T2 result) { try { result = (T2)Convert.ChangeType(source, typeof(T2)); return true; } catch { result = default(T2); return false; } } /// /// 创建人:zengqz. /// 创建时间:2010-6-12 15:22:37 /// 最后一次修改人: /// 最后一次修改时间: /// 返回一个 主键,包含生成主键时间的信息,改进GUID的有序性,提高索引效率 /// /// 32位的字符串 private static string NewPK() { byte[] guidArray = System.Guid.NewGuid().ToByteArray(); DateTime baseDate = new DateTime(1900, 1, 1); DateTime now = DateTime.Now; TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks); TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks)); byte[] daysArray = BitConverter.GetBytes(days.Days); byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333)); Array.Reverse(daysArray); Array.Reverse(msecsArray); Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2); Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4); return new System.Guid(guidArray).ToString().Replace("-", "").ToLower(); } public static Guid NewPKGuid() { byte[] guidArray = System.Guid.NewGuid().ToByteArray(); DateTime baseDate = new DateTime(1900, 1, 1); DateTime now = DateTime.Now; TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks); TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks)); byte[] daysArray = BitConverter.GetBytes(days.Days); byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333)); Array.Reverse(daysArray); Array.Reverse(msecsArray); Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2); Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4); return new System.Guid(guidArray); } /// /// 创建人:zengqz. /// 创建时间:2009-7-2 15:22:37 /// 最后一次修改人: /// 最后一次修改时间: /// 说明:得到GUID字符串(32个字符) /// /// 去除"-"的GUID字符串 public static string GetGUID() { return NewPK(); } public static void ReturnToPage(System.Web.UI.Page page, string msg, string url) { if (url == null) url = ""; if ((msg != "") && (msg != null)) { page.ClientScript.RegisterStartupScript(page.GetType(), "ShowMessage", ""); } StringBuilder builder = new StringBuilder(); builder.Append(""); page.ClientScript.RegisterStartupScript(page.GetType(), "CloseWindow", builder.ToString()); } #region 返回随机数 getRandom public static int getRandom(int iMax) { if (iMax < 1) iMax = 1; Random r = new Random(System.Environment.TickCount); return r.Next(iMax); } #endregion /// /// 创建人:zengqz. /// 创建时间:2009-7-7 9:22:00 /// 最后一次修改人: /// 最后一次修改时间: /// 说明:显示图标 /// /// 图标类型(bmp,csv,dll,doc,fon,ini,jpg,paf,pps,ppt,rar,tf,txt,slx,xml,zip) /// 显示图标的路径 public static string ShowIcon(string sPostfix) { string sResult = ""; switch (sPostfix) { case "bmp": case "csv": case "dll": case "doc": case "fon": case "ini": case "jpg": case "pdf": case "pps": case "ppt": case "rar": case "ttf": case "txt": case "xls": case "xml": case "zip": sResult = "~/Images/FileTypeIcon/" + sPostfix + ".gif"; break; default: sResult = "~/Images/FileTypeIcon/white.gif"; break; } return sResult; } /// /// 设置页面权限 /// /// 当前页面 /// 设置控件字符串 public static void SetPageRight(Page page, string sControlSet) { page.ClientScript.RegisterStartupScript(typeof(Page), "jsGetSetPageBtnDisplay", " jsSetPageBtnDisplay('" + sControlSet + "')", true); } /// /// 获取上传附件大小 /// /// public static int GetAttachmentSize() { string sAttachmentSize = ""; sAttachmentSize = ConfigurationManager.AppSettings["AttachmentSizeLimit"]; if (string.IsNullOrEmpty(sAttachmentSize)) { sAttachmentSize = "50"; } return Convert.ToInt32(sAttachmentSize); } /// /// 获取SOA权限路由 /// /// public static string GetSystemRoute() { return ConfigurationManager.AppSettings["SYSTEM_ROUTE"]; } /// /// 获取域名 /// /// public static string GetDomail_Url() { return ConfigurationManager.AppSettings["Domail_Url"]; } /// /// 获取虚拟目录名称 /// /// public static string GetVirtual_Directory() { return ConfigurationManager.AppSettings["Virtual_Directory_Name"]; } public static string GetDownFile(string fileName, DateTime fileDate) { string downfileDoc = ConfigurationManager.AppSettings["Doc_downFile"]; downfileDoc = Path.Combine(downfileDoc, fileDate.ToString("yyyyMM")); downfileDoc = Path.Combine(downfileDoc, fileName); downfileDoc = downfileDoc.Replace("\\", "/"); return downfileDoc; } /// /// 计算文件的MD5校验 /// /// /// public static string GetMD5HashFromFile(string fileName) { try { FileStream file = new FileStream(fileName, FileMode.Open); MD5 md5 = new MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message); } } ///// ///// 上传文件 ///// ///// 文件流 ///// 文件路径(包括文件名) ///// //public static bool UploadFile(byte[] buffer, string filePath) //{ // var flag = false; // try // { // string filePhysicalPath = HttpContext.Current.Server.MapPath(filePath); //存放文件的物理路径 // var path = Path.GetDirectoryName(filePhysicalPath); // if (!Directory.Exists(path)) // { // Directory.CreateDirectory(path); // } // //定义并实例化一个内存流,以存放提交上来的字节数组。 // MemoryStream ms = new MemoryStream(buffer); // //定义实际文件对象,保存上载的文件。 // FileStream fs = new FileStream(filePhysicalPath, FileMode.Create); // //把内内存里的数据写入物理文件 // ms.WriteTo(fs); // ms.Close(); // fs.Close(); // fs = null; // ms = null; // flag = true; // } // catch // { // flag = false; // } // return flag; //} /// /// 上传文件(支持断点续传) /// /// 文件流 /// 文件路径(包括文件名) /// 偏移 /// 上传是否成功 public static bool UploadFile(byte[] buffer, string filePath, long offset = 0) { var writeBuffer = buffer; if (writeBuffer == null) return false; if (offset < 0) offset = 0; try { string filePhysicalPath = HttpContext.Current.Server.MapPath(filePath); //存放文件的物理路径 var path = Path.GetDirectoryName(filePhysicalPath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (FileStream filesStream = new FileStream(filePhysicalPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { filesStream.Seek(offset, SeekOrigin.Begin); filesStream.Write(buffer, 0, buffer.Length); filesStream.Flush(); } return true; } catch (Exception ex) { throw ex; //return false; } } /// /// 获取临时文件名路径 /// /// public static string GetTempFile() { return ConfigurationManager.AppSettings["Doc_downFile"]; } /// /// 获取模板文件名路径 /// /// public static string GetTemplateFile() { return ConfigurationManager.AppSettings["Doc_TemplateFile"]; } /// /// 是否本地登录 /// /// public static string GetIsLocalLogin() { return ConfigurationManager.AppSettings["Is_Local_Login"]; } /// /// 是否需要单点登陆 /// /// public static string GetIsSSOLogin() { return ConfigurationManager.AppSettings["Is_SSO_Login"]; } /// /// 获取单点登陆 登录令牌键值 /// /// public static string GetSS0CookieID() { return ConfigurationManager.AppSettings["SS0_CookieID"]; } /// /// 获取单点登陆 省平台登录令牌键值 /// /// public static string GetSS0PortalCookieID() { return ConfigurationManager.AppSettings["SS0_Portal_CookieID"]; } /// /// 获取单点登陆 登录令牌键值 /// /// public static string GetCookiesDomain() { return ConfigurationManager.AppSettings["Cookies_Domain"]; } /// /// 是否使用AIO短信接口 /// /// public static string GetIsUseAIOSMS() { return ConfigurationManager.AppSettings["Is_UseAIOSMS"]; } /// /// AIO短信接口 帐号 /// /// public static string GetAIOSMSAccount() { return ConfigurationManager.AppSettings["AIO_SMS_Account"]; } /// /// AIO短信接口 密码 /// /// public static string GetAIOSMSPassword() { return ConfigurationManager.AppSettings["AIO_SMS_Password"]; } #region 得到用户IP地址 getUserIP public static string GetUserIP() { HttpRequest objRequest = HttpContext.Current.Request; return objRequest.UserHostAddress; //return (objRequest.ServerVariables["HTTP_VIA"] != null) ? objRequest.ServerVariables["HTTP_X_FORWARDED_FOR"] : objRequest.ServerVariables["REMOTE_ADDR"]; } #endregion #region AES加密和解密 /// /// 执行DES解密 /// /// 解密字符串 /// 返回解密后字符串 public static string DESDecrypt(string decryptStr) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[decryptStr.Length / 2]; for (int x = 0; x < decryptStr.Length / 2; x++) { int i = (Convert.ToInt32(decryptStr.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } byte[] desKey = new byte[] { 0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08 }; byte[] desIV = new byte[] { 0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08 }; des.Key = desKey; des.IV = desIV; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); try { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); } catch (Exception) { ms.Dispose(); return ""; } StringBuilder ret = new StringBuilder(); return System.Text.Encoding.Default.GetString(ms.ToArray()); } /// /// xuner DES加密 /// /// 加密前字符串 /// 加密后字符串 public static string DESEncrypt(string pToEncrypt) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); byte[] desKey = new byte[] { 0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08 }; byte[] desIV = new byte[] { 0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08 }; des.Key = desKey; des.IV = desIV; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString(); } #endregion /// /// 获取一个汉字的拼音首字母 /// /// /// public static string GetSpell(string cnChar) { //将汉字转化为ASNI码,二进制序列 byte[] arrCN = Encoding.Default.GetBytes(cnChar); if (arrCN.Length > 1) { int area = (short)arrCN[0]; int pos = (short)arrCN[1]; int code = (area << 8) + pos; int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 }; for (int i = 0; i < 26; i++) { int max = 55290; if (i != 25) max = areacode[i + 1]; if (areacode[i] <= code && code < max) { return Encoding.Default.GetString(new byte[] { (byte)(65 + i) }); } } return "*"; } else return cnChar; } /// /// 验证手机号码 /// /// /// public static bool IsMobileNo(string mobileNo) { return System.Text.RegularExpressions.Regex.IsMatch(mobileNo, @"^[1]+[3,5]+\d{9}"); } public static List WeekList { get { return new List() { 0,1,2,3,4,5,6,7 }; } } } }