CommonUtil.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. namespace Admin.NET.Core;
  12. /// <summary>
  13. /// 通用工具类
  14. /// </summary>
  15. public static class CommonUtil
  16. {
  17. /// <summary>
  18. /// 生成百分数
  19. /// </summary>
  20. /// <param name="PassCount"></param>
  21. /// <param name="allCount"></param>
  22. /// <returns></returns>
  23. public static string ExecPercent(decimal PassCount, decimal allCount)
  24. {
  25. string res = "";
  26. if (allCount > 0)
  27. {
  28. var value = (double)Math.Round(PassCount / allCount * 100, 1);
  29. if (value < 0)
  30. res = Math.Round(value + 5 / Math.Pow(10, 0 + 1), 0, MidpointRounding.AwayFromZero).ToString();
  31. else
  32. res = Math.Round(value, 0, MidpointRounding.AwayFromZero).ToString();
  33. }
  34. if (res == "") res = "0";
  35. return res + "%";
  36. }
  37. /// <summary>
  38. /// 获取服务地址
  39. /// </summary>
  40. /// <returns></returns>
  41. public static string GetLocalhost()
  42. {
  43. string result = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}";
  44. // 代理模式:获取真正的本机地址
  45. // X-Original-Host=原始请求
  46. // X-Forwarded-Server=从哪里转发过来
  47. if (App.HttpContext.Request.Headers.ContainsKey("Origin")) // 配置成完整的路径如(结尾不要带"/"),比如 https://www.abc.com
  48. result = $"{App.HttpContext.Request.Headers["Origin"]}";
  49. else if (App.HttpContext.Request.Headers.ContainsKey("X-Original")) // 配置成完整的路径如(结尾不要带"/"),比如 https://www.abc.com
  50. result = $"{App.HttpContext.Request.Headers["X-Original"]}";
  51. else if (App.HttpContext.Request.Headers.ContainsKey("X-Original-Host"))
  52. result = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Headers["X-Original-Host"]}";
  53. return result;
  54. }
  55. /// <summary>
  56. /// 对象序列化XML
  57. /// </summary>
  58. /// <typeparam name="T"></typeparam>
  59. /// <param name="obj"></param>
  60. /// <returns></returns>
  61. public static string SerializeObjectToXml<T>(T obj)
  62. {
  63. if (obj == null) return string.Empty;
  64. var xs = new XmlSerializer(obj.GetType());
  65. var stream = new MemoryStream();
  66. var setting = new XmlWriterSettings
  67. {
  68. Encoding = new UTF8Encoding(false), // 不包含BOM
  69. Indent = true // 设置格式化缩进
  70. };
  71. using (var writer = XmlWriter.Create(stream, setting))
  72. {
  73. var ns = new XmlSerializerNamespaces();
  74. ns.Add("", ""); // 去除默认命名空间
  75. xs.Serialize(writer, obj, ns);
  76. }
  77. return Encoding.UTF8.GetString(stream.ToArray());
  78. }
  79. /// <summary>
  80. /// 字符串转XML格式
  81. /// </summary>
  82. /// <param name="xmlStr"></param>
  83. /// <returns></returns>
  84. public static XElement SerializeStringToXml(string xmlStr)
  85. {
  86. try
  87. {
  88. return XElement.Parse(xmlStr);
  89. }
  90. catch
  91. {
  92. return null;
  93. }
  94. }
  95. /// <summary>
  96. /// 导出模板Excel
  97. /// </summary>
  98. /// <returns></returns>
  99. public static async Task<IActionResult> ExportExcelTemplate<T>(string fileName = null) where T : class, new()
  100. {
  101. IImporter importer = new ExcelImporter();
  102. var res = await importer.GenerateTemplateBytes<T>();
  103. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = $"{(string.IsNullOrEmpty(fileName) ? typeof(T).Name : fileName)}.xlsx" };
  104. }
  105. /// <summary>
  106. /// 导出数据excel
  107. /// </summary>
  108. /// <returns></returns>
  109. public static async Task<IActionResult> ExportExcelData<T>(ICollection<T> data, string fileName = null) where T : class, new()
  110. {
  111. var export = new ExcelExporter();
  112. var res = await export.ExportAsByteArray<T>(data);
  113. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = $"{(string.IsNullOrEmpty(fileName) ? typeof(T).Name : fileName)}.xlsx" };
  114. }
  115. /// <summary>
  116. /// 导出数据excel,包括字典转换
  117. /// </summary>
  118. /// <returns></returns>
  119. public static async Task<IActionResult> ExportExcelData<TSource, TTarget>(ISugarQueryable<TSource> query, Func<TSource, TTarget, TTarget> action = null)
  120. where TSource : class, new() where TTarget : class, new()
  121. {
  122. var PropMappings = GetExportPropertMap<TSource, TTarget>();
  123. var data = query.ToList();
  124. //相同属性复制值,字典值转换
  125. var result = new List<TTarget>();
  126. foreach (var item in data)
  127. {
  128. var newData = new TTarget();
  129. foreach (var dict in PropMappings)
  130. {
  131. var targeProp = dict.Value.Item3;
  132. if (targeProp != null)
  133. {
  134. var propertyInfo = dict.Value.Item2;
  135. var sourceVal = propertyInfo.GetValue(item, null);
  136. if (sourceVal == null)
  137. {
  138. continue;
  139. }
  140. var map = dict.Value.Item1;
  141. if (map != null && map.ContainsKey(sourceVal))
  142. {
  143. var newVal = map[sourceVal];
  144. targeProp.SetValue(newData, newVal);
  145. }
  146. else
  147. {
  148. if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
  149. {
  150. targeProp.SetValue(newData, sourceVal);
  151. }
  152. else
  153. {
  154. var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
  155. targeProp.SetValue(newData, newVal);
  156. }
  157. }
  158. }
  159. if (action != null)
  160. {
  161. newData = action(item, newData);
  162. }
  163. }
  164. result.Add(newData);
  165. }
  166. var export = new ExcelExporter();
  167. var res = await export.ExportAsByteArray(result);
  168. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = typeof(TTarget).Name + ".xlsx" };
  169. }
  170. /// <summary>
  171. /// 导入数据Excel
  172. /// </summary>
  173. /// <param name="file"></param>
  174. /// <returns></returns>
  175. public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file) where T : class, new()
  176. {
  177. IImporter importer = new ExcelImporter();
  178. var res = await importer.Import<T>(file.OpenReadStream());
  179. var message = string.Empty;
  180. if (res.HasError)
  181. {
  182. if (res.Exception != null)
  183. message += $"\r\n{res.Exception.Message}";
  184. foreach (DataRowErrorInfo drErrorInfo in res.RowErrors)
  185. {
  186. int rowNum = drErrorInfo.RowIndex;
  187. foreach (var item in drErrorInfo.FieldErrors)
  188. message += $"\r\n{item.Key}:{item.Value}(文件第{drErrorInfo.RowIndex}行)";
  189. }
  190. message += "\r\n字段缺失:" + string.Join(",", res.TemplateErrors.Select(m => m.RequireColumnName).ToList());
  191. throw Oops.Oh("导入异常:" + message);
  192. }
  193. return res.Data;
  194. }
  195. /// <summary>
  196. /// 导入Excel数据并错误标记
  197. /// </summary>
  198. /// <typeparam name="T"></typeparam>
  199. /// <param name="file"></param>
  200. /// <param name="importResultCallback"></param>
  201. /// <returns></returns>
  202. public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file, Func<ImportResult<T>, ImportResult<T>> importResultCallback = null) where T : class, new()
  203. {
  204. IImporter importer = new ExcelImporter();
  205. var resultStream = new MemoryStream();
  206. var res = await importer.Import<T>(file.OpenReadStream(), resultStream, importResultCallback);
  207. resultStream.Seek(0, SeekOrigin.Begin);
  208. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  209. App.GetRequiredService<SysCacheService>().Remove(CacheConst.KeyExcelTemp + userId);
  210. App.GetRequiredService<SysCacheService>().Set(CacheConst.KeyExcelTemp + userId, resultStream, TimeSpan.FromMinutes(5));
  211. var message = string.Empty;
  212. if (res.HasError)
  213. {
  214. if (res.Exception != null)
  215. message += $"\r\n{res.Exception.Message}";
  216. foreach (DataRowErrorInfo drErrorInfo in res.RowErrors)
  217. {
  218. int rowNum = drErrorInfo.RowIndex;
  219. foreach (var item in drErrorInfo.FieldErrors)
  220. message += $"\r\n{item.Key}:{item.Value}(文件第{drErrorInfo.RowIndex}行)";
  221. }
  222. if (res.TemplateErrors.Count > 0)
  223. message += "\r\n字段缺失:" + string.Join(",", res.TemplateErrors.Select(m => m.RequireColumnName).ToList());
  224. if (message.Length > 200)
  225. message = message.Substring(0, 200) + "...\r\n异常过多,建议下载错误标记文件查看详细错误信息并重新导入。";
  226. throw Oops.Oh("导入异常:" + message);
  227. }
  228. return res.Data;
  229. }
  230. /// <summary>
  231. /// 导入数据Excel
  232. /// </summary>
  233. /// <typeparam name="T"></typeparam>
  234. /// <param name="file"></param>
  235. /// <returns></returns>
  236. public static async Task<List<T>> ImportExcelDataAsync<T>([Required] IFormFile file) where T : class, new()
  237. {
  238. var sysFileService = App.GetRequiredService<SysFileService>();
  239. var newFile = await sysFileService.UploadFile(new FileUploadInput { File = file });
  240. var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, newFile.FilePath!, newFile.Id + newFile.Suffix);
  241. IImporter importer = new ExcelImporter();
  242. var res = await importer.Import<T>(filePath);
  243. // 删除文件
  244. _ = sysFileService.DeleteFile(new DeleteFileInput { Id = newFile.Id });
  245. if (res == null)
  246. throw Oops.Oh("导入数据为空");
  247. if (res.Exception != null)
  248. throw Oops.Oh("导入异常:" + res.Exception);
  249. if (res.TemplateErrors?.Count > 0)
  250. throw Oops.Oh("模板异常:" + res.TemplateErrors.Select(x => $"[{x.RequireColumnName}]{x.Message}").Join("\n"));
  251. return res.Data.ToList();
  252. }
  253. // 例:List<Dm_ApplyDemo> ls = CommonUtil.ParseList<Dm_ApplyDemoInport, Dm_ApplyDemo>(importResult.Data);
  254. /// <summary>
  255. /// 对象转换 含字典转换
  256. /// </summary>
  257. /// <typeparam name="TSource"></typeparam>
  258. /// <typeparam name="TTarget"></typeparam>
  259. /// <param name="data"></param>
  260. /// <param name="action"></param>
  261. /// <returns></returns>
  262. public static List<TTarget> ParseList<TSource, TTarget>(IEnumerable<TSource> data, Func<TSource, TTarget, TTarget> action = null) where TTarget : new()
  263. {
  264. var propMappings = GetImportPropertMap<TSource, TTarget>();
  265. // 相同属性复制值,字典值转换
  266. var result = new List<TTarget>();
  267. foreach (var item in data)
  268. {
  269. var newData = new TTarget();
  270. foreach (var dict in propMappings)
  271. {
  272. var targeProp = dict.Value.Item3;
  273. if (targeProp != null)
  274. {
  275. var propertyInfo = dict.Value.Item2;
  276. var sourceVal = propertyInfo.GetValue(item, null);
  277. if (sourceVal == null)
  278. continue;
  279. var map = dict.Value.Item1;
  280. if (map != null && map.ContainsKey(sourceVal.ToString()))
  281. {
  282. var newVal = map[sourceVal.ToString()];
  283. targeProp.SetValue(newData, newVal);
  284. }
  285. else
  286. {
  287. if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
  288. {
  289. targeProp.SetValue(newData, sourceVal);
  290. }
  291. else
  292. {
  293. var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
  294. targeProp.SetValue(newData, newVal);
  295. }
  296. }
  297. }
  298. }
  299. if (action != null)
  300. newData = action(item, newData);
  301. if (newData != null)
  302. result.Add(newData);
  303. }
  304. return result;
  305. }
  306. /// <summary>
  307. /// 获取导入属性映射
  308. /// </summary>
  309. /// <typeparam name="TSource"></typeparam>
  310. /// <typeparam name="TTarget"></typeparam>
  311. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  312. private static Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>> GetImportPropertMap<TSource, TTarget>() where TTarget : new()
  313. {
  314. // 整理导入对象的属性名称,<字典数据,原属性信息,目标属性信息>
  315. var propMappings = new Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>>();
  316. var dictService = App.GetRequiredService<SqlSugarRepository<SysDictData>>();
  317. var tSourceProps = typeof(TSource).GetProperties().ToList();
  318. var tTargetProps = typeof(TTarget).GetProperties().ToDictionary(u => u.Name);
  319. foreach (var propertyInfo in tSourceProps)
  320. {
  321. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  322. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  323. {
  324. var targetProp = tTargetProps[attrs.TargetPropName];
  325. var mappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((u, a) =>
  326. new JoinQueryInfos(JoinType.Inner, u.Id == a.DictTypeId))
  327. .Where(u => u.Code == attrs.TypeCode)
  328. .Where((u, a) => u.Status == StatusEnum.Enable && a.Status == StatusEnum.Enable)
  329. .Select((u, a) => new
  330. {
  331. Label = a.Value,
  332. Value = a.Code
  333. }).ToList()
  334. .ToDictionary(u => u.Label, u => u.Value.ParseTo(targetProp.PropertyType));
  335. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(mappingValues, propertyInfo, targetProp));
  336. }
  337. else
  338. {
  339. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(
  340. null, propertyInfo, tTargetProps.ContainsKey(propertyInfo.Name) ? tTargetProps[propertyInfo.Name] : null));
  341. }
  342. }
  343. return propMappings;
  344. }
  345. /// <summary>
  346. /// 获取导出属性映射
  347. /// </summary>
  348. /// <typeparam name="TSource"></typeparam>
  349. /// <typeparam name="TTarget"></typeparam>
  350. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  351. private static Dictionary<string, Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>> GetExportPropertMap<TSource, TTarget>() where TTarget : new()
  352. {
  353. // 整理导入对象的属性名称,<字典数据,原属性信息,目标属性信息>
  354. var propMappings = new Dictionary<string, Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>>();
  355. var dictService = App.GetRequiredService<SqlSugarRepository<SysDictData>>();
  356. var targetProps = typeof(TTarget).GetProperties().ToList();
  357. var sourceProps = typeof(TSource).GetProperties().ToDictionary(u => u.Name);
  358. foreach (var propertyInfo in targetProps)
  359. {
  360. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  361. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  362. {
  363. var targetProp = sourceProps[attrs.TargetPropName];
  364. var mappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((u, a) =>
  365. new JoinQueryInfos(JoinType.Inner, u.Id == a.DictTypeId))
  366. .Where(u => u.Code == attrs.TypeCode)
  367. .Where((u, a) => u.Status == StatusEnum.Enable && a.Status == StatusEnum.Enable)
  368. .Select((u, a) => new
  369. {
  370. Label = a.Value,
  371. Value = a.Code
  372. }).ToList()
  373. .ToDictionary(u => u.Value.ParseTo(targetProp.PropertyType), u => u.Label);
  374. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>(mappingValues, targetProp, propertyInfo));
  375. }
  376. else
  377. {
  378. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>(
  379. null, sourceProps.ContainsKey(propertyInfo.Name) ? sourceProps[propertyInfo.Name] : null, propertyInfo));
  380. }
  381. }
  382. return propMappings;
  383. }
  384. /// <summary>
  385. /// 获取属性映射
  386. /// </summary>
  387. /// <typeparam name="TTarget"></typeparam>
  388. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  389. private static Dictionary<string, Tuple<string, string>> GetExportDicttMap<TTarget>() where TTarget : new()
  390. {
  391. // 整理导入对象的属性名称,目标属性名,字典Code
  392. var propMappings = new Dictionary<string, Tuple<string, string>>();
  393. var tTargetProps = typeof(TTarget).GetProperties();
  394. foreach (var propertyInfo in tTargetProps)
  395. {
  396. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  397. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  398. {
  399. propMappings.Add(propertyInfo.Name, new Tuple<string, string>(attrs.TargetPropName, attrs.TypeCode));
  400. }
  401. }
  402. return propMappings;
  403. }
  404. /// <summary>
  405. /// 解析IP地址
  406. /// </summary>
  407. /// <param name="ip"></param>
  408. /// <returns></returns>
  409. public static (string ipLocation, double? longitude, double? latitude) GetIpAddress(string ip)
  410. {
  411. try
  412. {
  413. var ipInfo = IpTool.SearchWithI18N(ip); // 国际化查询,默认中文 中文zh-CN、英文en
  414. var addressList = new List<string>() { ipInfo.Country, ipInfo.Province, ipInfo.City, ipInfo.NetworkOperator };
  415. return (string.Join(" ", addressList.Where(u => u != "0" && !string.IsNullOrWhiteSpace(u)).ToList()), ipInfo.Longitude, ipInfo.Latitude); // 去掉0及空并用空格连接
  416. }
  417. catch
  418. {
  419. // 不做处理
  420. }
  421. return ("未知", 0, 0);
  422. }
  423. /// <summary>
  424. /// 获取客户端设备信息(操作系统+浏览器)
  425. /// </summary>
  426. /// <param name="userAgent"></param>
  427. /// <returns></returns>
  428. public static string GetClientDeviceInfo(string userAgent)
  429. {
  430. try
  431. {
  432. if (userAgent != null)
  433. {
  434. var client = Parser.GetDefault().Parse(userAgent);
  435. if (client.Device.IsSpider)
  436. return "爬虫";
  437. return $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}" +
  438. $"|{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
  439. }
  440. }
  441. catch
  442. { }
  443. return "未知";
  444. }
  445. }