Function.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web.UI;
  6. using System.Configuration;
  7. using System.Text.RegularExpressions;
  8. using System.Security.Cryptography;
  9. using System.IO;
  10. using System.Web;
  11. namespace Bowin.Common.Utility
  12. {
  13. public static class Function
  14. {
  15. /// <summary>
  16. /// 过滤sql注入
  17. /// </summary>
  18. /// <param name="htmlStr"></param>
  19. /// <returns></returns>
  20. public static string FilterSQLStr(string htmlStr)
  21. {
  22. htmlStr = htmlStr.Replace(";", "").Replace("&", "&#38;").Replace(" having ", "").Replace(" and ", "").Replace("+and+", "").Replace("and%20", "").Replace("exec ", "").Replace("select ", "").Replace("delete ", "").Replace("update ", "").Replace("count ", "");
  23. htmlStr = htmlStr.Replace("chr ", "").Replace("mid ", "").Replace("master ", "").Replace("truncate ", "").Replace("char ", "").Replace("declare ", "");
  24. htmlStr = htmlStr.Replace("or ", "").Replace("*", "&#42;").Replace("%", "&#37;").Replace("$", "&#36;");
  25. htmlStr = htmlStr.Replace("-", "&#45;").Replace("+", "&#43;").Replace(",", "&#44;").Replace("'", "&#39;").Replace("\\ ", "").Replace("\\' ", "");
  26. htmlStr = htmlStr.Replace("\\\"", "").Replace("=", "&#61;").Replace("\"", "&#92;").Replace("/", "&#47;").Replace("(", "&#40;").Replace(")", "&#41;");
  27. htmlStr = htmlStr.Replace("<", "&lt;").Replace(">", "&gt;");
  28. htmlStr = htmlStr.Replace("@", "&#64;");
  29. return htmlStr;
  30. }
  31. public static bool TryParse<T1, T2>(this T1 source, out T2 result)
  32. {
  33. try
  34. {
  35. result = (T2)Convert.ChangeType(source, typeof(T2));
  36. return true;
  37. }
  38. catch
  39. {
  40. result = default(T2);
  41. return false;
  42. }
  43. }
  44. ///<summary>
  45. /// 创建人:zengqz.
  46. /// 创建时间:2010-6-12 15:22:37
  47. /// 最后一次修改人:
  48. /// 最后一次修改时间:
  49. /// 返回一个 主键,包含生成主键时间的信息,改进GUID的有序性,提高索引效率
  50. /// </summary>
  51. /// <returns>32位的字符串</returns>
  52. private static string NewPK()
  53. {
  54. byte[] guidArray = System.Guid.NewGuid().ToByteArray();
  55. DateTime baseDate = new DateTime(1900, 1, 1);
  56. DateTime now = DateTime.Now;
  57. TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);
  58. TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks));
  59. byte[] daysArray = BitConverter.GetBytes(days.Days);
  60. byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));
  61. Array.Reverse(daysArray);
  62. Array.Reverse(msecsArray);
  63. Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
  64. Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);
  65. return new System.Guid(guidArray).ToString().Replace("-", "").ToLower();
  66. }
  67. public static Guid NewPKGuid()
  68. {
  69. byte[] guidArray = System.Guid.NewGuid().ToByteArray();
  70. DateTime baseDate = new DateTime(1900, 1, 1);
  71. DateTime now = DateTime.Now;
  72. TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);
  73. TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks));
  74. byte[] daysArray = BitConverter.GetBytes(days.Days);
  75. byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));
  76. Array.Reverse(daysArray);
  77. Array.Reverse(msecsArray);
  78. Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
  79. Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);
  80. return new System.Guid(guidArray);
  81. }
  82. /// <summary>
  83. /// 创建人:zengqz.
  84. /// 创建时间:2009-7-2 15:22:37
  85. /// 最后一次修改人:
  86. /// 最后一次修改时间:
  87. /// 说明:得到GUID字符串(32个字符)
  88. /// </summary>
  89. /// <returns>去除"-"的GUID字符串</returns>
  90. public static string GetGUID()
  91. {
  92. return NewPK();
  93. }
  94. public static void ReturnToPage(System.Web.UI.Page page, string msg, string url)
  95. {
  96. if (url == null) url = "";
  97. if ((msg != "") && (msg != null))
  98. {
  99. page.ClientScript.RegisterStartupScript(page.GetType(), "ShowMessage", "<script>addLoadEvent(function(){alert('" + msg + "')});</script>");
  100. }
  101. StringBuilder builder = new StringBuilder();
  102. builder.Append("<script>addLoadEvent(function(){");
  103. switch (url)
  104. {
  105. case "":
  106. builder.Append("jsClose()");
  107. break;
  108. case "parent":
  109. builder.Append("jsClose('parent')");
  110. break;
  111. case "parentsubmit":
  112. builder.Append("jsClose('parentsubmit')");
  113. break;
  114. case "this":
  115. string s = (page.Request.UrlReferrer == null) ? "" : page.Request.UrlReferrer.ToString();
  116. if (s == "")
  117. {
  118. builder.Append("jsClose()");
  119. }
  120. else
  121. {
  122. Regex rx = new Regex(@"[\?|&]ref=\d*");
  123. s = rx.Replace(s, "");
  124. s += (s.IndexOf("?") > 0) ? "&ref=" : "?ref=";
  125. builder.Append("jsClose('" + s + getRandom(9999) + "')");
  126. }
  127. break;
  128. case "hold":
  129. break;
  130. default:
  131. builder.Append("jsClose('" + url + "')");
  132. break;
  133. }
  134. builder.Append("});</script>");
  135. page.ClientScript.RegisterStartupScript(page.GetType(), "CloseWindow", builder.ToString());
  136. }
  137. #region 返回随机数 getRandom
  138. public static int getRandom(int iMax)
  139. {
  140. if (iMax < 1) iMax = 1;
  141. Random r = new Random(System.Environment.TickCount);
  142. return r.Next(iMax);
  143. }
  144. #endregion
  145. /// <summary>
  146. /// 创建人:zengqz.
  147. /// 创建时间:2009-7-7 9:22:00
  148. /// 最后一次修改人:
  149. /// 最后一次修改时间:
  150. /// 说明:显示图标
  151. /// </summary>
  152. /// <param name="sPostfix">图标类型(bmp,csv,dll,doc,fon,ini,jpg,paf,pps,ppt,rar,tf,txt,slx,xml,zip)</param>
  153. /// <returns>显示图标的路径</returns>
  154. public static string ShowIcon(string sPostfix)
  155. {
  156. string sResult = "";
  157. switch (sPostfix)
  158. {
  159. case "bmp":
  160. case "csv":
  161. case "dll":
  162. case "doc":
  163. case "fon":
  164. case "ini":
  165. case "jpg":
  166. case "pdf":
  167. case "pps":
  168. case "ppt":
  169. case "rar":
  170. case "ttf":
  171. case "txt":
  172. case "xls":
  173. case "xml":
  174. case "zip":
  175. sResult = "~/Images/FileTypeIcon/" + sPostfix + ".gif";
  176. break;
  177. default:
  178. sResult = "~/Images/FileTypeIcon/white.gif";
  179. break;
  180. }
  181. return sResult;
  182. }
  183. /// <summary>
  184. /// 设置页面权限
  185. /// </summary>
  186. /// <param name="page">当前页面</param>
  187. /// <param name="sControlSet">设置控件字符串</param>
  188. public static void SetPageRight(Page page, string sControlSet)
  189. {
  190. page.ClientScript.RegisterStartupScript(typeof(Page), "jsGetSetPageBtnDisplay", " jsSetPageBtnDisplay('" + sControlSet + "')", true);
  191. }
  192. /// <summary>
  193. /// 获取上传附件大小
  194. /// </summary>
  195. /// <returns></returns>
  196. public static int GetAttachmentSize()
  197. {
  198. string sAttachmentSize = "";
  199. sAttachmentSize = ConfigurationManager.AppSettings["AttachmentSizeLimit"];
  200. if (string.IsNullOrEmpty(sAttachmentSize))
  201. {
  202. sAttachmentSize = "50";
  203. }
  204. return Convert.ToInt32(sAttachmentSize);
  205. }
  206. /// <summary>
  207. /// 获取SOA权限路由
  208. /// </summary>
  209. /// <returns></returns>
  210. public static string GetSystemRoute()
  211. {
  212. return ConfigurationManager.AppSettings["SYSTEM_ROUTE"];
  213. }
  214. /// <summary>
  215. /// 获取域名
  216. /// </summary>
  217. /// <returns></returns>
  218. public static string GetDomail_Url()
  219. {
  220. return ConfigurationManager.AppSettings["Domail_Url"];
  221. }
  222. /// <summary>
  223. /// 获取虚拟目录名称
  224. /// </summary>
  225. /// <returns></returns>
  226. public static string GetVirtual_Directory()
  227. {
  228. return ConfigurationManager.AppSettings["Virtual_Directory_Name"];
  229. }
  230. public static string GetDownFile(string fileName, DateTime fileDate)
  231. {
  232. string downfileDoc = ConfigurationManager.AppSettings["Doc_downFile"];
  233. downfileDoc = Path.Combine(downfileDoc, fileDate.ToString("yyyyMM"));
  234. downfileDoc = Path.Combine(downfileDoc, fileName);
  235. downfileDoc = downfileDoc.Replace("\\", "/");
  236. return downfileDoc;
  237. }
  238. /// <summary>
  239. /// 计算文件的MD5校验
  240. /// </summary>
  241. /// <param name="fileName"></param>
  242. /// <returns></returns>
  243. public static string GetMD5HashFromFile(string fileName)
  244. {
  245. try
  246. {
  247. FileStream file = new FileStream(fileName, FileMode.Open);
  248. MD5 md5 = new MD5CryptoServiceProvider();
  249. byte[] retVal = md5.ComputeHash(file);
  250. file.Close();
  251. StringBuilder sb = new StringBuilder();
  252. for (int i = 0; i < retVal.Length; i++)
  253. {
  254. sb.Append(retVal[i].ToString("x2"));
  255. }
  256. return sb.ToString();
  257. }
  258. catch (Exception ex)
  259. {
  260. throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
  261. }
  262. }
  263. ///// <summary>
  264. ///// 上传文件
  265. ///// </summary>
  266. ///// <param name="buffer">文件流</param>
  267. ///// <param name="fileName">文件路径(包括文件名)</param>
  268. ///// <returns></returns>
  269. //public static bool UploadFile(byte[] buffer, string filePath)
  270. //{
  271. // var flag = false;
  272. // try
  273. // {
  274. // string filePhysicalPath = HttpContext.Current.Server.MapPath(filePath); //存放文件的物理路径
  275. // var path = Path.GetDirectoryName(filePhysicalPath);
  276. // if (!Directory.Exists(path))
  277. // {
  278. // Directory.CreateDirectory(path);
  279. // }
  280. // //定义并实例化一个内存流,以存放提交上来的字节数组。
  281. // MemoryStream ms = new MemoryStream(buffer);
  282. // //定义实际文件对象,保存上载的文件。
  283. // FileStream fs = new FileStream(filePhysicalPath, FileMode.Create);
  284. // //把内内存里的数据写入物理文件
  285. // ms.WriteTo(fs);
  286. // ms.Close();
  287. // fs.Close();
  288. // fs = null;
  289. // ms = null;
  290. // flag = true;
  291. // }
  292. // catch
  293. // {
  294. // flag = false;
  295. // }
  296. // return flag;
  297. //}
  298. /// <summary>
  299. /// 上传文件(支持断点续传)
  300. /// </summary>
  301. /// <param name="buffer">文件流</param>
  302. /// <param name="filePath">文件路径(包括文件名)</param>
  303. /// <param name="offset">偏移</param>
  304. /// <returns>上传是否成功</returns>
  305. public static bool UploadFile(byte[] buffer, string filePath, long offset = 0)
  306. {
  307. var writeBuffer = buffer;
  308. if (writeBuffer == null) return false;
  309. if (offset < 0) offset = 0;
  310. try
  311. {
  312. string filePhysicalPath = HttpContext.Current.Server.MapPath(filePath); //存放文件的物理路径
  313. var path = Path.GetDirectoryName(filePhysicalPath);
  314. if (!Directory.Exists(path))
  315. {
  316. Directory.CreateDirectory(path);
  317. }
  318. using (FileStream filesStream = new FileStream(filePhysicalPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
  319. {
  320. filesStream.Seek(offset, SeekOrigin.Begin);
  321. filesStream.Write(buffer, 0, buffer.Length);
  322. filesStream.Flush();
  323. }
  324. return true;
  325. }
  326. catch (Exception ex)
  327. {
  328. throw ex;
  329. //return false;
  330. }
  331. }
  332. /// <summary>
  333. /// 获取临时文件名路径
  334. /// </summary>
  335. /// <returns></returns>
  336. public static string GetTempFile()
  337. {
  338. return ConfigurationManager.AppSettings["Doc_downFile"];
  339. }
  340. /// <summary>
  341. /// 获取模板文件名路径
  342. /// </summary>
  343. /// <returns></returns>
  344. public static string GetTemplateFile()
  345. {
  346. return ConfigurationManager.AppSettings["Doc_TemplateFile"];
  347. }
  348. /// <summary>
  349. /// 是否本地登录
  350. /// </summary>
  351. /// <returns></returns>
  352. public static string GetIsLocalLogin()
  353. {
  354. return ConfigurationManager.AppSettings["Is_Local_Login"];
  355. }
  356. /// <summary>
  357. /// 是否需要单点登陆
  358. /// </summary>
  359. /// <returns></returns>
  360. public static string GetIsSSOLogin()
  361. {
  362. return ConfigurationManager.AppSettings["Is_SSO_Login"];
  363. }
  364. /// <summary>
  365. /// 获取单点登陆 登录令牌键值
  366. /// </summary>
  367. /// <returns></returns>
  368. public static string GetSS0CookieID()
  369. {
  370. return ConfigurationManager.AppSettings["SS0_CookieID"];
  371. }
  372. /// <summary>
  373. /// 获取单点登陆 省平台登录令牌键值
  374. /// </summary>
  375. /// <returns></returns>
  376. public static string GetSS0PortalCookieID()
  377. {
  378. return ConfigurationManager.AppSettings["SS0_Portal_CookieID"];
  379. }
  380. /// <summary>
  381. /// 获取单点登陆 登录令牌键值
  382. /// </summary>
  383. /// <returns></returns>
  384. public static string GetCookiesDomain()
  385. {
  386. return ConfigurationManager.AppSettings["Cookies_Domain"];
  387. }
  388. /// <summary>
  389. /// 是否使用AIO短信接口
  390. /// </summary>
  391. /// <returns></returns>
  392. public static string GetIsUseAIOSMS()
  393. {
  394. return ConfigurationManager.AppSettings["Is_UseAIOSMS"];
  395. }
  396. /// <summary>
  397. /// AIO短信接口 帐号
  398. /// </summary>
  399. /// <returns></returns>
  400. public static string GetAIOSMSAccount()
  401. {
  402. return ConfigurationManager.AppSettings["AIO_SMS_Account"];
  403. }
  404. /// <summary>
  405. /// AIO短信接口 密码
  406. /// </summary>
  407. /// <returns></returns>
  408. public static string GetAIOSMSPassword()
  409. {
  410. return ConfigurationManager.AppSettings["AIO_SMS_Password"];
  411. }
  412. #region 得到用户IP地址 getUserIP
  413. public static string GetUserIP()
  414. {
  415. HttpRequest objRequest = HttpContext.Current.Request;
  416. return objRequest.UserHostAddress;
  417. //return (objRequest.ServerVariables["HTTP_VIA"] != null) ? objRequest.ServerVariables["HTTP_X_FORWARDED_FOR"] : objRequest.ServerVariables["REMOTE_ADDR"];
  418. }
  419. #endregion
  420. #region AES加密和解密
  421. /// <summary>
  422. /// 执行DES解密
  423. /// </summary>
  424. /// <param name="decryptStr">解密字符串</param>
  425. /// <returns>返回解密后字符串</returns>
  426. public static string DESDecrypt(string decryptStr)
  427. {
  428. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  429. byte[] inputByteArray = new byte[decryptStr.Length / 2];
  430. for (int x = 0; x < decryptStr.Length / 2; x++)
  431. {
  432. int i = (Convert.ToInt32(decryptStr.Substring(x * 2, 2), 16));
  433. inputByteArray[x] = (byte)i;
  434. }
  435. byte[] desKey = new byte[] { 0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08 };
  436. byte[] desIV = new byte[] { 0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08 };
  437. des.Key = desKey;
  438. des.IV = desIV;
  439. MemoryStream ms = new MemoryStream();
  440. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  441. try
  442. {
  443. cs.Write(inputByteArray, 0, inputByteArray.Length);
  444. cs.FlushFinalBlock();
  445. }
  446. catch (Exception)
  447. {
  448. ms.Dispose();
  449. return "";
  450. }
  451. StringBuilder ret = new StringBuilder();
  452. return System.Text.Encoding.Default.GetString(ms.ToArray());
  453. }
  454. /// <summary>
  455. /// xuner DES加密
  456. /// </summary>
  457. /// <param name="pToEncrypt">加密前字符串</param>
  458. /// <returns>加密后字符串</returns>
  459. public static string DESEncrypt(string pToEncrypt)
  460. {
  461. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  462. byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
  463. byte[] desKey = new byte[] { 0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08 };
  464. byte[] desIV = new byte[] { 0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08 };
  465. des.Key = desKey;
  466. des.IV = desIV;
  467. MemoryStream ms = new MemoryStream();
  468. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  469. cs.Write(inputByteArray, 0, inputByteArray.Length);
  470. cs.FlushFinalBlock();
  471. StringBuilder ret = new StringBuilder();
  472. foreach (byte b in ms.ToArray())
  473. {
  474. ret.AppendFormat("{0:X2}", b);
  475. }
  476. ret.ToString();
  477. return ret.ToString();
  478. }
  479. #endregion
  480. /// <summary>
  481. /// 获取一个汉字的拼音首字母
  482. /// </summary>
  483. /// <param name="cnChar"></param>
  484. /// <returns></returns>
  485. public static string GetSpell(string cnChar)
  486. {
  487. //将汉字转化为ASNI码,二进制序列
  488. byte[] arrCN = Encoding.Default.GetBytes(cnChar);
  489. if (arrCN.Length > 1)
  490. {
  491. int area = (short)arrCN[0];
  492. int pos = (short)arrCN[1];
  493. int code = (area << 8) + pos;
  494. int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119,
  495. 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387,
  496. 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
  497. for (int i = 0; i < 26; i++)
  498. {
  499. int max = 55290;
  500. if (i != 25) max = areacode[i + 1];
  501. if (areacode[i] <= code && code < max)
  502. {
  503. return Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
  504. }
  505. }
  506. return "*";
  507. }
  508. else return cnChar;
  509. }
  510. /// <summary>
  511. /// 验证手机号码
  512. /// </summary>
  513. /// <param name="mobileNo"></param>
  514. /// <returns></returns>
  515. public static bool IsMobileNo(string mobileNo)
  516. {
  517. return System.Text.RegularExpressions.Regex.IsMatch(mobileNo, @"^[1]+[3,5]+\d{9}");
  518. }
  519. public static List<int> WeekList
  520. {
  521. get
  522. {
  523. return new List<int>()
  524. {
  525. 0,1,2,3,4,5,6,7
  526. };
  527. }
  528. }
  529. }
  530. }