using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Text.RegularExpressions; using MySystem.BsModels; using Library; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.IO; namespace MySystem { public class PublicFunction { public WebCMSEntities db = new WebCMSEntities(); public BsModels.WebCMSEntities bsdb = new BsModels.WebCMSEntities(); #region 获取权限JSON数据 public string GetRightJson() { string result = "["; List list = bsdb.RightDic.ToList(); List Level1 = list.Where(m => m.RightLevel == 1).ToList(); foreach (BsModels.RightDic sub1 in Level1) { result += "{title: '" + sub1.Name + "', id: '" + sub1.Id + "', spread: false, children: ["; List Level2 = list.Where(m => m.RightLevel == 2 && m.Id.StartsWith(sub1.Id)).ToList(); if (Level2.Count > 0) { foreach (BsModels.RightDic sub2 in Level2) { result += "{title: '" + sub2.Name + "', id: '" + sub2.Id + "', spread: false, children: ["; List Level3 = list.Where(m => m.RightLevel == 3 && m.Id.StartsWith(sub2.Id)).ToList(); if (Level3.Count > 0) { foreach (BsModels.RightDic sub3 in Level3) { result += "{title: '" + sub3.Name + "', id: '" + sub3.Id + "', spread: false, children: ["; string rightString = ForOperateRight(sub3.Id); if (!string.IsNullOrEmpty(rightString)) { result += rightString; } else { result += "{title: '基本权限', id: '" + sub3.Id + "_base'}"; } result += "]},"; } result = result.TrimEnd(','); } else { string rightString = ForOperateRight(sub2.Id); if (!string.IsNullOrEmpty(rightString)) { result += rightString; } else { result += "{title: '基本权限', id: '" + sub2.Id + "_base'}"; } } result += "]},"; } result = result.TrimEnd(','); } else { result += ForOperateRight(sub1.Id); string rightString = ForOperateRight(sub1.Id); if (!string.IsNullOrEmpty(rightString)) { result += rightString; } else { result += "{title: '基本权限', id: '" + sub1.Id + "_base'}"; } } result += "]},"; } result = result.TrimEnd(','); result += "]"; return result; } //读取当前菜单有哪些权限 public string ForOperateRight(string Id) { string result = ""; List rights = bsdb.MenuRight.Where(m => m.MenuId.StartsWith(Id)).OrderBy(m => m.MenuId).ToList(); foreach (BsModels.MenuRight right in rights) { result += "{title: '" + right.Name + "', id: '" + right.MenuId + "'},"; } BsModels.RightDic rightDic = bsdb.RightDic.FirstOrDefault(m => m.Id == Id) ?? new BsModels.RightDic(); if (!string.IsNullOrEmpty(rightDic.OtherRight)) { string[] OtherRightList = rightDic.OtherRight.Split('\n'); foreach (string SubOtherRight in OtherRightList) { string[] SubOtherRightData = SubOtherRight.Split('_'); result += "{title: '" + SubOtherRightData[1] + "', id: '" + Id + "_" + SubOtherRightData[0] + "'},"; } } result = result.TrimEnd(','); return result; } public string TranslateRightString(string RightString) { string result = ""; if (!string.IsNullOrEmpty(RightString)) { string[] RightList = RightString.Split(','); foreach (string sub in RightList) { string EndString = sub.Substring(sub.LastIndexOf("_") + 1); if (EndString.Length > 1 && !function.IsInt(EndString)) { result += sub + ","; } } } return result.TrimEnd(','); } #endregion #region 中译英 public string TranslateZHToEn(string Source) { string result = function.GetWebRequest("http://fanyi.youdao.com/translate?&doctype=json&type=ZH_CN2EN&i=" + Source); //{"type":"ZH_CN2EN","errorCode":0,"elapsedTime":2,"translateResult":[[{"src":"大事件","tgt":"The big event"}]]} Match match = Regex.Match(result, "\"tgt\":\".*?\""); if (match.Success) { return match.Value.Replace("\"tgt\":", "").Trim('"'); } return ""; } #endregion #region 解析编辑器里的视频代码 public string CheckMediaFromHtml(string content) { if (string.IsNullOrEmpty(content)) { return ""; } string result = content; MatchCollection mc = Regex.Matches(content, ""); foreach (Match submc in mc) { string info = submc.Value; Match match = Regex.Match(info, "src=\".*?\""); if (match.Success) { string path = match.Value; path = path.Replace("src=\"", ""); path = path.TrimEnd(new char[] { '"' }); string html = ""; string width = "600"; string height = "300"; Match width_match = Regex.Match(info, "width=\".*?\""); if (width_match.Success) { width = width_match.Value.Replace("width=", "").Trim('"'); } Match height_match = Regex.Match(info, "height=\".*?\""); if (height_match.Success) { height = height_match.Value.Replace("height=", "").Trim('"'); } if (path.EndsWith(".mp4")) { if (string.IsNullOrEmpty(html)) { html = ""; } } else if (path.EndsWith(".mp3")) { html = ""; } result = result.Replace(info, html); } } return result; } #endregion #region 对象转Json字符串 public static string ObjectToJsonString(object obj) { return Newtonsoft.Json.JsonConvert.SerializeObject(obj); } #endregion #region Json字符串转对象 public static T DeserializeJSON(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject(json); } #endregion #region 删除文件 public static bool DeleteFile(string VirtualPath) { string FilePath = function.getPath(VirtualPath); if (System.IO.File.Exists(FilePath)) { System.IO.File.Delete(FilePath); return true; } return false; } #endregion #region 两点距离 public static double GetDistanceNumber(string start, string end) { if (!string.IsNullOrEmpty(start) && !string.IsNullOrEmpty(end)) { string[] startpos = start.Split(','); string[] endpos = end.Split(','); double lng1 = double.Parse(startpos[0]); double lat1 = double.Parse(startpos[1]); double lng2 = double.Parse(endpos[0]); double lat2 = double.Parse(endpos[1]); double radLat1 = rad(lat1); double radLat2 = rad(lat2); double a = radLat1 - radLat2; double b = rad(lng1) - rad(lng2); 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))); s = s * EARTH_RADIUS; s = Math.Round(s * 10000) / 10000; return s; } return 10000000; } private static double rad(double d) { return d * Math.PI / 180.0; } private static double EARTH_RADIUS = 6378.137; #endregion #region 短信条数 public int SMSCount() { SystemSet check = db.SystemSet.FirstOrDefault() ?? new SystemSet(); return check.QueryCount; } #endregion #region 短信消耗 public void UseSMS() { SystemSet check = db.SystemSet.FirstOrDefault(); if (check != null) { check.QueryCount -= 1; db.SaveChanges(); } } #endregion #region 获取OSS开关 public string GetOssStatus() { SystemSet set = db.SystemSet.FirstOrDefault() ?? new SystemSet(); return set.UploadOss == 1 ? "-oss" : ""; } #endregion #region 获取上传文件参数 public string GetUploadParam(string buttonId) { string tag = function.MD5_16(buttonId); string param = RedisDbconn.Instance.Get("btn:" + tag); if (!string.IsNullOrEmpty(param)) { return param; } SystemSet set = db.SystemSet.FirstOrDefault() ?? new SystemSet(); return "{width:" + set.UploadAutoZoomWidth + ",height:" + set.UploadAutoZoomHeight + ",quality:" + set.UploadAutoZoomQuality + "},{max_file_size:" + set.UploadMaxSize + "}"; } #endregion #region 获取上传文件提示文字 public string GetUploadHint(string buttonId, bool ispic = true) { string tag = function.MD5_16(buttonId); string param = RedisDbconn.Instance.Get("btn:" + tag); if (string.IsNullOrEmpty(param)) { SystemSet set = db.SystemSet.FirstOrDefault() ?? new SystemSet(); param = "{width:" + set.UploadAutoZoomWidth + ",height:" + set.UploadAutoZoomHeight + ",quality:" + set.UploadAutoZoomQuality + "},{max_file_size:" + set.UploadMaxSize + "}"; } string[] json = param.Replace(" ", "").Replace("},{", "}#cut#{").Split(new string[] { "#cut#" }, StringSplitOptions.None); Dictionary resize = Newtonsoft.Json.JsonConvert.DeserializeObject>(json[0]); Dictionary size = Newtonsoft.Json.JsonConvert.DeserializeObject>(json[1]); int max_file_size = int.Parse(size["max_file_size"]) / 1024; string unit = "KB"; if (max_file_size / 1024 > 0) { max_file_size = max_file_size / 1024; unit = "MB"; } if (max_file_size / 1024 > 0) { max_file_size = max_file_size / 1024; unit = "GB"; } if (ispic) { return "建议尺寸" + resize["width"] + "x" + resize["height"] + "," + max_file_size + unit + "以内"; } return "建议" + max_file_size + "以内"; } #endregion #region 通过表名、文本、值获得字典数据 public Dictionary GetDictionaryByTableName(string tableEnName, string Text, string Value) { Text = Text.Split('_')[0]; Value = Value.Split('_')[0]; Dictionary dic = new Dictionary(); DataTable dt = dbconn.dtable("select " + Text + "," + Value + " from " + tableEnName + " order by Sort desc,Id asc"); foreach (DataRow dr in dt.Rows) { dic.Add(dr[1].ToString(), dr[0].ToString()); } return dic; } #endregion #region 获取Excel文件内容 public DataTable ExcelToDataTable(string filepath) { List result = new List(); DataTable dtTable = new DataTable(); List rowList = new List(); try { ISheet sheet; using (var stream = new FileStream(filepath, FileMode.Open)) { stream.Position = 0; XSSFWorkbook xssWorkbook = new XSSFWorkbook(stream); sheet = xssWorkbook.GetSheetAt(0); IRow headerRow = sheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { ICell cell = headerRow.GetCell(j); if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue; { dtTable.Columns.Add(cell.ToString()); } } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row == null) continue; if (row.Cells.All(d => d.CellType == CellType.Blank)) continue; for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { if (!string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString())) { rowList.Add(row.GetCell(j).ToString()); } } } if (rowList.Count > 0) dtTable.Rows.Add(rowList.ToArray()); rowList.Clear(); } } } catch (Exception ex) { function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "获取Excel文件内容异常"); } return dtTable; } #endregion #region 获取网络文件内容 public static string GetNetFileContent(string url) { string textContent = ""; using (var client = new System.Net.WebClient()) { try { textContent = client.DownloadString(url); // 通过 DownloadString 方法获取网页内容 } catch (Exception ex) { function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "获取网络文件内容异常"); } } return textContent; } #endregion #region 测试创客Id public static int[] testids = { }; #endregion #region 数据库结构 public static Dictionary> BsTables = new Dictionary>(); #endregion } }