// Admin.NET 项目的版æƒã€å•†æ ‡ã€ä¸“利和其他相关æƒåˆ©å‡å—ç›¸åº”æ³•å¾‹æ³•è§„çš„ä¿æŠ¤ã€‚ä½¿ç”¨æœ¬é¡¹ç›®åº”éµå®ˆç›¸å…³æ³•律法规和许å¯è¯çš„è¦æ±‚。
//
// 本项目主è¦éµå¾ª MIT 许å¯è¯å’Œ Apache 许å¯è¯ï¼ˆç‰ˆæœ¬ 2.0)进行分å‘和使用。许å¯è¯ä½äºŽæºä»£ç æ ‘æ ¹ç›®å½•ä¸çš„ LICENSE-MIT å’Œ LICENSE-APACHE 文件。
//
// ä¸å¾—利用本项目从事å±å®³å›½å®¶å®‰å…¨ã€æ‰°ä¹±ç¤¾ä¼šç§©åºã€ä¾µçŠ¯ä»–äººåˆæ³•æƒç›Šç‰æ³•å¾‹æ³•è§„ç¦æ¢çš„æ´»åЍï¼ä»»ä½•基于本项目二次开å‘è€Œäº§ç”Ÿçš„ä¸€åˆ‡æ³•å¾‹çº çº·å’Œè´£ä»»ï¼Œæˆ‘ä»¬ä¸æ‰¿æ‹…任何责任ï¼
using IPTools.Core;
using Magicodes.ExporterAndImporter.Core.Models;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace Admin.NET.Core;
/// <summary>
/// 通用工具类
/// </summary>
public static class CommonUtil
{
/// <summary>
/// 生æˆç™¾åˆ†æ•°
/// </summary>
/// <param name="PassCount"></param>
/// <param name="allCount"></param>
/// <returns></returns>
public static string ExecPercent(decimal PassCount, decimal allCount)
{
string res = "";
if (allCount > 0)
{
var value = (double)Math.Round(PassCount / allCount * 100, 1);
if (value < 0)
res = Math.Round(value + 5 / Math.Pow(10, 0 + 1), 0, MidpointRounding.AwayFromZero).ToString();
else
res = Math.Round(value, 0, MidpointRounding.AwayFromZero).ToString();
}
if (res == "") res = "0";
return res + "%";
}
/// <summary>
/// èŽ·å–æœåŠ¡åœ°å€
/// </summary>
/// <returns></returns>
public static string GetLocalhost()
{
string result = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}";
// ä»£ç†æ¨¡å¼ï¼šèŽ·å–真æ£çš„æœ¬æœºåœ°å€
// X-Original-Host=原始请求
// X-Forwarded-Server=从哪里转å‘过æ¥
if (App.HttpContext.Request.Headers.ContainsKey("Origin")) // é…ç½®æˆå®Œæ•´çš„路径如(结尾ä¸è¦å¸¦"/"),比如 https://www.abc.com
result = $"{App.HttpContext.Request.Headers["Origin"]}";
else if (App.HttpContext.Request.Headers.ContainsKey("X-Original")) // é…ç½®æˆå®Œæ•´çš„路径如(结尾ä¸è¦å¸¦"/"),比如 https://www.abc.com
result = $"{App.HttpContext.Request.Headers["X-Original"]}";
else if (App.HttpContext.Request.Headers.ContainsKey("X-Original-Host"))
result = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Headers["X-Original-Host"]}";
return result;
}
/// <summary>
/// 对象åºåˆ—化XML
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string SerializeObjectToXml<T>(T obj)
{
if (obj == null) return string.Empty;
var xs = new XmlSerializer(obj.GetType());
var stream = new MemoryStream();
var setting = new XmlWriterSettings
{
Encoding = new UTF8Encoding(false), // ä¸åŒ…å«BOM
Indent = true // è®¾ç½®æ ¼å¼åŒ–缩进
};
using (var writer = XmlWriter.Create(stream, setting))
{
var ns = new XmlSerializerNamespaces();
ns.Add("", ""); // 去除默认命å空间
xs.Serialize(writer, obj, ns);
}
return Encoding.UTF8.GetString(stream.ToArray());
}
/// <summary>
/// å—符串转XMLæ ¼å¼
/// </summary>
/// <param name="xmlStr"></param>
/// <returns></returns>
public static XElement SerializeStringToXml(string xmlStr)
{
try
{
return XElement.Parse(xmlStr);
}
catch
{
return null;
}
}
/// <summary>
/// 导出模æ¿Excel
/// </summary>
/// <returns></returns>
public static async Task<IActionResult> ExportExcelTemplate<T>(string fileName = null) where T : class, new()
{
IImporter importer = new ExcelImporter();
var res = await importer.GenerateTemplateBytes<T>();
return new FileContentResult(res, "application/octet-stream") { FileDownloadName = $"{(string.IsNullOrEmpty(fileName) ? typeof(T).Name : fileName)}.xlsx" };
}
/// <summary>
/// 导出数æ®excel
/// </summary>
/// <returns></returns>
public static async Task<IActionResult> ExportExcelData<T>(ICollection<T> data, string fileName = null) where T : class, new()
{
var export = new ExcelExporter();
var res = await export.ExportAsByteArray<T>(data);
return new FileContentResult(res, "application/octet-stream") { FileDownloadName = $"{(string.IsNullOrEmpty(fileName) ? typeof(T).Name : fileName)}.xlsx" };
}
/// <summary>
/// 导出数æ®excel,包括å—典转æ¢
/// </summary>
/// <returns></returns>
public static async Task<IActionResult> ExportExcelData<TSource, TTarget>(ISugarQueryable<TSource> query, Func<TSource, TTarget, TTarget> action = null)
where TSource : class, new() where TTarget : class, new()
{
var PropMappings = GetExportPropertMap<TSource, TTarget>();
var data = query.ToList();
//相åŒå±žæ€§å¤åˆ¶å€¼ï¼Œå—典值转æ¢
var result = new List<TTarget>();
foreach (var item in data)
{
var newData = new TTarget();
foreach (var dict in PropMappings)
{
var targeProp = dict.Value.Item3;
if (targeProp != null)
{
var propertyInfo = dict.Value.Item2;
var sourceVal = propertyInfo.GetValue(item, null);
if (sourceVal == null)
{
continue;
}
var map = dict.Value.Item1;
if (map != null && map.ContainsKey(sourceVal))
{
var newVal = map[sourceVal];
targeProp.SetValue(newData, newVal);
}
else
{
if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
{
targeProp.SetValue(newData, sourceVal);
}
else
{
var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
targeProp.SetValue(newData, newVal);
}
}
}
if (action != null)
{
newData = action(item, newData);
}
}
result.Add(newData);
}
var export = new ExcelExporter();
var res = await export.ExportAsByteArray(result);
return new FileContentResult(res, "application/octet-stream") { FileDownloadName = typeof(TTarget).Name + ".xlsx" };
}
/// <summary>
/// 导入数æ®Excel
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file) where T : class, new()
{
IImporter importer = new ExcelImporter();
var res = await importer.Import<T>(file.OpenReadStream());
var message = string.Empty;
if (res.HasError)
{
if (res.Exception != null)
message += $"\r\n{res.Exception.Message}";
foreach (DataRowErrorInfo drErrorInfo in res.RowErrors)
{
int rowNum = drErrorInfo.RowIndex;
foreach (var item in drErrorInfo.FieldErrors)
message += $"\r\n{item.Key}:{item.Value}(文件第{drErrorInfo.RowIndex}行)";
}
message += "\r\nå—æ®µç¼ºå¤±ï¼š" + string.Join(",", res.TemplateErrors.Select(m => m.RequireColumnName).ToList());
throw Oops.Oh("导入异常:" + message);
}
return res.Data;
}
/// <summary>
/// 导入Excelæ•°æ®å¹¶é”™è¯¯æ ‡è®°
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="file"></param>
/// <param name="importResultCallback"></param>
/// <returns></returns>
public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file, Func<ImportResult<T>, ImportResult<T>> importResultCallback = null) where T : class, new()
{
IImporter importer = new ExcelImporter();
var resultStream = new MemoryStream();
var res = await importer.Import<T>(file.OpenReadStream(), resultStream, importResultCallback);
resultStream.Seek(0, SeekOrigin.Begin);
var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
App.GetRequiredService<SysCacheService>().Remove(CacheConst.KeyExcelTemp + userId);
App.GetRequiredService<SysCacheService>().Set(CacheConst.KeyExcelTemp + userId, resultStream, TimeSpan.FromMinutes(5));
var message = string.Empty;
if (res.HasError)
{
if (res.Exception != null)
message += $"\r\n{res.Exception.Message}";
foreach (DataRowErrorInfo drErrorInfo in res.RowErrors)
{
int rowNum = drErrorInfo.RowIndex;
foreach (var item in drErrorInfo.FieldErrors)
message += $"\r\n{item.Key}:{item.Value}(文件第{drErrorInfo.RowIndex}行)";
}
if (res.TemplateErrors.Count > 0)
message += "\r\nå—æ®µç¼ºå¤±ï¼š" + string.Join(",", res.TemplateErrors.Select(m => m.RequireColumnName).ToList());
if (message.Length > 200)
message = message.Substring(0, 200) + "...\r\nå¼‚å¸¸è¿‡å¤šï¼Œå»ºè®®ä¸‹è½½é”™è¯¯æ ‡è®°æ–‡ä»¶æŸ¥çœ‹è¯¦ç»†é”™è¯¯ä¿¡æ¯å¹¶é‡æ–°å¯¼å…¥ã€‚";
throw Oops.Oh("导入异常:" + message);
}
return res.Data;
}
// 例:List<Dm_ApplyDemo> ls = CommonUtil.ParseList<Dm_ApplyDemoInport, Dm_ApplyDemo>(importResult.Data);
/// <summary>
/// å¯¹è±¡è½¬æ¢ å«å—典转æ¢
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TTarget"></typeparam>
/// <param name="data"></param>
/// <param name="action"></param>
/// <returns></returns>
public static List<TTarget> ParseList<TSource, TTarget>(IEnumerable<TSource> data, Func<TSource, TTarget, TTarget> action = null) where TTarget : new()
{
var propMappings = GetImportPropertMap<TSource, TTarget>();
// 相åŒå±žæ€§å¤åˆ¶å€¼ï¼Œå—典值转æ¢
var result = new List<TTarget>();
foreach (var item in data)
{
var newData = new TTarget();
foreach (var dict in propMappings)
{
var targeProp = dict.Value.Item3;
if (targeProp != null)
{
var propertyInfo = dict.Value.Item2;
var sourceVal = propertyInfo.GetValue(item, null);
if (sourceVal == null)
continue;
var map = dict.Value.Item1;
if (map != null && map.ContainsKey(sourceVal.ToString()))
{
var newVal = map[sourceVal.ToString()];
targeProp.SetValue(newData, newVal);
}
else
{
if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
{
targeProp.SetValue(newData, sourceVal);
}
else
{
var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
targeProp.SetValue(newData, newVal);
}
}
}
}
if (action != null)
newData = action(item, newData);
if (newData != null)
result.Add(newData);
}
return result;
}
/// <summary>
/// 获å–å¯¼å…¥å±žæ€§æ˜ å°„
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TTarget"></typeparam>
/// <returns>æ•´ç†å¯¼å…¥å¯¹è±¡çš„ 属性å称, å—典数æ®ï¼ŒåŽŸå±žæ€§ä¿¡æ¯ï¼Œç›®æ ‡å±žæ€§ä¿¡æ¯ </returns>
private static Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>> GetImportPropertMap<TSource, TTarget>() where TTarget : new()
{
// æ•´ç†å¯¼å…¥å¯¹è±¡çš„属性å称,<å—典数æ®ï¼ŒåŽŸå±žæ€§ä¿¡æ¯ï¼Œç›®æ ‡å±žæ€§ä¿¡æ¯>
var propMappings = new Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>>();
var dictService = App.GetRequiredService<SqlSugarRepository<SysDictData>>();
var tSourceProps = typeof(TSource).GetProperties().ToList();
var tTargetProps = typeof(TTarget).GetProperties().ToDictionary(u => u.Name);
foreach (var propertyInfo in tSourceProps)
{
var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
{
var targetProp = tTargetProps[attrs.TargetPropName];
var mappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((u, a) =>
new JoinQueryInfos(JoinType.Inner, u.Id == a.DictTypeId))
.Where(u => u.Code == attrs.TypeCode)
.Where((u, a) => u.Status == StatusEnum.Enable && a.Status == StatusEnum.Enable)
.Select((u, a) => new
{
Label = a.Value,
Value = a.Code
}).ToList()
.ToDictionary(u => u.Label, u => u.Value.ParseTo(targetProp.PropertyType));
propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(mappingValues, propertyInfo, targetProp));
}
else
{
propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(
null, propertyInfo, tTargetProps.ContainsKey(propertyInfo.Name) ? tTargetProps[propertyInfo.Name] : null));
}
}
return propMappings;
}
/// <summary>
/// 获å–å¯¼å‡ºå±žæ€§æ˜ å°„
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TTarget"></typeparam>
/// <returns>æ•´ç†å¯¼å…¥å¯¹è±¡çš„ 属性å称, å—典数æ®ï¼ŒåŽŸå±žæ€§ä¿¡æ¯ï¼Œç›®æ ‡å±žæ€§ä¿¡æ¯ </returns>
private static Dictionary<string, Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>> GetExportPropertMap<TSource, TTarget>() where TTarget : new()
{
// æ•´ç†å¯¼å…¥å¯¹è±¡çš„属性å称,<å—典数æ®ï¼ŒåŽŸå±žæ€§ä¿¡æ¯ï¼Œç›®æ ‡å±žæ€§ä¿¡æ¯>
var propMappings = new Dictionary<string, Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>>();
var dictService = App.GetRequiredService<SqlSugarRepository<SysDictData>>();
var targetProps = typeof(TTarget).GetProperties().ToList();
var sourceProps = typeof(TSource).GetProperties().ToDictionary(u => u.Name);
foreach (var propertyInfo in targetProps)
{
var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
{
var targetProp = sourceProps[attrs.TargetPropName];
var mappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((u, a) =>
new JoinQueryInfos(JoinType.Inner, u.Id == a.DictTypeId))
.Where(u => u.Code == attrs.TypeCode)
.Where((u, a) => u.Status == StatusEnum.Enable && a.Status == StatusEnum.Enable)
.Select((u, a) => new
{
Label = a.Value,
Value = a.Code
}).ToList()
.ToDictionary(u => u.Value.ParseTo(targetProp.PropertyType), u => u.Label);
propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>(mappingValues, targetProp, propertyInfo));
}
else
{
propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>(
null, sourceProps.ContainsKey(propertyInfo.Name) ? sourceProps[propertyInfo.Name] : null, propertyInfo));
}
}
return propMappings;
}
/// <summary>
/// 获å–å±žæ€§æ˜ å°„
/// </summary>
/// <typeparam name="TTarget"></typeparam>
/// <returns>æ•´ç†å¯¼å…¥å¯¹è±¡çš„ 属性å称, å—典数æ®ï¼ŒåŽŸå±žæ€§ä¿¡æ¯ï¼Œç›®æ ‡å±žæ€§ä¿¡æ¯ </returns>
private static Dictionary<string, Tuple<string, string>> GetExportDicttMap<TTarget>() where TTarget : new()
{
// æ•´ç†å¯¼å…¥å¯¹è±¡çš„属性åç§°ï¼Œç›®æ ‡å±žæ€§å,å—å…¸Code
var propMappings = new Dictionary<string, Tuple<string, string>>();
var tTargetProps = typeof(TTarget).GetProperties();
foreach (var propertyInfo in tTargetProps)
{
var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
{
propMappings.Add(propertyInfo.Name, new Tuple<string, string>(attrs.TargetPropName, attrs.TypeCode));
}
}
return propMappings;
}
/// <summary>
/// è§£æžIP地å€
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static (string ipLocation, double? longitude, double? latitude) GetIpAddress(string ip)
{
try
{
var ipInfo = IpTool.SearchWithI18N(ip); // å›½é™…åŒ–æŸ¥è¯¢ï¼Œé»˜è®¤ä¸æ–‡ 䏿–‡zh-CNã€è‹±æ–‡en
var addressList = new List<string>() { ipInfo.Country, ipInfo.Province, ipInfo.City, ipInfo.NetworkOperator };
return (string.Join(" ", addressList.Where(u => u != "0" && !string.IsNullOrWhiteSpace(u)).ToList()), ipInfo.Longitude, ipInfo.Latitude); // 去掉0åŠç©ºå¹¶ç”¨ç©ºæ ¼è¿žæŽ¥
}
catch
{
// ä¸åšå¤„ç†
}
return ("未知", 0, 0);
}
/// <summary>
/// 获å–客户端设备信æ¯ï¼ˆæ“作系统+æµè§ˆå™¨ï¼‰
/// </summary>
/// <param name="userAgent"></param>
/// <returns></returns>
public static string GetClientDeviceInfo(string userAgent)
{
try
{
if (userAgent != null)
{
var client = Parser.GetDefault().Parse(userAgent);
if (client.Device.IsSpider)
return "爬虫";
return $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}" +
$"|{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
}
}
catch
{ }
return "未知";
}
}