PublicFunction.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Data;
  5. using System.Text.RegularExpressions;
  6. using Library;
  7. using System.IO;
  8. using System.Web;
  9. using Microsoft.IdentityModel.Tokens;
  10. using System.Security.Claims;
  11. using System.IdentityModel.Tokens.Jwt;
  12. using System.Text;
  13. namespace MySystem
  14. {
  15. public class PublicFunction
  16. {
  17. #region 中译英
  18. public string TranslateZHToEn(string Source)
  19. {
  20. string result = function.GetWebRequest("http://fanyi.youdao.com/translate?&doctype=json&type=ZH_CN2EN&i=" + Source);
  21. //{"type":"ZH_CN2EN","errorCode":0,"elapsedTime":2,"translateResult":[[{"src":"大事件","tgt":"The big event"}]]}
  22. Match match = Regex.Match(result, "\"tgt\":\".*?\"");
  23. if (match.Success)
  24. {
  25. return match.Value.Replace("\"tgt\":", "").Trim('"');
  26. }
  27. return "";
  28. }
  29. #endregion
  30. #region 解析编辑器里的视频代码
  31. public string CheckMediaFromHtml(string content)
  32. {
  33. if (string.IsNullOrEmpty(content))
  34. {
  35. return "";
  36. }
  37. string result = content;
  38. MatchCollection mc = Regex.Matches(content, "<embed.*?/>");
  39. foreach (Match submc in mc)
  40. {
  41. string info = submc.Value;
  42. Match match = Regex.Match(info, "src=\".*?\"");
  43. if (match.Success)
  44. {
  45. string path = match.Value;
  46. path = path.Replace("src=\"", "");
  47. path = path.TrimEnd(new char[] { '"' });
  48. string html = "";
  49. string width = "600";
  50. string height = "300";
  51. Match width_match = Regex.Match(info, "width=\".*?\"");
  52. if (width_match.Success)
  53. {
  54. width = width_match.Value.Replace("width=", "").Trim('"');
  55. }
  56. Match height_match = Regex.Match(info, "height=\".*?\"");
  57. if (height_match.Success)
  58. {
  59. height = height_match.Value.Replace("height=", "").Trim('"');
  60. }
  61. if (path.EndsWith(".mp4"))
  62. {
  63. if (string.IsNullOrEmpty(html))
  64. {
  65. html = "<video controls=\"controls\" autoplay=\"autoplay\" poster=\"\" onplay=\"true\" width=\"" + width + "\" height=\"" + height + "\" onclick=\"this.play();\">" +
  66. "<source src=\"" + path + "\">" +
  67. "<source src=\"" + path + "\" type=\"video/mp4\">" +
  68. "<source src=\"" + path + "\" type=\"video/webm\">" +
  69. "<source src=\"" + path + "\" type=\"video/ogg\">" +
  70. "</video>";
  71. }
  72. }
  73. else if (path.EndsWith(".mp3"))
  74. {
  75. html = "<audio controls=\"controls\" width=\"" + width + "\" height=\"" + height + "\" onclick=\"this.play();\">" +
  76. "<source src=\"" + path + "\" type=\"audio/mp3\" />" +
  77. "<embed src=\"" + path + "\" height=\"100\" width=\"100\" />" +
  78. "</audio>";
  79. }
  80. result = result.Replace(info, html);
  81. }
  82. }
  83. return result;
  84. }
  85. #endregion
  86. #region 对象转Json字符串
  87. public static string ObjectToJsonString(object obj)
  88. {
  89. return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  90. }
  91. #endregion
  92. #region Json字符串转对象
  93. public static T DeserializeJSON<T>(string json)
  94. {
  95. return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
  96. }
  97. #endregion
  98. #region 删除文件
  99. public static bool DeleteFile(string VirtualPath)
  100. {
  101. string FilePath = function.getPath(VirtualPath);
  102. if (System.IO.File.Exists(FilePath))
  103. {
  104. System.IO.File.Delete(FilePath);
  105. return true;
  106. }
  107. return false;
  108. }
  109. #endregion
  110. #region 两点距离
  111. public static double GetDistanceNumber(string start, string end)
  112. {
  113. if (!string.IsNullOrEmpty(start) && !string.IsNullOrEmpty(end))
  114. {
  115. string[] startpos = start.Split(',');
  116. string[] endpos = end.Split(',');
  117. double lng1 = double.Parse(startpos[0]);
  118. double lat1 = double.Parse(startpos[1]);
  119. double lng2 = double.Parse(endpos[0]);
  120. double lat2 = double.Parse(endpos[1]);
  121. double radLat1 = rad(lat1);
  122. double radLat2 = rad(lat2);
  123. double a = radLat1 - radLat2;
  124. double b = rad(lng1) - rad(lng2);
  125. double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
  126. s = s * EARTH_RADIUS;
  127. s = Math.Round(s * 10000) / 10000;
  128. return s;
  129. }
  130. return 10000000;
  131. }
  132. private static double rad(double d)
  133. {
  134. return d * Math.PI / 180.0;
  135. }
  136. private static double EARTH_RADIUS = 6378.137;
  137. #endregion
  138. #region 获取OSS开关
  139. public string GetOssStatus()
  140. {
  141. return "-oss";
  142. }
  143. #endregion
  144. #region 通过表名、文本、值获得字典数据
  145. public Dictionary<string, string> GetDictionaryByTableName(string tableEnName, string Text, string Value)
  146. {
  147. Text = Text.Split('_')[0];
  148. Value = Value.Split('_')[0];
  149. Dictionary<string, string> dic = new Dictionary<string, string>();
  150. DataTable dt = dbconn.dtable("select " + Text + "," + Value + " from " + tableEnName + " order by Sort desc,Id asc");
  151. foreach (DataRow dr in dt.Rows)
  152. {
  153. dic.Add(dr[1].ToString(), dr[0].ToString());
  154. }
  155. return dic;
  156. }
  157. #endregion
  158. #region 接口通用DES解密
  159. public static string DesDecrypt(string content)
  160. {
  161. content = HttpUtility.UrlDecode(content);
  162. return dbconn.DesDecrypt(content, "*ga34|^7");
  163. }
  164. #endregion
  165. #region 统计机具绑定数据
  166. public static void StatUserMachineData(int UserId, int BrandId, int Count)
  167. {
  168. Models.Main1.WebCMSEntities main1db = new Models.Main1.WebCMSEntities();
  169. string IdBrand = UserId + "_" + BrandId;
  170. Models.Main1.UserMachineData MachineData = main1db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
  171. if (MachineData == null)
  172. {
  173. MachineData = main1db.UserMachineData.Add(new Models.Main1.UserMachineData()
  174. {
  175. IdBrand = IdBrand,
  176. }).Entity;
  177. main1db.SaveChanges();
  178. }
  179. if (Count < 0)
  180. {
  181. MachineData.TotalMachineCount -= Math.Abs(Count);
  182. MachineData.UnBindCount -= Math.Abs(Count);
  183. }
  184. else
  185. {
  186. MachineData.TotalMachineCount += Count;
  187. MachineData.UnBindCount += Count;
  188. }
  189. main1db.SaveChanges();
  190. main1db.Dispose();
  191. }
  192. #endregion
  193. #region 绑定
  194. public static void BindUserMachineData(Models.Main1.WebCMSEntities db, int UserId, int BrandId, int Count, string PosSn)
  195. {
  196. if(BrandId == 1)
  197. {
  198. Models.Main1.PosMachines pos = db.PosMachines.FirstOrDefault(m => m.PosSn == PosSn) ?? new Models.Main1.PosMachines();
  199. pos.BindingState = 1;
  200. pos.BuyUserId = UserId;
  201. pos.UserId = UserId;
  202. pos.BindingTime = DateTime.Now;
  203. }
  204. else
  205. {
  206. Models.Main1.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn) ?? new Models.Main1.PosMachinesTwo();
  207. pos.BindingState = 1;
  208. pos.BuyUserId = UserId;
  209. pos.UserId = UserId;
  210. pos.BindingTime = DateTime.Now;
  211. }
  212. string IdBrand = UserId + "_" + BrandId;
  213. Models.Main1.UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
  214. if (MachineData == null)
  215. {
  216. MachineData = db.UserMachineData.Add(new Models.Main1.UserMachineData()
  217. {
  218. IdBrand = IdBrand,
  219. }).Entity;
  220. db.SaveChanges();
  221. }
  222. MachineData.UnBindCount -= Count;
  223. MachineData.BindCount += Count;
  224. db.SaveChanges();
  225. }
  226. #endregion
  227. #region 划拨记录
  228. public static void SendRecord(Models.Main1.WebCMSEntities db, int UserId, int ToUserId, int StoreId, string[] PosSnList)
  229. {
  230. string ChangeRecordNo = "SC" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
  231. for (int i = 0; i < PosSnList.Length; i++)
  232. {
  233. string PosSn = PosSnList[i];
  234. Models.Main1.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn) ?? new Models.Main1.PosMachinesTwo();
  235. pos.StoreId = StoreId;
  236. pos.TransferTime = DateTime.Now;
  237. pos.BuyUserId = ToUserId;
  238. pos.UserId = ToUserId;
  239. db.PosCouponRecord.Add(new Models.Main1.PosCouponRecord()
  240. {
  241. CreateDate = DateTime.Now,
  242. OrderNo = ChangeRecordNo,
  243. ToUserId = ToUserId,
  244. FromUserId = UserId,
  245. PosCouponId = pos.Id,
  246. });
  247. }
  248. int SnCount = PosSnList.Length;
  249. db.PosCouponOrders.Add(new Models.Main1.PosCouponOrders()
  250. {
  251. CreateDate = DateTime.Now,
  252. ChangeCount = SnCount,
  253. OrderNo = ChangeRecordNo,
  254. ToUserId = ToUserId,
  255. FromUserId = UserId,
  256. });
  257. db.SaveChanges();
  258. }
  259. #endregion
  260. #region 获取jwt的token
  261. public static string AppToken(string username)
  262. {
  263. string test = function.get_Random(10);
  264. var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtConfig.JwtSecret)), SecurityAlgorithms.HmacSha256);
  265. var claims = new Claim[] {
  266. new Claim(JwtRegisteredClaimNames.Iss, JwtConfig.JwtIss),
  267. new Claim(JwtRegisteredClaimNames.Aud, test),
  268. new Claim("Guid", Guid.NewGuid().ToString("D")),
  269. new Claim(ClaimTypes.Role, "system"),
  270. new Claim(ClaimTypes.Role, "admin"),
  271. };
  272. SecurityToken securityToken = new JwtSecurityToken(
  273. signingCredentials: securityKey,
  274. expires: DateTime.Now.AddDays(10),//过期时间
  275. claims: claims,
  276. audience: test,
  277. issuer: username
  278. );
  279. RedisDbconn.Instance.Set("utoken:" + username, test);
  280. RedisDbconn.Instance.SetExpire("utoken:" + username, 3600 * 24 * 10);
  281. //生成jwt令牌
  282. return new JwtSecurityTokenHandler().WriteToken(securityToken);
  283. }
  284. #endregion
  285. #region 获取jwt的token
  286. public static string AppToken(int UserId, string JwtSecret, string JwtIss, string tag = "")
  287. {
  288. return AppToken(UserId.ToString(), JwtSecret, JwtIss, tag);
  289. }
  290. public static string AppToken(string UserId, string JwtSecret, string JwtIss, string tag = "")
  291. {
  292. string Token = RedisDbconn.Instance.Get<string>("apptoken:" + UserId + tag);
  293. if (!string.IsNullOrEmpty(Token))
  294. {
  295. return Token;
  296. }
  297. string issuer = "new_" + UserId + tag;
  298. string test = function.get_Random(10);
  299. var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtSecret)), SecurityAlgorithms.HmacSha256);
  300. var claims = new Claim[] {
  301. new Claim(JwtRegisteredClaimNames.Iss,JwtIss),
  302. new Claim(JwtRegisteredClaimNames.Aud,test),
  303. new Claim("Guid", Guid.NewGuid().ToString("D")),
  304. new Claim(ClaimTypes.Role, "system"),
  305. new Claim(ClaimTypes.Role, "admin"),
  306. };
  307. SecurityToken securityToken = new JwtSecurityToken(
  308. signingCredentials: securityKey,
  309. expires: DateTime.Now.AddDays(10),//过期时间
  310. claims: claims,
  311. audience: test,
  312. issuer: issuer
  313. );
  314. RedisDbconn.Instance.Set("utoken:" + issuer, test);
  315. RedisDbconn.Instance.SetExpire("utoken:" + issuer, 3600 * 24 * 10);
  316. //生成jwt令牌
  317. Token = new JwtSecurityTokenHandler().WriteToken(securityToken);
  318. RedisDbconn.Instance.Set("apptoken:" + UserId + tag, Token);
  319. RedisDbconn.Instance.SetExpire("apptoken:" + UserId + tag, 3600 * 24 * 10 - 60);
  320. //生成jwt令牌
  321. return new JwtSecurityTokenHandler().WriteToken(securityToken);
  322. }
  323. #endregion
  324. }
  325. }