PublicFunction.cs 13 KB

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