CommonUtil.cs 21 KB

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