PublicFunction.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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.Main.WebCMSEntities db, int UserId, int BrandId, int Count, string PosSn)
  195. {
  196. //主库
  197. Models.Main1.WebCMSEntities main1db = new Models.Main1.WebCMSEntities();
  198. if(BrandId == 1)
  199. {
  200. Models.Main1.PosMachines pos = main1db.PosMachines.FirstOrDefault(m => m.PosSn == PosSn) ?? new Models.Main1.PosMachines();
  201. pos.BindingState = 1;
  202. pos.BuyUserId = UserId;
  203. pos.UserId = UserId;
  204. pos.BindingTime = DateTime.Now;
  205. }
  206. else
  207. {
  208. Models.Main1.PosMachinesTwo pos = main1db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn) ?? new Models.Main1.PosMachinesTwo();
  209. pos.BindingState = 1;
  210. pos.BuyUserId = UserId;
  211. pos.UserId = UserId;
  212. pos.BindingTime = DateTime.Now;
  213. }
  214. string IdBrand = UserId + "_" + BrandId;
  215. Models.Main.UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
  216. if (MachineData == null)
  217. {
  218. MachineData = db.UserMachineData.Add(new Models.Main.UserMachineData()
  219. {
  220. IdBrand = IdBrand,
  221. }).Entity;
  222. db.SaveChanges();
  223. }
  224. MachineData.UnBindCount -= Count;
  225. MachineData.BindCount += Count;
  226. db.SaveChanges();
  227. }
  228. #endregion
  229. #region 划拨记录
  230. public static void SendRecord(Models.Main1.WebCMSEntities db, int UserId, int ToUserId, int StoreId, string[] PosSnList)
  231. {
  232. string ChangeRecordNo = "SC" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
  233. for (int i = 0; i < PosSnList.Length; i++)
  234. {
  235. string PosSn = PosSnList[i];
  236. Models.Main1.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn) ?? new Models.Main1.PosMachinesTwo();
  237. pos.StoreId = StoreId;
  238. pos.TransferTime = DateTime.Now;
  239. pos.BuyUserId = ToUserId;
  240. pos.UserId = ToUserId;
  241. db.PosCouponRecord.Add(new Models.Main1.PosCouponRecord()
  242. {
  243. CreateDate = DateTime.Now,
  244. OrderNo = ChangeRecordNo,
  245. ToUserId = ToUserId,
  246. FromUserId = UserId,
  247. PosCouponId = pos.Id,
  248. });
  249. }
  250. int SnCount = PosSnList.Length;
  251. db.PosCouponOrders.Add(new Models.Main1.PosCouponOrders()
  252. {
  253. CreateDate = DateTime.Now,
  254. ChangeCount = SnCount,
  255. OrderNo = ChangeRecordNo,
  256. ToUserId = ToUserId,
  257. FromUserId = UserId,
  258. });
  259. db.SaveChanges();
  260. }
  261. #endregion
  262. #region 获取jwt的token
  263. public static string AppToken(string username)
  264. {
  265. string test = function.get_Random(10);
  266. var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtConfig.JwtSecret)), SecurityAlgorithms.HmacSha256);
  267. var claims = new Claim[] {
  268. new Claim(JwtRegisteredClaimNames.Iss, JwtConfig.JwtIss),
  269. new Claim(JwtRegisteredClaimNames.Aud, test),
  270. new Claim("Guid", Guid.NewGuid().ToString("D")),
  271. new Claim(ClaimTypes.Role, "system"),
  272. new Claim(ClaimTypes.Role, "admin"),
  273. };
  274. SecurityToken securityToken = new JwtSecurityToken(
  275. signingCredentials: securityKey,
  276. expires: DateTime.Now.AddDays(10),//过期时间
  277. claims: claims,
  278. audience: test,
  279. issuer: username
  280. );
  281. RedisDbconn.Instance.Set("utoken:" + username, test);
  282. RedisDbconn.Instance.SetExpire("utoken:" + username, 3600 * 24 * 10);
  283. //生成jwt令牌
  284. return new JwtSecurityTokenHandler().WriteToken(securityToken);
  285. }
  286. #endregion
  287. #region 获取jwt的token
  288. public static string AppToken(int UserId, string JwtSecret, string JwtIss, string tag = "")
  289. {
  290. return AppToken(UserId.ToString(), JwtSecret, JwtIss, tag);
  291. }
  292. public static string AppToken(string UserId, string JwtSecret, string JwtIss, string tag = "")
  293. {
  294. string Token = RedisDbconn.Instance.Get<string>("apptoken:" + UserId + tag);
  295. if (!string.IsNullOrEmpty(Token))
  296. {
  297. return Token;
  298. }
  299. string issuer = "new_" + UserId + tag;
  300. string test = function.get_Random(10);
  301. var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtSecret)), SecurityAlgorithms.HmacSha256);
  302. var claims = new Claim[] {
  303. new Claim(JwtRegisteredClaimNames.Iss,JwtIss),
  304. new Claim(JwtRegisteredClaimNames.Aud,test),
  305. new Claim("Guid", Guid.NewGuid().ToString("D")),
  306. new Claim(ClaimTypes.Role, "system"),
  307. new Claim(ClaimTypes.Role, "admin"),
  308. };
  309. SecurityToken securityToken = new JwtSecurityToken(
  310. signingCredentials: securityKey,
  311. expires: DateTime.Now.AddDays(10),//过期时间
  312. claims: claims,
  313. audience: test,
  314. issuer: issuer
  315. );
  316. RedisDbconn.Instance.Set("utoken:" + issuer, test);
  317. RedisDbconn.Instance.SetExpire("utoken:" + issuer, 3600 * 24 * 10);
  318. //生成jwt令牌
  319. Token = new JwtSecurityTokenHandler().WriteToken(securityToken);
  320. RedisDbconn.Instance.Set("apptoken:" + UserId + tag, Token);
  321. RedisDbconn.Instance.SetExpire("apptoken:" + UserId + tag, 3600 * 24 * 10 - 60);
  322. //生成jwt令牌
  323. return new JwtSecurityTokenHandler().WriteToken(securityToken);
  324. }
  325. #endregion
  326. }
  327. }