CommonUtil.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using IPTools.Core;
  7. using Magicodes.ExporterAndImporter.Core.Models;
  8. using System.Xml;
  9. using System.Xml.Linq;
  10. using System.Xml.Serialization;
  11. using UAParser;
  12. namespace Admin.NET.Core;
  13. /// <summary>
  14. /// 通用工具类
  15. /// </summary>
  16. public static class CommonUtil
  17. {
  18. /// <summary>
  19. /// 生成百分数
  20. /// </summary>
  21. /// <param name="PassCount"></param>
  22. /// <param name="allCount"></param>
  23. /// <returns></returns>
  24. public static string ExecPercent(decimal PassCount, decimal allCount)
  25. {
  26. string res = "";
  27. if (allCount > 0)
  28. {
  29. var value = (double)Math.Round(PassCount / allCount * 100, 1);
  30. if (value < 0)
  31. res = Math.Round(value + 5 / Math.Pow(10, 0 + 1), 0, MidpointRounding.AwayFromZero).ToString();
  32. else
  33. res = Math.Round(value, 0, MidpointRounding.AwayFromZero).ToString();
  34. }
  35. if (res == "") res = "0";
  36. return res + "%";
  37. }
  38. /// <summary>
  39. /// 获取服务地址
  40. /// </summary>
  41. /// <returns></returns>
  42. public static string GetLocalhost()
  43. {
  44. string result = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}";
  45. // 代理模式:获取真正的本机地址
  46. // X-Original-Host=原始请求
  47. // X-Forwarded-Server=从哪里转发过来
  48. if (App.HttpContext.Request.Headers.ContainsKey("Origin")) // 配置成完整的路径如(结尾不要带"/"),比如 https://www.abc.com
  49. result = $"{App.HttpContext.Request.Headers["Origin"]}";
  50. else if (App.HttpContext.Request.Headers.ContainsKey("X-Original")) // 配置成完整的路径如(结尾不要带"/"),比如 https://www.abc.com
  51. result = $"{App.HttpContext.Request.Headers["X-Original"]}";
  52. else if (App.HttpContext.Request.Headers.ContainsKey("X-Original-Host"))
  53. result = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Headers["X-Original-Host"]}";
  54. return result;
  55. }
  56. /// <summary>
  57. /// 对象序列化XML
  58. /// </summary>
  59. /// <typeparam name="T"></typeparam>
  60. /// <param name="obj"></param>
  61. /// <returns></returns>
  62. public static string SerializeObjectToXml<T>(T obj)
  63. {
  64. if (obj == null) return string.Empty;
  65. var xs = new XmlSerializer(obj.GetType());
  66. var stream = new MemoryStream();
  67. var setting = new XmlWriterSettings
  68. {
  69. Encoding = new UTF8Encoding(false), // 不包含BOM
  70. Indent = true // 设置格式化缩进
  71. };
  72. using (var writer = XmlWriter.Create(stream, setting))
  73. {
  74. var ns = new XmlSerializerNamespaces();
  75. ns.Add("", ""); // 去除默认命名空间
  76. xs.Serialize(writer, obj, ns);
  77. }
  78. return Encoding.UTF8.GetString(stream.ToArray());
  79. }
  80. /// <summary>
  81. /// 字符串转XML格式
  82. /// </summary>
  83. /// <param name="xmlStr"></param>
  84. /// <returns></returns>
  85. public static XElement SerializeStringToXml(string xmlStr)
  86. {
  87. try
  88. {
  89. return XElement.Parse(xmlStr);
  90. }
  91. catch
  92. {
  93. return null;
  94. }
  95. }
  96. /// <summary>
  97. /// 导出模板Excel
  98. /// </summary>
  99. /// <returns></returns>
  100. public static async Task<IActionResult> ExportExcelTemplate<T>(string fileName = null) where T : class, new()
  101. {
  102. IImporter importer = new ExcelImporter();
  103. var res = await importer.GenerateTemplateBytes<T>();
  104. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = $"{(string.IsNullOrEmpty(fileName) ? typeof(T).Name : fileName)}.xlsx" };
  105. }
  106. /// <summary>
  107. /// 导出数据excel
  108. /// </summary>
  109. /// <returns></returns>
  110. public static async Task<IActionResult> ExportExcelData<T>(ICollection<T> data, string fileName = null) where T : class, new()
  111. {
  112. var export = new ExcelExporter();
  113. var res = await export.ExportAsByteArray<T>(data);
  114. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = $"{(string.IsNullOrEmpty(fileName) ? typeof(T).Name : fileName)}.xlsx" };
  115. }
  116. /// <summary>
  117. /// 导出数据excel,包括字典转换
  118. /// </summary>
  119. /// <returns></returns>
  120. public static async Task<IActionResult> ExportExcelData<TSource, TTarget>(ISugarQueryable<TSource> query, Func<TSource, TTarget, TTarget> action = null)
  121. where TSource : class, new() where TTarget : class, new()
  122. {
  123. var PropMappings = GetExportPropertMap<TSource, TTarget>();
  124. var data = query.ToList();
  125. //相同属性复制值,字典值转换
  126. var result = new List<TTarget>();
  127. foreach (var item in data)
  128. {
  129. var newData = new TTarget();
  130. foreach (var dict in PropMappings)
  131. {
  132. var targeProp = dict.Value.Item3;
  133. if (targeProp != null)
  134. {
  135. var propertyInfo = dict.Value.Item2;
  136. var sourceVal = propertyInfo.GetValue(item, null);
  137. if (sourceVal == null)
  138. {
  139. continue;
  140. }
  141. var map = dict.Value.Item1;
  142. if (map != null && map.ContainsKey(sourceVal))
  143. {
  144. var newVal = map[sourceVal];
  145. targeProp.SetValue(newData, newVal);
  146. }
  147. else
  148. {
  149. if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
  150. {
  151. targeProp.SetValue(newData, sourceVal);
  152. }
  153. else
  154. {
  155. var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
  156. targeProp.SetValue(newData, newVal);
  157. }
  158. }
  159. }
  160. if (action != null)
  161. {
  162. newData = action(item, newData);
  163. }
  164. }
  165. result.Add(newData);
  166. }
  167. var export = new ExcelExporter();
  168. var res = await export.ExportAsByteArray(result);
  169. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = typeof(TTarget).Name + ".xlsx" };
  170. }
  171. /// <summary>
  172. /// 导入数据Excel
  173. /// </summary>
  174. /// <param name="file"></param>
  175. /// <returns></returns>
  176. public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file) where T : class, new()
  177. {
  178. IImporter importer = new ExcelImporter();
  179. var res = await importer.Import<T>(file.OpenReadStream());
  180. var message = string.Empty;
  181. if (res.HasError)
  182. {
  183. if (res.Exception != null)
  184. message += $"\r\n{res.Exception.Message}";
  185. foreach (DataRowErrorInfo drErrorInfo in res.RowErrors)
  186. {
  187. int rowNum = drErrorInfo.RowIndex;
  188. foreach (var item in drErrorInfo.FieldErrors)
  189. message += $"\r\n{item.Key}:{item.Value}(文件第{drErrorInfo.RowIndex}行)";
  190. }
  191. message += "字段缺失:" + string.Join(",", res.TemplateErrors.Select(m => m.RequireColumnName).ToList());
  192. throw Oops.Oh("导入异常:" + message);
  193. }
  194. return res.Data;
  195. }
  196. // 例:List<Dm_ApplyDemo> ls = CommonUtil.ParseList<Dm_ApplyDemoInport, Dm_ApplyDemo>(importResult.Data);
  197. /// <summary>
  198. /// 对象转换 含字典转换
  199. /// </summary>
  200. /// <typeparam name="TSource"></typeparam>
  201. /// <typeparam name="TTarget"></typeparam>
  202. /// <param name="data"></param>
  203. /// <param name="action"></param>
  204. /// <returns></returns>
  205. public static List<TTarget> ParseList<TSource, TTarget>(IEnumerable<TSource> data, Func<TSource, TTarget, TTarget> action = null) where TTarget : new()
  206. {
  207. var propMappings = GetImportPropertMap<TSource, TTarget>();
  208. // 相同属性复制值,字典值转换
  209. var result = new List<TTarget>();
  210. foreach (var item in data)
  211. {
  212. var newData = new TTarget();
  213. foreach (var dict in propMappings)
  214. {
  215. var targeProp = dict.Value.Item3;
  216. if (targeProp != null)
  217. {
  218. var propertyInfo = dict.Value.Item2;
  219. var sourceVal = propertyInfo.GetValue(item, null);
  220. if (sourceVal == null)
  221. continue;
  222. var map = dict.Value.Item1;
  223. if (map != null && map.ContainsKey(sourceVal.ToString()))
  224. {
  225. var newVal = map[sourceVal.ToString()];
  226. targeProp.SetValue(newData, newVal);
  227. }
  228. else
  229. {
  230. if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
  231. {
  232. targeProp.SetValue(newData, sourceVal);
  233. }
  234. else
  235. {
  236. var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
  237. targeProp.SetValue(newData, newVal);
  238. }
  239. }
  240. }
  241. }
  242. if (action != null)
  243. newData = action(item, newData);
  244. if (newData != null)
  245. result.Add(newData);
  246. }
  247. return result;
  248. }
  249. /// <summary>
  250. /// 获取导入属性映射
  251. /// </summary>
  252. /// <typeparam name="TSource"></typeparam>
  253. /// <typeparam name="TTarget"></typeparam>
  254. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  255. private static Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>> GetImportPropertMap<TSource, TTarget>() where TTarget : new()
  256. {
  257. // 整理导入对象的属性名称,<字典数据,原属性信息,目标属性信息>
  258. var propMappings = new Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>>();
  259. var dictService = App.GetService<SqlSugarRepository<SysDictData>>();
  260. var tSourceProps = typeof(TSource).GetProperties().ToList();
  261. var tTargetProps = typeof(TTarget).GetProperties().ToDictionary(m => m.Name);
  262. foreach (var propertyInfo in tSourceProps)
  263. {
  264. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  265. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  266. {
  267. var targetProp = tTargetProps[attrs.TargetPropName];
  268. var mappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((a, b) =>
  269. new JoinQueryInfos(JoinType.Inner, a.Id == b.DictTypeId))
  270. .Where(a => a.Code == attrs.TypeCode)
  271. .Where((a, b) => a.Status == StatusEnum.Enable && b.Status == StatusEnum.Enable)
  272. .Select((a, b) => new
  273. {
  274. Label = b.Value,
  275. Value = b.Code
  276. }).ToList()
  277. .ToDictionary(m => m.Label, m => m.Value.ParseTo(targetProp.PropertyType));
  278. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(mappingValues, propertyInfo, targetProp));
  279. }
  280. else
  281. {
  282. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(
  283. null, propertyInfo, tTargetProps.ContainsKey(propertyInfo.Name) ? tTargetProps[propertyInfo.Name] : null));
  284. }
  285. }
  286. return propMappings;
  287. }
  288. /// <summary>
  289. /// 获取导出属性映射
  290. /// </summary>
  291. /// <typeparam name="TSource"></typeparam>
  292. /// <typeparam name="TTarget"></typeparam>
  293. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  294. private static Dictionary<string, Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>> GetExportPropertMap<TSource, TTarget>() where TTarget : new()
  295. {
  296. // 整理导入对象的属性名称,<字典数据,原属性信息,目标属性信息>
  297. var propMappings = new Dictionary<string, Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>>();
  298. var dictService = App.GetService<SqlSugarRepository<SysDictData>>();
  299. var targetProps = typeof(TTarget).GetProperties().ToList();
  300. var sourceProps = typeof(TSource).GetProperties().ToDictionary(m => m.Name);
  301. foreach (var propertyInfo in targetProps)
  302. {
  303. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  304. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  305. {
  306. var targetProp = sourceProps[attrs.TargetPropName];
  307. var mappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((a, b) =>
  308. new JoinQueryInfos(JoinType.Inner, a.Id == b.DictTypeId))
  309. .Where(a => a.Code == attrs.TypeCode)
  310. .Where((a, b) => a.Status == StatusEnum.Enable && b.Status == StatusEnum.Enable)
  311. .Select((a, b) => new
  312. {
  313. Label = b.Value,
  314. Value = b.Code
  315. }).ToList()
  316. .ToDictionary(m => m.Value.ParseTo(targetProp.PropertyType), m => m.Label);
  317. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>(mappingValues, targetProp, propertyInfo));
  318. }
  319. else
  320. {
  321. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>(
  322. null, sourceProps.ContainsKey(propertyInfo.Name) ? sourceProps[propertyInfo.Name] : null, propertyInfo));
  323. }
  324. }
  325. return propMappings;
  326. }
  327. /// <summary>
  328. /// 获取属性映射
  329. /// </summary>
  330. /// <typeparam name="TTarget"></typeparam>
  331. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  332. private static Dictionary<string, Tuple<string, string>> GetExportDicttMap<TTarget>() where TTarget : new()
  333. {
  334. // 整理导入对象的属性名称,目标属性名,字典Code
  335. var propMappings = new Dictionary<string, Tuple<string, string>>();
  336. var tTargetProps = typeof(TTarget).GetProperties();
  337. foreach (var propertyInfo in tTargetProps)
  338. {
  339. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  340. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  341. {
  342. propMappings.Add(propertyInfo.Name, new Tuple<string, string>(attrs.TargetPropName, attrs.TypeCode));
  343. }
  344. }
  345. return propMappings;
  346. }
  347. /// <summary>
  348. /// 解析IP地址
  349. /// </summary>
  350. /// <param name="ip"></param>
  351. /// <returns></returns>
  352. public static (string ipLocation, double? longitude, double? latitude) GetIpAddress(string ip)
  353. {
  354. try
  355. {
  356. var ipInfo = IpTool.SearchWithI18N(ip); // 国际化查询,默认中文 中文zh-CN、英文en
  357. var addressList = new List<string>() { ipInfo.Country, ipInfo.Province, ipInfo.City, ipInfo.NetworkOperator };
  358. return (string.Join(" ", addressList.Where(u => u != "0" && !string.IsNullOrWhiteSpace(u)).ToList()), ipInfo.Longitude, ipInfo.Latitude); // 去掉0及空并用空格连接
  359. }
  360. catch
  361. {
  362. // 不做处理
  363. }
  364. return ("未知", 0, 0);
  365. }
  366. /// <summary>
  367. /// 获取客户端设备信息(操作系统+浏览器)
  368. /// </summary>
  369. /// <param name="userAgent"></param>
  370. /// <returns></returns>
  371. public static string GetClientDeviceInfo(string userAgent)
  372. {
  373. try
  374. {
  375. if (userAgent != null)
  376. {
  377. var client = Parser.GetDefault().Parse(userAgent);
  378. if (client.Device.IsSpider)
  379. return "爬虫";
  380. return $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}" +
  381. $"|{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
  382. }
  383. }
  384. catch
  385. { }
  386. return "未知";
  387. }
  388. }