From 870aa2039a13939ec68974e9f843da28b4d9b1a0 Mon Sep 17 00:00:00 2001 From: MarvelTiter Date: Fri, 29 May 2026 15:37:58 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E5=A4=87=E4=BB=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SoapRequestHelper.csproj | 1 + src/SoapRequestHelper/SoapResponse.cs | 63 +++++++++++++++---- src/Toolkit/Toolkit.csproj | 3 +- 3 files changed, 53 insertions(+), 14 deletions(-) diff --git a/src/SoapRequestHelper/SoapRequestHelper.csproj b/src/SoapRequestHelper/SoapRequestHelper.csproj index 749f285..96a8bf0 100644 --- a/src/SoapRequestHelper/SoapRequestHelper.csproj +++ b/src/SoapRequestHelper/SoapRequestHelper.csproj @@ -12,6 +12,7 @@ True True nuget.md + true diff --git a/src/SoapRequestHelper/SoapResponse.cs b/src/SoapRequestHelper/SoapResponse.cs index 67d5467..c533cef 100644 --- a/src/SoapRequestHelper/SoapResponse.cs +++ b/src/SoapRequestHelper/SoapResponse.cs @@ -232,6 +232,9 @@ private static DataTable CreateDataTable(IEnumerable schema, IEnumerab return dt; } +#if NET8_0_OR_GREATER + [return: System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields)] +#endif private static Type ConvertElementType(string type) { return type switch @@ -245,10 +248,10 @@ private static Type ConvertElementType(string type) _ => typeof(string), }; } - static readonly ConcurrentDictionary tryParseCache = []; + private static object? Parse(string? input, Type type) { - if ( string.IsNullOrEmpty(input)) + if (string.IsNullOrEmpty(input)) { return default; } @@ -257,20 +260,54 @@ private static Type ConvertElementType(string type) return input.Trim(); } type = Nullable.GetUnderlyingType(type) ?? type; - var method = tryParseCache.GetOrAdd(type, t => - { - return t.GetMethod("TryParse", [typeof(string), t.MakeByRefType()]); - }); - if (method == null) + + if (TryParse(input, type, out var value)) { - return default; + return value; } - object?[] parameters = [input, default]; - var r = method.Invoke(null, parameters); - if (r is bool b && b == true) + + return default; + + static bool TryParse(string text, Type type, out object? value) { - return parameters[1]; + if (type == typeof(DateTime)) + { + _ = DateTime.TryParse(text, out var v); + value = v; + return true; + } + else if (type == typeof(bool)) + { + _ = bool.TryParse(text, out var v); + value = v; + return true; + } + else if (type == typeof(int)) + { + _ = int.TryParse(text, out var v); + value = v; + return true; + } + else if (type == typeof(decimal)) + { + _ = decimal.TryParse(text, out var v); + value = v; + return true; + } + else if (type == typeof(long)) + { + _ = long.TryParse(text, out var v); + value = v; + return true; + } + else if (type == typeof(short)) + { + _ = short.TryParse(text, out var v); + value = v; + return true; + } + value = default; + return false; } - return default; } } \ No newline at end of file diff --git a/src/Toolkit/Toolkit.csproj b/src/Toolkit/Toolkit.csproj index 9f57003..b35f195 100644 --- a/src/Toolkit/Toolkit.csproj +++ b/src/Toolkit/Toolkit.csproj @@ -1,7 +1,7 @@  - net462;net6.0;net8.0 + net462;net6.0;net8.0;net10.0 disable True MarvelTiter @@ -13,6 +13,7 @@ latest enable True + true From f31c49919c809854f66189a47ca08342e3c8d126 Mon Sep 17 00:00:00 2001 From: MarvelTiter Date: Tue, 2 Jun 2026 15:41:05 +0800 Subject: [PATCH 2/2] aot --- Test/TestWeb/Components/Pages/Home.razor | 34 +- ...64\346\226\260\346\227\245\345\277\227.md" | 3 + .../DataTableExtension/DataTableBuilder.cs | 131 +++--- .../DataTableExtension/DataTableHelper.cs | 245 +++++++---- .../DataTableExtension/MapFromExpression.cs | 180 ++++---- .../DataTableExtension/TableExpressionBase.cs | 67 +-- src/Toolkit/EnumExtensions/EnumHelper.cs | 40 +- .../ExpressionHelper/DataTypeConvert.cs | 271 ++++++------ .../ExpressionHelper/ExpressionCombine.cs | 50 +++ src/Toolkit/FrequencyGuard/Debounce.cs | 150 +++++++ src/Toolkit/FrequencyGuard/Throttle.cs | 158 +++++++ src/Toolkit/HttpHelper/ISoapServiceManager.cs | 41 +- src/Toolkit/HttpHelper/SoapFaultException.cs | 15 + src/Toolkit/HttpHelper/SoapResponse.cs | 408 +++++++++--------- .../HttpHelper/SoapServiceConfiguration.cs | 2 + src/Toolkit/HttpHelper/SoapServiceManager.cs | 44 +- src/Toolkit/HttpHelper/SoapVersion.cs | 17 +- src/Toolkit/LogTool/ConsoleLogger.cs | 36 +- src/Toolkit/LogTool/DatabaseLogger.cs | 70 +-- .../LogTool/DbLogger/DbLoggerProvider.cs | 2 + .../LogTool/DbLogger/DbLoggerSetting.cs | 21 +- src/Toolkit/LogTool/DbLogger/IDbLogger.cs | 11 +- .../LogTool/DbLogger/InternalDbLogger.cs | 93 ++-- src/Toolkit/LogTool/DebugLogger.cs | 33 +- .../FileLogger/DeleteLogFileService.cs | 61 ++- .../LogTool/FileLogger/FileLoggerProvider.cs | 77 ++-- .../LogTool/FileLogger/FileLoggerSetting.cs | 51 +-- .../LogTool/FileLogger/InternalFileLogger.cs | 2 + src/Toolkit/LogTool/ISimpleLogger.cs | 12 +- src/Toolkit/LogTool/LocalFileLogger.cs | 211 ++++----- .../LogTool/LogExtension/InternalLogger.cs | 92 ++-- .../LogTool/LogExtension/SimpleLogProvider.cs | 92 ++-- src/Toolkit/LogTool/LogInfo.cs | 150 +++---- src/Toolkit/LogTool/Logger.cs | 117 ++--- src/Toolkit/LogTool/LoggerSetting.cs | 3 +- src/Toolkit/LogTool/SerivceExtension.cs | 5 +- src/Toolkit/LogTool/SimpleLogLevel.cs | 7 +- src/Toolkit/LogTool/SimpleLogger.cs | 4 +- src/Toolkit/Machine/CpuHelper.cs | 5 +- src/Toolkit/Machine/DiskHelper.cs | 22 +- src/Toolkit/Machine/MemoryHelper.cs | 17 +- src/Toolkit/Machine/SysHelper.cs | 150 ++++--- .../CreateExpression.ClassMap.cs | 134 +++--- .../CreateExpression.CollectionMap.cs | 228 +++++----- .../CreateExpression.FromDictionary.cs | 81 ++-- .../CreateExpression.ToDictionary.cs | 72 ++-- .../Mapper/ExpressionCore/CreateExpression.cs | 86 ++-- .../Extensions/MapperServiceExtension.cs | 34 +- src/Toolkit/Mapper/MapInfo.cs | 39 +- src/Toolkit/Mapper/MapRuleProvider.cs | 69 +-- src/Toolkit/Mapper/Mapper.cs | 152 +++---- src/Toolkit/Mapper/MapperConfig.cs | 98 ++--- src/Toolkit/Mapper/MapperConfigProvider.cs | 19 +- src/Toolkit/Mapper/MapperExtensions.cs | 88 ++-- src/Toolkit/Mapper/MappingProfile.cs | 97 +++-- src/Toolkit/Mapper/MappingRule.cs | 140 +++--- src/Toolkit/Mapper/Profiles.cs | 32 +- .../MemberInfoExtension.cs | 365 ++++++++++------ .../StringExtension/StringExtensions.cs | 63 ++- src/Toolkit/Toolkit.csproj | 2 +- .../TypeConvertHelper/ObjectConvertHelper.cs | 40 +- .../TypeConvertHelper/StringConvertHelper.cs | 70 +-- src/Toolkit/TypeExtensions/TypeExtensions.cs | 138 ++++-- src/Toolkit/XmlHelper/XmlString.cs | 7 +- src/Toolkit/XmlHelper/XmlStringExtensions.cs | 87 ++-- 65 files changed, 3111 insertions(+), 2230 deletions(-) create mode 100644 src/Toolkit/FrequencyGuard/Debounce.cs create mode 100644 src/Toolkit/FrequencyGuard/Throttle.cs diff --git a/Test/TestWeb/Components/Pages/Home.razor b/Test/TestWeb/Components/Pages/Home.razor index 9ec490f..dae7f54 100644 --- a/Test/TestWeb/Components/Pages/Home.razor +++ b/Test/TestWeb/Components/Pages/Home.razor @@ -2,12 +2,15 @@ @using System.Diagnostics.CodeAnalysis @using LoggerProviderExtensions.HubLogger @using System.Text +@using MT.Toolkit @implements IAsyncDisposable Home
@logContent.ToString()
+ + Welcome to your new app. @code { [Inject, NotNull] ILogger? Logger { get; set; } @@ -18,33 +21,42 @@ Welcome to your new app. base.OnInitialized(); // _ = StartFetchLog(); Channel.OnLog += HandleLog; + debounce = Debounce.Create(Log2, 1000); + throttle = Throttle.Create(Log2, 1000); } private void HandleLog(LoggerProviderExtensions.StructuredLogEntry entry) { logContent.AppendLine($"{entry.Category}: {entry.MessageTemplate}"); - Console.WriteLine($"{entry.Category}: {entry.MessageTemplate}"); InvokeAsync(StateHasChanged); } - // private async Task StartFetchLog() - // { - // await foreach (var item in Channel.LogEntries) - // { - // logContent.AppendLine($"{item.Category}: {item.MessageTemplate}"); - // Console.WriteLine($"{item.Category}: {item.MessageTemplate}"); - // StateHasChanged(); - // } - // } - private void Log() { Logger.LogInformation("This is a log message at {Time}", DateTime.Now); } + private void Log2(string type) + { + Logger.LogInformation("{type} log at {Time}", type, DateTime.Now); + } + + private Debounce? debounce; + private Throttle? throttle; + + private async Task DebounceTest() + { + _ = debounce!.InvokeAsync("DebounceTest"); + } + private async Task ThrottleTest() + { + _ = throttle!.InvokeAsync("ThrottleTest"); + } public ValueTask DisposeAsync() { Channel.OnLog -= HandleLog; + debounce!.Dispose(); + throttle!.Dispose(); return ValueTask.CompletedTask; } } \ No newline at end of file diff --git "a/doc/\346\233\264\346\226\260\346\227\245\345\277\227.md" "b/doc/\346\233\264\346\226\260\346\227\245\345\277\227.md" index bc21d44..a755658 100644 --- "a/doc/\346\233\264\346\226\260\346\227\245\345\277\227.md" +++ "b/doc/\346\233\264\346\226\260\346\227\245\345\277\227.md" @@ -1,5 +1,8 @@ ## 版本功能更新日志 +### v2026.06.02.1 +- ⚡️支持AOT编译 + ### v2.1.9.0 - ⚡️移除Mapper相关代码 -> 使用`AutoGenMapperGenerator`代替 diff --git a/src/Toolkit/DataTableExtension/DataTableBuilder.cs b/src/Toolkit/DataTableExtension/DataTableBuilder.cs index eab2ecb..fda40cb 100644 --- a/src/Toolkit/DataTableExtension/DataTableBuilder.cs +++ b/src/Toolkit/DataTableExtension/DataTableBuilder.cs @@ -1,76 +1,81 @@ using System; using System.Collections.Generic; using System.Data; +using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; -namespace MT.Toolkit.DataTableExtension +namespace MT.Toolkit.DataTableExtension; + +internal static class DataTableBuilder< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] +#endif +T> { - public static class DataTableBuilder - { - private static Func? func; + private static Func? func; - public static Func Build(DataColumnCollection dataColumn, bool mapAll) - { - if (func != null) return func; - func = CreateFunc(typeof(T), dataColumn, mapAll); - return func; - } + public static Func Build(DataColumnCollection dataColumn, bool mapAll) + { + if (func != null) return func; + func = CreateFunc(dataColumn, mapAll); + return func; + } - static Func CreateFunc(Type tarType, DataColumnCollection cols, bool mapAll) - { - // Datarow row; - ParameterExpression rowExp = Expression.Parameter(typeof(DataRow), "row"); - List bindings = new List(); - // fields - var fields = tarType.GetFields(BindingFlags.Public | BindingFlags.Instance); - foreach (FieldInfo field in fields) - { - void work() - { - if (cols.Contains(field.Name)) - { - DataColumn col = cols[field.Name]!; - var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, field.FieldType); - MemberAssignment memberAssignment = Expression.Bind(field, valueExp); - bindings.Add(memberAssignment); - return; - } - if (mapAll) - { - throw new ArgumentException($"Property {field.Name} is not matched by any column in datatable"); - } - } - work(); - } + static Func CreateFunc(DataColumnCollection cols, bool mapAll) + { + Type tarType = typeof(T); + // Datarow row; + ParameterExpression rowExp = Expression.Parameter(typeof(DataRow), "row"); + List bindings = []; + // fields + var fields = tarType.GetFields(BindingFlags.Public | BindingFlags.Instance); + foreach (FieldInfo field in fields) + { + void work() + { + if (cols.Contains(field.Name)) + { + DataColumn col = cols[field.Name]!; + var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, field.FieldType); + MemberAssignment memberAssignment = Expression.Bind(field, valueExp); + bindings.Add(memberAssignment); + return; + } + if (mapAll) + { + throw new ArgumentException($"Property {field.Name} is not matched by any column in datatable"); + } + } + work(); + } - // properties - var props = tarType.GetProperties(BindingFlags.Public | BindingFlags.Instance); - foreach (PropertyInfo prop in props) - { - void work() - { - if (cols.Contains(prop.Name)) - { - if (!prop.CanWrite) return; - DataColumn col = cols[prop.Name]!; - var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, prop.PropertyType); - MemberAssignment memberAssignment = Expression.Bind(prop, valueExp); - bindings.Add(memberAssignment); - return; - } - if (mapAll) - { - throw new ArgumentException($"Property {prop.Name} is not matched by any column in datatable"); - } + // properties + var props = tarType.GetProperties(BindingFlags.Public | BindingFlags.Instance); + foreach (PropertyInfo prop in props) + { + void work() + { + if (cols.Contains(prop.Name)) + { + if (!prop.CanWrite) return; + DataColumn col = cols[prop.Name]!; + var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, prop.PropertyType); + MemberAssignment memberAssignment = Expression.Bind(prop, valueExp); + bindings.Add(memberAssignment); + return; + } + if (mapAll) + { + throw new ArgumentException($"Property {prop.Name} is not matched by any column in datatable"); + } - } - work(); - } - MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(tarType), bindings); - var lambda = Expression.Lambda>(memberInitExpression, rowExp); - return lambda.Compile(); - } + } + work(); + } + MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(tarType), bindings); + var lambda = Expression.Lambda>(memberInitExpression, rowExp); + return lambda.Compile(); + } - } } diff --git a/src/Toolkit/DataTableExtension/DataTableHelper.cs b/src/Toolkit/DataTableExtension/DataTableHelper.cs index 7c70f2c..5f29489 100644 --- a/src/Toolkit/DataTableExtension/DataTableHelper.cs +++ b/src/Toolkit/DataTableExtension/DataTableHelper.cs @@ -1,113 +1,214 @@ using System; using System.Collections.Generic; -using System.Text; using System.Data; +using System.Diagnostics.CodeAnalysis; +using System.Text; + +namespace MT.Toolkit.DataTableExtension; -namespace MT.Toolkit.DataTableExtension +/// +/// DataTable帮助类 +/// +public static class DataTableHelper { - public static class DataTableHelper + /// + /// 是否有至少一行数据 + /// + /// + /// + public static bool HasRows(this DataTable? dt) + { + return dt is not null && dt.Rows.Count > 0; + } + + /// + /// 将DataTable转换为可枚举的对象集合 + /// + /// + /// + /// + /// + public static IEnumerable ToEnumerable< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] +#endif + T>(this DataTable? self, bool mapAllFields = false) { - public static bool HasRows(this DataTable dt) + if (self is null) { - return dt != null && dt.Rows.Count > 0; + yield break; } - public static IEnumerable ToEnumerable(this DataTable self, bool mapAllFields = false) + foreach (DataRow row in self.Rows) { - foreach (DataRow row in self.Rows) - { - yield return row.Parse(mapAllFields); - } + yield return row.Parse(mapAllFields); } + } - public static IEnumerable Select(this DataTable self, Func filter, bool mapAllFields = false) + /// + /// 将DataTable转换为可枚举的对象集合,并根据指定的过滤条件进行筛选 + /// + /// + /// + /// + /// + /// + public static IEnumerable Select< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] +#endif + T>(this DataTable self, Func filter, bool mapAllFields = false) + { + foreach (DataRow row in self.Rows) { - foreach (DataRow row in self.Rows) + if (filter.Invoke(row)) { - if (filter.Invoke(row)) - { - yield return row.Parse(mapAllFields); - } + yield return row.Parse(mapAllFields); } } + } - public static IEnumerable Select(this DataTable self, Func filter, bool mapAllFields = false) + /// + /// 将DataTable转换为可枚举的对象集合,并根据指定的过滤条件进行筛选 + /// + /// + /// + /// + /// + /// + public static IEnumerable Select< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] +#endif + T>(this DataTable self, Func filter, bool mapAllFields = false) + { + foreach (DataRow row in self.Rows) { - foreach (DataRow row in self.Rows) + var t = row.Parse(mapAllFields); + if (filter.Invoke(t)) { - var t = row.Parse(mapAllFields); - if (filter.Invoke(t)) - { - yield return t; - } + yield return t; } } + } - public static T Parse(this DataRow row, bool mapAllFields) + /// + /// 转换DataRow为对象 + /// + /// + /// + /// + /// + public static T Parse< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] +#endif + T>(this DataRow row, bool mapAllFields) + { + var columns = row.Table.Columns; + var func = DataTableBuilder.Build(columns, mapAllFields); + return (T)func.Invoke(row); + } + + /// + /// 获取DataRow中指定列的值,并将其转换为指定类型 + /// + /// + /// + /// + /// + /// + public static T GetValue(this DataRow self, string key) + { + if (!self.Table.Columns.Contains(key)) { - var columns = row.Table.Columns; - var func = DataTableBuilder.Build(columns, mapAllFields); - return (T)func.Invoke(row); + throw new ArgumentException($"column {key} is not contains in datatable"); } - public static T GetValue(this DataRow self, string key) + if (self.IsNull(key)) { - if (!self.Table.Columns.Contains(key)) - { - throw new ArgumentException($"column {key} is not contains in datatable"); - } - - if (self.IsNull(key)) - { - return default!; - } - var val = self[key]; - - var undeylying = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); - return (T)Convert.ChangeType(val, undeylying); + return default!; } + var val = self[key]; - public static string? GetValue(this DataRow self, string key) - { - if (!self.Table.Columns.Contains(key)) - { - throw new ArgumentException($"column {key} is not contains in datatable"); - } + var undeylying = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); + return (T)Convert.ChangeType(val, undeylying); + } - if (self.IsNull(key)) - { - return default; - } - var val = self[key]; - return val?.ToString(); + /// + /// 获取DataRow中指定列的值, 并将其转换为字符串 + /// + /// + /// + /// + /// + public static string? GetValue(this DataRow self, string key) + { + if (!self.Table.Columns.Contains(key)) + { + throw new ArgumentException($"column {key} is not contains in datatable"); } - public static void MapFromTable(this T self, DataTable source) + if (self.IsNull(key)) { - var action = MapFromExpression.Build(source.Columns); - action?.Invoke(self, source.Rows[0]); + return default; } + var val = self[key]; + return val?.ToString(); + } + + /// + /// 从DataTable的第一行数据映射到对象实例中 + /// + /// + /// + /// + public static void MapFromTable< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] +#endif + T>(this T self, DataTable? source) + { + if (source is null) + return; + var action = MapFromExpression.Build(source.Columns); + action?.Invoke(self, source.Rows[0]); + } - public static DataRow? FirstRow(this DataTable dt) + /// + /// 获取DataTable的第一行数据 + /// + /// + /// + public static DataRow? FirstRow(this DataTable? dt) + { + if (dt?.Rows.Count == 0) { - if (dt?.Rows.Count == 0) - { - return null; - } - return dt?.Rows[0]; + return null; } + return dt?.Rows[0]; + } - public static DataTable ToDataTable(this IEnumerable datas) + /// + /// 实体集合转换为DataTable + /// + /// + /// + /// + public static DataTable ToDataTable< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] +#endif + T>(this IEnumerable datas) + { + var dt = MapToDataTableExtension.GetDataTable(); + foreach (var item in datas) { - var dt = MapToDataTableExtension.GetDataTable(); - foreach (var item in datas) - { - var row = dt.NewRow(); - MapToDataTableExtension.FillDataRow(item, row); - dt.Rows.Add(row); - } - //dt.Columns.Add() - return dt; + var row = dt.NewRow(); + MapToDataTableExtension.FillDataRow(item, row); + dt.Rows.Add(row); } + //dt.Columns.Add() + return dt; } } diff --git a/src/Toolkit/DataTableExtension/MapFromExpression.cs b/src/Toolkit/DataTableExtension/MapFromExpression.cs index d0fbe7b..6afda4f 100644 --- a/src/Toolkit/DataTableExtension/MapFromExpression.cs +++ b/src/Toolkit/DataTableExtension/MapFromExpression.cs @@ -2,110 +2,136 @@ using System; using System.Collections.Generic; using System.Data; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; -namespace MT.Toolkit.DataTableExtension +namespace MT.Toolkit.DataTableExtension; + +internal static class MapFromExpression< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] +#endif +T> { - public static class MapFromExpression + static Dictionary> actions = new Dictionary>(); + public static Action Build(DataColumnCollection cols) { - static Dictionary> actions = new Dictionary>(); - public static Action Build(DataColumnCollection cols) + var columnNames = from col in cols.Cast() + select col.ColumnName; + var key = string.Join("_", columnNames); + if (actions.TryGetValue(key, out var action)) { - var columnNames = from col in cols.Cast() - select col.ColumnName; - var key = string.Join("_", columnNames); - if (actions.TryGetValue(key, out var action)) - { - return action; - } - action = CreateAction(cols); - actions.Add(key, action); return action; } + action = CreateAction(cols); + actions.Add(key, action); + return action; + } - private static Action CreateAction(DataColumnCollection cols) + private static Action CreateAction(DataColumnCollection cols) + { + ParameterExpression rowExp = Expression.Parameter(typeof(DataRow), "row"); + ParameterExpression tarExp = Expression.Parameter(typeof(T), "tar"); + var tarType = typeof(T); + List body = new List(); + // properties + var props = tarType.GetProperties(BindingFlags.Public | BindingFlags.Instance); + foreach (DataColumn col in cols) { - ParameterExpression rowExp = Expression.Parameter(typeof(DataRow), "row"); - ParameterExpression tarExp = Expression.Parameter(typeof(T), "tar"); - var tarType = typeof(T); - List body = new List(); - // properties - var props = tarType.GetProperties(BindingFlags.Public | BindingFlags.Instance); - foreach (DataColumn col in cols) + var prop = props.FirstOrDefault(p => p.Name.Equals(col.ColumnName, StringComparison.CurrentCultureIgnoreCase)); + if (prop != null && prop.CanWrite && prop.SetMethod is not null) { - var prop = props.FirstOrDefault(p => p.Name.ToLower() == col.ColumnName.ToLower()); - if (prop != null && prop.CanWrite) - { - var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, prop.PropertyType); - MethodCallExpression propAssign = Expression.Call(tarExp, prop.SetMethod, valueExp); - body.Add(propAssign); - } + var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, prop.PropertyType); + MethodCallExpression propAssign = Expression.Call(tarExp, prop.SetMethod, valueExp); + body.Add(propAssign); } - var block = Expression.Block(body); - var lambda = Expression.Lambda>(block, tarExp, rowExp); - return lambda.Compile(); } + var block = Expression.Block(body); + var lambda = Expression.Lambda>(block, tarExp, rowExp); + return lambda.Compile(); + } +} + +internal static class ExpressionUsedMethods +{ + //public static MethodInfo DataColumnAdd = typeof(DataColumnCollection).GetMethod(nameof(DataColumnCollection.Add), [typeof(string), typeof(Type)])!; + //public static MethodInfo DataRowSet = typeof(DataRow).GetMethod("set_Item", [typeof(string), typeof(object)])!; +#if NET8_0_OR_GREATER + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2111", + Justification = "通过 AddColumn 的 columnType 参数上的 DynamicallyAccessedMembers 保证安全,且实际调用时传入的类型已满足保留要求")] +#endif + public static MethodInfo DataColumnAdd = typeof(ExpressionUsedMethods).GetMethod(nameof(AddColumn), [typeof(DataTable), typeof(string), typeof(Type)])!; + public static MethodInfo DataRowSet = typeof(ExpressionUsedMethods).GetMethod(nameof(SetRowValue), [typeof(DataRow), typeof(string), typeof(object)])!; + public static void AddColumn(DataTable dataTable, string columnName, +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields|DynamicallyAccessedMemberTypes.PublicProperties)] +#endif + Type columnType) + { + dataTable.Columns.Add(columnName, columnType); } - internal static class ExpressionUsedMethods + public static void SetRowValue(DataRow row, string columnName, object value) { - public static MethodInfo DataColumnAdd = typeof(DataColumnCollection).GetMethod(nameof(DataColumnCollection.Add), [typeof(string), typeof(Type)])!; - public static MethodInfo DataRowSet = typeof(DataRow).GetMethod("set_Item", [typeof(string), typeof(object)])!; + row[columnName] = value; } +} + +internal static class MapToDataTableExtension< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] +#endif +T> +{ + private static readonly Func createTable; + private static readonly Action fillRow; - internal static class MapToDataTableExtension + static MapToDataTableExtension() { - private static Func createTable; - private static Action fillRow; + createTable = BuildCreateTableFunc(); + fillRow = BuildCreateRowFunc(); + } - static MapToDataTableExtension() - { - createTable = BuildCreateTableFunc(); - fillRow = BuildCreateRowFunc(); - } + internal static DataTable GetDataTable() => createTable.Invoke(); + internal static void FillDataRow(T value, DataRow row) => fillRow.Invoke(value, row); + private static Func BuildCreateTableFunc() + { + var dtExp = Expression.Variable(typeof(DataTable)); + var ctorMethod = typeof(DataTable).GetConstructor([typeof(string)])!; + var newDt = Expression.New(ctorMethod, [Expression.Constant(typeof(T).Name, typeof(string))]); + var assign = Expression.Assign(dtExp, newDt); - internal static DataTable GetDataTable() => createTable.Invoke(); - internal static void FillDataRow(T value, DataRow row) => fillRow.Invoke(value, row); - private static Func BuildCreateTableFunc() + List body = [ + dtExp,assign + ]; + var props = typeof(T).GetProperties(); + foreach (var item in props) { - var dtExp = Expression.Variable(typeof(DataTable)); - var ctorMethod = typeof(DataTable).GetConstructor([typeof(string)])!; - var newDt = Expression.New(ctorMethod, [Expression.Constant(typeof(T).Name, typeof(string))]); - var assign = Expression.Assign(dtExp, newDt); - - List body = [ - dtExp,assign - ]; - var props = typeof(T).GetProperties(); - var columns = Expression.Property(dtExp, nameof(DataTable.Columns)); - foreach (var item in props) - { - if (!item.CanRead) continue; - body.Add(Expression.Call(columns, ExpressionUsedMethods.DataColumnAdd, Expression.Constant(item.Name, typeof(string)), Expression.Constant(item.PropertyType, typeof(Type)))); - } - body.Add(dtExp); - var block = Expression.Block([dtExp], [.. body]); - var lambda = Expression.Lambda>(block); - return lambda.Compile(); + if (!item.CanRead) continue; + body.Add(Expression.Call(dtExp, ExpressionUsedMethods.DataColumnAdd, Expression.Constant(item.Name, typeof(string)), Expression.Constant(item.PropertyType, typeof(Type)))); } + body.Add(dtExp); + var block = Expression.Block([dtExp], [.. body]); + var lambda = Expression.Lambda>(block); + return lambda.Compile(); + } - private static Action BuildCreateRowFunc() + private static Action BuildCreateRowFunc() + { + var val = Expression.Parameter(typeof(T), "p"); + var row = Expression.Parameter(typeof(DataRow), "r"); + var props = typeof(T).GetProperties(); + List body = []; + foreach (var item in props) { - var val = Expression.Parameter(typeof(T), "p"); - var row = Expression.Parameter(typeof(DataRow), "r"); - var props = typeof(T).GetProperties(); - List body = []; - foreach (var item in props) - { - if (!item.CanRead) continue; - body.Add(Expression.Call(row, ExpressionUsedMethods.DataRowSet, Expression.Constant(item.Name, typeof(string)), Expression.Convert(Expression.Property(val, item), typeof(object)))); - } - var block = Expression.Block( [.. body]); - var lambda = Expression.Lambda>(block, val, row); - return lambda.Compile(); + if (!item.CanRead) continue; + body.Add(Expression.Call(row, ExpressionUsedMethods.DataRowSet, Expression.Constant(item.Name, typeof(string)), Expression.Convert(Expression.Property(val, item), typeof(object)))); } + var block = Expression.Block([.. body]); + var lambda = Expression.Lambda>(block, val, row); + return lambda.Compile(); } } diff --git a/src/Toolkit/DataTableExtension/TableExpressionBase.cs b/src/Toolkit/DataTableExtension/TableExpressionBase.cs index edbd23f..31608d3 100644 --- a/src/Toolkit/DataTableExtension/TableExpressionBase.cs +++ b/src/Toolkit/DataTableExtension/TableExpressionBase.cs @@ -1,42 +1,43 @@ using MT.Toolkit.ExpressionHelper; using System; using System.Data; +using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; namespace MT.Toolkit.DataTableExtension { - internal class TableExpressionBase - { - public static MethodInfo Datarow_getItem = typeof(DataRow).GetMethod("get_Item", new Type[] { typeof(string) }); - public static MethodInfo DataRow_IsNull = typeof(DataRow).GetMethod("IsNull", new Type[] { typeof(string) }); - public static Expression GetTargetValueExpression(DataColumn column, ParameterExpression parameterExpression, Type targetType) - { - MethodCallExpression rowObjExp = Expression.Call(parameterExpression, Datarow_getItem, Expression.Constant(column.ColumnName)); - MethodCallExpression checkNullExp = Expression.Call(parameterExpression, DataRow_IsNull, Expression.Constant(column.ColumnName)); - Expression e; - Type t = column.DataType; - if (targetType != typeof(byte[])) - { - e = Expression.Call(rowObjExp, typeof(object).GetMethod("ToString", Type.EmptyTypes)); - t = typeof(string); - } - else - e = rowObjExp; - Expression realValueExp = DataTypeConvert.GetConversionExpression(e, t, targetType); - if (column.AllowDBNull) - { - return Expression.Condition( - checkNullExp, - Expression.Default(targetType), - realValueExp, - targetType - ); - } - else - { - return realValueExp; - } - } - } + internal class TableExpressionBase + { + public static MethodInfo Datarow_getItem = typeof(DataRow).GetMethod("get_Item", [typeof(string)])!; + public static MethodInfo DataRow_IsNull = typeof(DataRow).GetMethod("IsNull", [typeof(string)])!; + public static Expression GetTargetValueExpression(DataColumn column, ParameterExpression parameterExpression, Type targetType) + { + MethodCallExpression rowObjExp = Expression.Call(parameterExpression, Datarow_getItem, Expression.Constant(column.ColumnName)); + MethodCallExpression checkNullExp = Expression.Call(parameterExpression, DataRow_IsNull, Expression.Constant(column.ColumnName)); + Expression e; + Type t = column.DataType; + if (targetType != typeof(byte[])) + { + e = Expression.Call(rowObjExp, typeof(object).GetMethod("ToString", Type.EmptyTypes)!); + t = typeof(string); + } + else + e = rowObjExp; + Expression realValueExp = DataTypeConvert.GetConversionExpression(e, t, targetType); + if (column.AllowDBNull) + { + return Expression.Condition( + checkNullExp, + Expression.Default(targetType), + realValueExp, + targetType + ); + } + else + { + return realValueExp; + } + } + } } diff --git a/src/Toolkit/EnumExtensions/EnumHelper.cs b/src/Toolkit/EnumExtensions/EnumHelper.cs index 2660132..dc22538 100644 --- a/src/Toolkit/EnumExtensions/EnumHelper.cs +++ b/src/Toolkit/EnumExtensions/EnumHelper.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.ComponentModel; using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; @@ -16,28 +18,40 @@ namespace MT.Toolkit.EnumExtensions /// public static class EnumHelper { - private static readonly ConcurrentDictionary<(Type, string), string> enumCache = []; + private static readonly ConcurrentDictionary> enumCache = []; /// - /// + /// 获取枚举的显示名称 /// /// /// /// - public static string GetDisplayName(this T @enum) where T : Enum + public static string GetDisplayName< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] +#endif + T>(this T @enum) where T : Enum { - return enumCache.GetOrAdd((typeof(T), @enum.ToString()), key => + var et = typeof(T); + var member = et.GetMember(@enum.ToString()).First(); + if (!enumCache.TryGetValue(et, out var edic)) { - var member = key.Item1.GetMember(key.Item2).FirstOrDefault(); - if (member != null) + edic = new(); + enumCache.TryAdd(et, edic); + } + if (!edic.TryGetValue(member, out var des)) + { + if (member.GetCustomAttribute() is { } displayAttr) + { + des = displayAttr.Name; + } + else if (member.GetCustomAttribute() is { } descriptionAttr) { - var displayAttr = member.GetCustomAttribute(); - if (displayAttr is not null) - { - return displayAttr.Name ?? key.Item2; - } + des = descriptionAttr.Description; } - return key.Item2; - }); + des ??= @enum.ToString(); + edic.TryAdd(member, des); + } + return des; } } diff --git a/src/Toolkit/ExpressionHelper/DataTypeConvert.cs b/src/Toolkit/ExpressionHelper/DataTypeConvert.cs index 27a9bfb..cce7d84 100644 --- a/src/Toolkit/ExpressionHelper/DataTypeConvert.cs +++ b/src/Toolkit/ExpressionHelper/DataTypeConvert.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; @@ -8,151 +9,167 @@ using System.Text; using System.Threading.Tasks; -namespace MT.Toolkit.ExpressionHelper +namespace MT.Toolkit.ExpressionHelper; + +internal class DataTypeConvert { - public class DataTypeConvert + public static Expression GetConversionExpression(Expression source, + Type sourceType, + Type targetType) { - public static Expression GetConversionExpression(Expression source, Type sourceType, Type targetType) + if (ReferenceEquals(sourceType, targetType)) { - if (ReferenceEquals(sourceType, targetType)) - { - return Expression.Convert(source, sourceType); - } - else if (ReferenceEquals(sourceType, typeof(string))) - { - // XXX.Parse() - return GetParseExpression(source, targetType, CultureInfo.CurrentCulture); - } - else if (ReferenceEquals(targetType, typeof(string))) - { - // XXX.ToString() - return Expression.Call(source, sourceType.GetMethod("ToString", Type.EmptyTypes)!); - } - else if (ReferenceEquals(targetType, typeof(bool))) - { - MethodInfo ToBooleanMethod = typeof(Convert).GetMethod("ToBoolean", new[] { sourceType }); - return Expression.Call(ToBooleanMethod, source); - } - else if (ReferenceEquals(sourceType, typeof(byte[]))) - { - return GetArrayHandlerExpression(source, targetType); - } - else - { - return ConvertTypeExpression(source, sourceType, targetType); - } + return Expression.Convert(source, sourceType); } - private static Expression GetArrayHandlerExpression(Expression sourceExpression, Type targetType) + else if (ReferenceEquals(sourceType, typeof(string))) { - Expression TargetExpression = default; - if (ReferenceEquals(targetType, typeof(byte[]))) - { - TargetExpression = sourceExpression; - } - else if (ReferenceEquals(targetType, typeof(MemoryStream))) - { - ConstructorInfo ConstructorInfo = targetType.GetConstructor(new[] { typeof(byte[]) }); - TargetExpression = Expression.New(ConstructorInfo, sourceExpression); - } - else - { - throw new ArgumentException("Cannot convert a byte array to " + targetType.Name); - } - return TargetExpression; + // XXX.Parse() + return GetParseExpression(source, targetType, CultureInfo.CurrentCulture); + } + else if (ReferenceEquals(targetType, typeof(string))) + { + // XXX.ToString() + return Expression.Call(source, typeof(Convert).GetMethod("ToString", [sourceType])!); + } + else if (ReferenceEquals(targetType, typeof(bool))) + { + MethodInfo ToBooleanMethod = typeof(Convert).GetMethod("ToBoolean", [sourceType])!; + return Expression.Call(ToBooleanMethod, source); + } + else if (ReferenceEquals(sourceType, typeof(byte[]))) + { + return GetArrayHandlerExpression(source, targetType); + } + else + { + return ConvertTypeExpression(source, sourceType, targetType); } + } + private static Expression GetArrayHandlerExpression(Expression sourceExpression, Type targetType) + { + Expression TargetExpression = default!; + if (ReferenceEquals(targetType, typeof(byte[]))) + { + TargetExpression = sourceExpression; + } + else if (ReferenceEquals(targetType, typeof(MemoryStream))) + { + ConstructorInfo ConstructorInfo = typeof(MemoryStream).GetConstructor([typeof(byte[])])!; + TargetExpression = Expression.New(ConstructorInfo, sourceExpression); + } + else + { + throw new ArgumentException("Cannot convert a byte array to " + targetType.Name); + } + return TargetExpression; + } - private static Expression GetParseExpression(Expression SourceExpression, Type TargetType, CultureInfo Culture) + private static Expression GetParseExpression(Expression SourceExpression, Type TargetType, CultureInfo Culture) + { + Type UnderlyingType = Nullable.GetUnderlyingType(TargetType) ?? TargetType; + if (UnderlyingType.IsEnum) { - Type UnderlyingType = Nullable.GetUnderlyingType(TargetType) ?? TargetType; - if (UnderlyingType.IsEnum) - { - MethodCallExpression ParsedEnumExpression = GetEnumParseExpression(SourceExpression, UnderlyingType); - //Enum.Parse returns an object that needs to be unboxed - return Expression.Unbox(ParsedEnumExpression, TargetType); - } - else + MethodCallExpression ParsedEnumExpression = GetEnumParseExpression(SourceExpression, UnderlyingType); + //Enum.Parse returns an object that needs to be unboxed + return Expression.Unbox(ParsedEnumExpression, TargetType); + } + else + { + Expression valueExp = default!; + valueExp = UnderlyingType.FullName switch { - Expression ParseExpression = default; - switch (UnderlyingType.FullName) - { - case "System.Byte": - case "System.UInt16": - case "System.UInt32": - case "System.UInt64": - case "System.SByte": - case "System.Int16": - case "System.Int32": - case "System.Int64": - case "System.Double": - case "System.Decimal": - ParseExpression = GetNumberParseExpression(SourceExpression, UnderlyingType, Culture); - break; - case "System.DateTime": - ParseExpression = GetDateTimeParseExpression(SourceExpression, UnderlyingType, Culture); - break; - case "System.Boolean": - case "System.Char": - ParseExpression = GetGenericParseExpression(SourceExpression, UnderlyingType); - break; - default: - throw new ArgumentException(string.Format("Conversion from {0} to {1} is not supported", "String", TargetType)); - } - if (Nullable.GetUnderlyingType(TargetType) == null) - { - return ParseExpression; - } - else - { - //Convert to nullable if necessary - return Expression.Convert(ParseExpression, TargetType); - } - } - Expression GetGenericParseExpression(Expression sourceExpression, Type type) + "System.Byte" => NumberParseExpression(SourceExpression, Culture), + "System.UInt16" => NumberParseExpression(SourceExpression, Culture), + "System.UInt32" => NumberParseExpression(SourceExpression, Culture), + "System.UInt64" => NumberParseExpression(SourceExpression, Culture), + "System.SByte" => NumberParseExpression(SourceExpression, Culture), + "System.Int16" => NumberParseExpression(SourceExpression, Culture), + "System.Int32" => NumberParseExpression(SourceExpression, Culture), + "System.Int64" => NumberParseExpression(SourceExpression, Culture), + "System.Double" => NumberParseExpression(SourceExpression, Culture), + "System.Decimal" => NumberParseExpression(SourceExpression, Culture), + "System.DateTime" => GetDateTimeParseExpression(SourceExpression, Culture), + "System.Boolean" => GetGenericParseExpression(SourceExpression), + "System.Char" => GetGenericParseExpression(SourceExpression), + _ => throw new ArgumentException(string.Format("Conversion from {0} to {1} is not supported", "String", TargetType)), + }; + if (Nullable.GetUnderlyingType(TargetType) == null) { - MethodInfo ParseMetod = type.GetMethod("Parse", new[] { typeof(string) }); - MethodCallExpression CallExpression = Expression.Call(ParseMetod, new[] { sourceExpression }); - return CallExpression; + return valueExp; } - Expression GetDateTimeParseExpression(Expression sourceExpression, Type type, CultureInfo culture) + else { - MethodInfo ParseMetod = type.GetMethod("Parse", new[] { typeof(string), typeof(DateTimeFormatInfo) }); - ConstantExpression ProviderExpression = Expression.Constant(culture.DateTimeFormat, typeof(DateTimeFormatInfo)); - MethodCallExpression CallExpression = Expression.Call(ParseMetod, new[] { sourceExpression, ProviderExpression }); - return CallExpression; + //Convert to nullable if necessary + return Expression.Convert(valueExp, TargetType); } + } + Expression GetGenericParseExpression< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] +#endif + T>(Expression sourceExpression) + { + MethodInfo ParseMetod = typeof(T).GetMethod("Parse", [typeof(string)])!; + MethodCallExpression CallExpression = Expression.Call(ParseMetod, [sourceExpression]); + return CallExpression; + } + Expression GetDateTimeParseExpression(Expression sourceExpression, CultureInfo culture) + { + MethodInfo ParseMetod = typeof(DateTime).GetMethod("Parse", [typeof(string), typeof(DateTimeFormatInfo)])!; + ConstantExpression ProviderExpression = Expression.Constant(culture.DateTimeFormat, typeof(DateTimeFormatInfo)); + MethodCallExpression CallExpression = Expression.Call(ParseMetod, [sourceExpression, ProviderExpression]); + return CallExpression; + } - MethodCallExpression GetEnumParseExpression(Expression sourceExpression, Type type) - { - //Get the MethodInfo for parsing an Enum - MethodInfo EnumParseMethod = typeof(Enum).GetMethod("Parse", new[] { typeof(Type), typeof(string), typeof(bool) }); - ConstantExpression TargetMemberTypeExpression = Expression.Constant(type); - ConstantExpression IgnoreCase = Expression.Constant(true, typeof(bool)); - //Create an expression the calls the Parse method - MethodCallExpression CallExpression = Expression.Call(EnumParseMethod, new[] { TargetMemberTypeExpression, sourceExpression, IgnoreCase }); - return CallExpression; - } - MethodCallExpression GetNumberParseExpression(Expression sourceExpression, Type type, CultureInfo culture) - { - MethodInfo ParseMetod = type.GetMethod("Parse", new[] { typeof(string), typeof(NumberFormatInfo) }); - ConstantExpression ProviderExpression = Expression.Constant(culture.NumberFormat, typeof(NumberFormatInfo)); - MethodCallExpression CallExpression = Expression.Call(ParseMetod, new[] { sourceExpression, ProviderExpression }); - return CallExpression; - } - } - static MethodInfo changeType = typeof(Convert).GetMethod("ChangeType", [typeof(object), typeof(Type)])!; - static MethodInfo isNullOrEmpty = typeof(string).GetMethod(nameof(string.IsNullOrEmpty))!; - private static Expression ConvertTypeExpression(Expression source, Type sourceType, Type targetType) + MethodCallExpression GetEnumParseExpression(Expression sourceExpression, Type type) { - var underType = Nullable.GetUnderlyingType(targetType) ?? targetType; - var isNull = Expression.Equal(source, Expression.Constant(null)); - var stringValue = Expression.Call(source, sourceType.GetMethod("ToString", Type.EmptyTypes)!); - var isNullOrEmptyExpression = Expression.Call(isNullOrEmpty, stringValue); - var canConvert = Expression.AndAlso(Expression.IsFalse(isNull), Expression.IsFalse(isNullOrEmptyExpression)); - var finalValue = Expression.Convert(Expression.Call(changeType, source, Expression.Constant(underType)), targetType); - return Expression.Condition(canConvert, finalValue, Expression.Default(targetType)); + //Get the MethodInfo for parsing an Enum + MethodInfo EnumParseMethod = typeof(Enum).GetMethod("Parse", [typeof(Type), typeof(string), typeof(bool)])!; + ConstantExpression TargetMemberTypeExpression = Expression.Constant(type); + ConstantExpression IgnoreCase = Expression.Constant(true, typeof(bool)); + //Create an expression the calls the Parse method + MethodCallExpression CallExpression = Expression.Call(EnumParseMethod, [TargetMemberTypeExpression, sourceExpression, IgnoreCase]); + return CallExpression; + } + +// MethodCallExpression GetNumberParseExpression(Expression sourceExpression, +//#if NET8_0_OR_GREATER +// [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] +//#endif +// Type type, CultureInfo culture) +// { +// MethodInfo ParseMetod = type.GetMethod("Parse", [typeof(string), typeof(NumberFormatInfo)])!; +// ConstantExpression ProviderExpression = Expression.Constant(culture.NumberFormat, typeof(NumberFormatInfo)); +// MethodCallExpression CallExpression = Expression.Call(ParseMetod, [sourceExpression, ProviderExpression]); +// return CallExpression; +// } + MethodCallExpression NumberParseExpression< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] +#endif + T>(Expression source, CultureInfo culture) + { + MethodInfo ParseMetod = typeof(T).GetMethod("Parse", [typeof(string), typeof(NumberFormatInfo)])!; + ConstantExpression ProviderExpression = Expression.Constant(culture.NumberFormat, typeof(NumberFormatInfo)); + MethodCallExpression CallExpression = Expression.Call(ParseMetod, [source, ProviderExpression]); + return CallExpression; } } + + static MethodInfo changeType = typeof(Convert).GetMethod("ChangeType", [typeof(object), typeof(Type)])!; + static MethodInfo isNullOrEmpty = typeof(string).GetMethod(nameof(string.IsNullOrEmpty))!; + private static ConditionalExpression ConvertTypeExpression(Expression source, Type sourceType, Type targetType) + { + var underType = Nullable.GetUnderlyingType(targetType) ?? targetType; + var isNull = Expression.Equal(source, Expression.Constant(null)); + var stringValue = Expression.Call(source, typeof(Convert).GetMethod("ToString", [sourceType])!); + var isNullOrEmptyExpression = Expression.Call(isNullOrEmpty, stringValue); + var canConvert = Expression.AndAlso(Expression.IsFalse(isNull), Expression.IsFalse(isNullOrEmptyExpression)); + var finalValue = Expression.Convert(Expression.Call(changeType, source, Expression.Constant(underType)), targetType); + return Expression.Condition(canConvert, finalValue, Expression.Default(targetType)); + + } } diff --git a/src/Toolkit/ExpressionHelper/ExpressionCombine.cs b/src/Toolkit/ExpressionHelper/ExpressionCombine.cs index dcb3b87..7ac0c24 100644 --- a/src/Toolkit/ExpressionHelper/ExpressionCombine.cs +++ b/src/Toolkit/ExpressionHelper/ExpressionCombine.cs @@ -7,8 +7,18 @@ namespace MT.Toolkit.ExpressionHelper { + /// + /// 表达式操作 + /// public static class ExpressionCombine { + /// + /// 使用连接两个表达式树 + /// + /// + /// + /// + /// public static Expression> AndAlso(this Expression> self, Expression> other) { var p = self.Parameters; @@ -16,6 +26,14 @@ public static Expression> AndAlso(this Expression return Expression.Lambda>(body, p); } + /// + /// 使用连接两个表达式树 + /// + /// + /// + /// + /// + /// public static Expression> AndAlsoIf(this Expression> self, bool condition, Expression> other) { if (!condition) return self; @@ -24,6 +42,14 @@ public static Expression> AndAlsoIf(this Expression>(body, p); } + /// + /// 使用连接两个表达式树 + /// + /// + /// + /// + /// + /// public static Expression> AndAlsoIf(this Expression> self, Func condition, Expression> other) { if (!condition.Invoke()) return self; @@ -32,6 +58,13 @@ public static Expression> AndAlsoIf(this Expression>(body, p); } + /// + /// 使用连接两个表达式树 + /// + /// + /// + /// + /// public static Expression> OrElse(this Expression> self, Expression> other) { var p = self.Parameters; @@ -39,6 +72,14 @@ public static Expression> OrElse(this Expression> return Expression.Lambda>(body, p); } + /// + /// 使用连接两个表达式树 + /// + /// + /// + /// + /// + /// public static Expression> OrElseIf(this Expression> self, bool condition, Expression> other) { if (!condition) return self; @@ -46,6 +87,15 @@ public static Expression> OrElseIf(this Expression>(body, p); } + + /// + /// 使用连接两个表达式树 + /// + /// + /// + /// + /// + /// public static Expression> OrElseIf(this Expression> self, Func condition, Expression> other) { if (!condition.Invoke()) return self; diff --git a/src/Toolkit/FrequencyGuard/Debounce.cs b/src/Toolkit/FrequencyGuard/Debounce.cs new file mode 100644 index 0000000..99709f9 --- /dev/null +++ b/src/Toolkit/FrequencyGuard/Debounce.cs @@ -0,0 +1,150 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace MT.Toolkit; + +/// +/// 防抖器 +/// +public class Debounce : IDisposable +{ + private CancellationTokenSource? cts = null; + private readonly Func action; + private readonly int delayMs; + + private Debounce(Action action, int delayMs) + { + this.action = (value, _) => + { + action(value); + return Task.CompletedTask; + }; + this.delayMs = delayMs; + } + + private Debounce(Func action, int delayMs) + { + this.action = action; + this.delayMs = delayMs; + } + + /// + /// + /// + /// + /// + public async Task InvokeAsync(T value, CancellationToken cancellationToken = default) + { + cts?.Cancel(); + cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var token = cts.Token; + try + { + await Task.Delay(delayMs, token); + if (!token.IsCancellationRequested) + { + await action(value, token); + return true; + } + return false; + } + catch (OperationCanceledException) + { + return false; + } + } + + /// + /// 创建一个防抖器 + /// + public static Debounce Create(Action action, int delayMs) + => new(action, delayMs); + + /// + /// 创建一个防抖器 + /// + public static Debounce Create(Func action, int delayMs) + => new(action, delayMs); + + /// + /// + /// + public void Dispose() + { + cts?.Dispose(); + GC.SuppressFinalize(this); + } +} + +/// +/// 无参防抖器 +/// +public class Debounce : IDisposable +{ + private CancellationTokenSource? cts = null; + private readonly Func action; + private readonly int delayMs; + + private Debounce(Action action, int delayMs) + { + this.action = _ => + { + action(); + return Task.CompletedTask; + }; + this.delayMs = delayMs; + } + + private Debounce(Func action, int delayMs) + { + this.action = action; + this.delayMs = delayMs; + } + + /// + /// + /// + /// + public async Task InvokeAsync(CancellationToken cancellationToken = default) + { + cts?.Cancel(); + cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var token = cts.Token; + try + { + await Task.Delay(delayMs, token); + if (!token.IsCancellationRequested) + { + await action(token); + return true; + } + return false; + } + catch (OperationCanceledException) + { + return false; + } + } + + /// + /// 创建一个防抖器 + /// + public static Debounce Create(Action action, int delayMs) + => new(action, delayMs); + + /// + /// 创建一个防抖器 + /// + public static Debounce Create(Func action, int delayMs) + => new(action, delayMs); + + /// + /// + /// + public void Dispose() + { + cts?.Dispose(); + GC.SuppressFinalize(this); + } +} \ No newline at end of file diff --git a/src/Toolkit/FrequencyGuard/Throttle.cs b/src/Toolkit/FrequencyGuard/Throttle.cs new file mode 100644 index 0000000..c92c49b --- /dev/null +++ b/src/Toolkit/FrequencyGuard/Throttle.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace MT.Toolkit; + +/// +/// 节流器 +/// +public class Throttle : IDisposable +{ + private readonly SemaphoreSlim semaphoreSlim = new(1, 1); + private readonly Func action; + private readonly int delayMs; + + private Throttle(Action action, int delayMs) + { + this.action = (value, _) => + { + action(value); + return Task.CompletedTask; + }; + this.delayMs = delayMs; + } + + private Throttle(Func action, int delayMs) + { + this.action = action; + this.delayMs = delayMs; + } + + /// + /// + /// + /// + /// + /// + public async Task InvokeAsync(T value, CancellationToken cancellationToken = default) + { + try + { + if (!await semaphoreSlim.WaitAsync(0, cancellationToken)) + return false; + _ = ReleaseSemaphore(semaphoreSlim, delayMs); + await action(value, cancellationToken).ConfigureAwait(false); + return true; + } + catch (Exception) + { + throw; + } + } + + private static async Task ReleaseSemaphore(SemaphoreSlim semaphore, int ms) + { + await Task.Delay(ms).ConfigureAwait(false); + semaphore.Release(); + } + + /// + /// 创建一个防抖器 + /// + public static Throttle Create(Action action, int delayMs) + => new(action, delayMs); + + /// + /// 创建一个防抖器 + /// + public static Throttle Create(Func action, int delayMs) + => new(action, delayMs); + + /// + /// + /// + public void Dispose() + { + semaphoreSlim.Dispose(); + GC.SuppressFinalize(this); + } +} + + +/// +/// 无参节流器 +/// +public class Throttle : IDisposable +{ + private readonly SemaphoreSlim semaphoreSlim = new(1, 1); + private readonly Func action; + private readonly int delayMs; + + private Throttle(Action action, int delayMs) + { + this.action = _ => + { + action(); + return Task.CompletedTask; + }; + this.delayMs = delayMs; + } + + private Throttle(Func action, int delayMs) + { + this.action = action; + this.delayMs = delayMs; + } + + /// + /// + /// + /// + /// + public async Task InvokeAsync(CancellationToken cancellationToken = default) + { + try + { + if (!await semaphoreSlim.WaitAsync(0, cancellationToken)) + return false; + _ = ReleaseSemaphore(semaphoreSlim, delayMs); + await action(cancellationToken).ConfigureAwait(false); + return true; + } + catch (Exception) + { + throw; + } + } + + private static async Task ReleaseSemaphore(SemaphoreSlim semaphore, int ms) + { + await Task.Delay(ms).ConfigureAwait(false); + semaphore.Release(); + } + + /// + /// 创建一个防抖器 + /// + public static Throttle Create(Action action, int delayMs) + => new(action, delayMs); + + /// + /// 创建一个防抖器 + /// + public static Throttle Create(Func action, int delayMs) + => new(action, delayMs); + + /// + /// + /// + public void Dispose() + { + semaphoreSlim.Dispose(); + GC.SuppressFinalize(this); + } +} diff --git a/src/Toolkit/HttpHelper/ISoapServiceManager.cs b/src/Toolkit/HttpHelper/ISoapServiceManager.cs index 9aae5f9..247c105 100644 --- a/src/Toolkit/HttpHelper/ISoapServiceManager.cs +++ b/src/Toolkit/HttpHelper/ISoapServiceManager.cs @@ -1,26 +1,27 @@ using System; using System.Collections.Concurrent; -namespace MT.Toolkit.HttpHelper +namespace MT.Toolkit.HttpHelper; + +/// +/// SOAP服务配置器 +/// +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +public interface ISoapServiceManager { + internal ConcurrentDictionary Configs { get; } + internal string? DefaultKey { get; } /// - /// SOAP服务配置器 + /// 设置默认的KEY /// - public interface ISoapServiceManager - { - internal ConcurrentDictionary Configs { get; } - internal string? DefaultKey { get; } - /// - /// 设置默认的KEY - /// - /// - /// - ISoapServiceManager SetDefault(string key); - /// - /// 添加SOAP服务 - /// - /// 配置名称 - /// - /// - ISoapServiceManager AddSoapService(string name, Action config); - } + /// + /// + ISoapServiceManager SetDefault(string key); + /// + /// 添加SOAP服务 + /// + /// 配置名称 + /// + /// + ISoapServiceManager AddSoapService(string name, Action config); } \ No newline at end of file diff --git a/src/Toolkit/HttpHelper/SoapFaultException.cs b/src/Toolkit/HttpHelper/SoapFaultException.cs index 54f8e45..39500ef 100644 --- a/src/Toolkit/HttpHelper/SoapFaultException.cs +++ b/src/Toolkit/HttpHelper/SoapFaultException.cs @@ -6,9 +6,24 @@ namespace MT.Toolkit.HttpHelper; +/// +/// Soap接口调用异常类 +/// +/// +/// +/// public class SoapFaultException(string? fCode, string? fString, string? fDetail) : Exception($"{fCode}-{fString}-{fDetail}") { + /// + /// Gets the fault code associated with the current error, if available. + /// public string? FaultCode { get; } = fCode; + /// + /// Gets the fault string associated with the current error, if available. + /// public string? FaultString { get; } = fString; + /// + /// Gets the fault detail associated with the current error, if available. + /// public string? FaultDetail { get; } = fDetail; } diff --git a/src/Toolkit/HttpHelper/SoapResponse.cs b/src/Toolkit/HttpHelper/SoapResponse.cs index 7356d63..69fb95b 100644 --- a/src/Toolkit/HttpHelper/SoapResponse.cs +++ b/src/Toolkit/HttpHelper/SoapResponse.cs @@ -1,247 +1,241 @@ using MT.Toolkit.TypeConvertHelper; using MT.Toolkit.XmlHelper; using System; -using System.Collections; using System.Collections.Generic; using System.Data; -using System.Data.SqlTypes; -using System.Dynamic; using System.IO; using System.Linq; -using System.Linq.Expressions; using System.Xml; using System.Xml.Linq; -using System.Xml.XPath; -namespace MT.Toolkit.HttpHelper +namespace MT.Toolkit.HttpHelper; + +#pragma warning disable + +[Obsolete("Use SoapRequestHelper Package instead.", true)] +public sealed class SoapResponse { - [Obsolete("Use SoapRequestHelper Package instead.", true)] - public sealed class SoapResponse - { - public const string RN_ALIAS = "r"; - /// - /// 请求是否发送成功 - /// - public bool Success { get; set; } = true; - /// - /// 请求发生异常时的异常 - /// - public Exception? Exception { get; set; } - /// - /// 请求发生异常或解析返回数据时发生异常的异常信息 - /// - public string? Message { get; set; } - private readonly XmlString? xmlString; - private readonly string? responseContent; - private XmlNamespaceManager? nsManager; - private readonly string? methodName; + public const string RN_ALIAS = "r"; + /// + /// 请求是否发送成功 + /// + public bool Success { get; set; } = true; + /// + /// 请求发生异常时的异常 + /// + public Exception? Exception { get; set; } + /// + /// 请求发生异常或解析返回数据时发生异常的异常信息 + /// + public string? Message { get; set; } + private readonly XmlString? xmlString; + private readonly string? responseContent; + private XmlNamespaceManager? nsManager; + private readonly string? methodName; - internal SoapResponse(string requestContent, string? responseContent, string? rawValue, XmlNamespaceManager manager, string? methodName) - { - RequestContent = requestContent; - this.responseContent = responseContent; - xmlString = rawValue; - nsManager = manager; - this.methodName = methodName; - } + internal SoapResponse(string requestContent, string? responseContent, string? rawValue, XmlNamespaceManager manager, string? methodName) + { + RequestContent = requestContent; + this.responseContent = responseContent; + xmlString = rawValue; + nsManager = manager; + this.methodName = methodName; + } - internal SoapResponse(string requestContent,string? responseContent, Exception ex) - { - Success = false; - RequestContent = requestContent; - this.responseContent = responseContent; - Exception = ex; - Message = ex.Message; - } - public string? RawContent => responseContent; - public string? RawValue => xmlString?.Value; - public string RequestContent { get; } - private XElement? retXml; + internal SoapResponse(string requestContent,string? responseContent, Exception ex) + { + Success = false; + RequestContent = requestContent; + this.responseContent = responseContent; + Exception = ex; + Message = ex.Message; + } + public string? RawContent => responseContent; + public string? RawValue => xmlString?.Value; + public string RequestContent { get; } + private XElement? retXml; - #region 解析返回值 - /// - /// 接口签名中return的内容 - /// - /// - /// - public T? ReadReturnValue() + #region 解析返回值 + /// + /// 接口签名中return的内容 + /// + /// + /// + public T? ReadReturnValue() + { + var type = typeof(T); + if (type != typeof(object)) { - var type = typeof(T); - if (type != typeof(object)) - { - var str = xmlString?.GetValue($"//{RN_ALIAS}:{methodName}Result", nsManager); - if (string.IsNullOrEmpty(str)) return default; - var ret = Convert.ChangeType(str, typeof(T)); - if (ret == null) return default; - return (T?)ret; - } - // 序列化返回的结果 - return GetNode($"//{RN_ALIAS}:{methodName}Result")?.AsDynamic(); + var str = xmlString?.GetValue($"//{RN_ALIAS}:{methodName}Result", nsManager); + if (string.IsNullOrEmpty(str)) return default; + var ret = Convert.ChangeType(str, typeof(T)); + if (ret == null) return default; + return (T?)ret; } - /// - /// 接口签名中return的内容 - /// - /// - /// - public dynamic? ReadReturnValue() => ReadReturnValue(); + // 序列化返回的结果 + return GetNode($"//{RN_ALIAS}:{methodName}Result")?.AsDynamic(); + } + /// + /// 接口签名中return的内容 + /// + public dynamic? ReadReturnValue() => ReadReturnValue(); - /// - /// 如果返回的结果可以解释为XML - /// - /// - public XElement? ReadReturnValueAsXml() + /// + /// 如果返回的结果可以解释为XML + /// + /// + public XElement? ReadReturnValueAsXml() + { + if (retXml == null) { - if (retXml == null) + var raw = GetValue($"//{RN_ALIAS}:{methodName}Result"); + if (raw != null) { - var raw = GetValue($"//{RN_ALIAS}:{methodName}Result"); - if (raw != null) - { - using var reader = new StringReader(raw); - using var xmlReader = XmlReader.Create(reader); - retXml = XElement.Load(xmlReader); - } + using var reader = new StringReader(raw); + using var xmlReader = XmlReader.Create(reader); + retXml = XElement.Load(xmlReader); } - return retXml; - } - /// - /// 如果返回的结果可以转为DataTable - /// - /// - public DataTable ReadReturnValueAsDataTable() - { - nsManager?.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); - var xml = xmlString?.GetElement($"//{RN_ALIAS}:{methodName}Result", nsManager); - var schema = xml.GetChildElements("//xs:sequence", nsManager); - var datas = xml.GetChildElements("//DocumentElement", nsManager); - return CreateDataTable(schema, datas, nsManager); } + return retXml; + } + /// + /// 如果返回的结果可以转为DataTable + /// + /// + public DataTable ReadReturnValueAsDataTable() + { + nsManager?.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); + var xml = xmlString?.GetElement($"//{RN_ALIAS}:{methodName}Result", nsManager); + var schema = xml.GetChildElements("//xs:sequence", nsManager); + var datas = xml.GetChildElements("//DocumentElement", nsManager); + return CreateDataTable(schema, datas, nsManager); + } - #endregion + #endregion - #region 额外的返回值,out / ref 等 - /// - /// out参数或者ref参数的返回值 - /// - /// - /// - /// - public T? ReadParameterReturnValue(string? name = null) - { - var outParam = ReadParameterReturnValueAsXml(name); - if (outParam == null) return default; - var type = typeof(T); - if (type != typeof(object)) - { - var str = outParam.Value; - if (string.IsNullOrEmpty(str)) return default; - var ret = Convert.ChangeType(str, typeof(T)); - if (ret == null) return default; - return (T?)ret; - } - return outParam.AsDynamic(); - } - /// - /// out参数或者ref参数的返回值 - /// - /// - /// - public dynamic? ReadParameterReturnValue(string? name = null) => ReadParameterReturnValue(name); - /// - /// 如果out参数或者ref参数的返回值可以解析为XML - /// - /// - /// - public XElement? ReadParameterReturnValueAsXml(string? name = null) + #region 额外的返回值,out / ref 等 + /// + /// out参数或者ref参数的返回值 + /// + /// + /// + /// + public T? ReadParameterReturnValue(string? name = null) + { + var outParam = ReadParameterReturnValueAsXml(name); + if (outParam == null) return default; + var type = typeof(T); + if (type != typeof(object)) { - var outParams = xmlString?.GetElementsAfterSelf($"//{RN_ALIAS}:{methodName}Result", nsManager); - XElement? outParam = outParams?.FirstOrDefault(x => - { - if (string.IsNullOrEmpty(name)) return true; - return x.Name == name; - }); - if (outParam == null) return default; - return outParam; + var str = outParam.Value; + if (string.IsNullOrEmpty(str)) return default; + var ret = Convert.ChangeType(str, typeof(T)); + if (ret == null) return default; + return (T?)ret; } - /// - /// 如果out参数或者ref参数的返回值可以解析为DataTable - /// - /// - public DataTable ReadParameterReturnValueAsDataTable() + return outParam.AsDynamic(); + } + /// + /// out参数或者ref参数的返回值 + /// + /// + /// + public dynamic? ReadParameterReturnValue(string? name = null) => ReadParameterReturnValue(name); + /// + /// 如果out参数或者ref参数的返回值可以解析为XML + /// + /// + /// + public XElement? ReadParameterReturnValueAsXml(string? name = null) + { + var outParams = xmlString?.GetElementsAfterSelf($"//{RN_ALIAS}:{methodName}Result", nsManager); + XElement? outParam = outParams?.FirstOrDefault(x => { - nsManager?.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); - var xml = ReadParameterReturnValueAsXml(); - var schema = xml.GetChildElements("//xs:sequence", nsManager); - var datas = xml.GetChildElements("//DocumentElement", nsManager); - return CreateDataTable(schema, datas, nsManager); - } + if (string.IsNullOrEmpty(name)) return true; + return x.Name == name; + }); + if (outParam == null) return default; + return outParam; + } + /// + /// 如果out参数或者ref参数的返回值可以解析为DataTable + /// + /// + public DataTable ReadParameterReturnValueAsDataTable() + { + nsManager?.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); + var xml = ReadParameterReturnValueAsXml(); + var schema = xml.GetChildElements("//xs:sequence", nsManager); + var datas = xml.GetChildElements("//DocumentElement", nsManager); + return CreateDataTable(schema, datas, nsManager); + } - #endregion + #endregion - /// - /// 从接口响应的Xml中获取数据,需要加上前缀 r - /// - /// - /// - public string? GetValue(string expression) => xmlString?.GetValue(expression, nsManager); + /// + /// 从接口响应的Xml中获取数据,需要加上前缀 r + /// + /// + /// + public string? GetValue(string expression) => xmlString?.GetValue(expression, nsManager); - /// - /// 从接口响应的Xml中获取数据,需要加上前缀 r - /// - /// - /// - private XElement? GetNode(string expression) => xmlString?.GetElement(expression, nsManager); + /// + /// 从接口响应的Xml中获取数据,需要加上前缀 r + /// + /// + /// + private XElement? GetNode(string expression) => xmlString?.GetElement(expression, nsManager); - /// - /// 从接口响应的Xml中获取数据,需要加上前缀 r - /// - /// 值类型 - /// - /// - public T? GetValue(string expression) where T : struct + /// + /// 从接口响应的Xml中获取数据,需要加上前缀 r + /// + /// 值类型 + /// + /// + public T? GetValue(string expression) where T : struct + { + //var str = xml?.GetValue(expression, nsManager); + //if (string.IsNullOrEmpty(str)) return default; + //var ret = Convert.ChangeType(str, typeof(T)); + //if (ret == null) return default; + //return (T?)ret; + return xmlString?.GetValue(expression, nsManager); + } + + private static DataTable CreateDataTable(IEnumerable schema, IEnumerable datas, XmlNamespaceManager? nsManager) + { + var dt = new DataTable(); + foreach (var element in schema) { - //var str = xml?.GetValue(expression, nsManager); - //if (string.IsNullOrEmpty(str)) return default; - //var ret = Convert.ChangeType(str, typeof(T)); - //if (ret == null) return default; - //return (T?)ret; - return xmlString?.GetValue(expression, nsManager); + var name = element.Attribute("name")!.Value; + var type = element.Attribute("type")!.Value; + dt.Columns.Add(name, ConvertElementType(type)); } - private static DataTable CreateDataTable(IEnumerable schema, IEnumerable datas, XmlNamespaceManager? nsManager) + foreach (var d in datas) { - var dt = new DataTable(); - foreach (var element in schema) + var row = dt.NewRow(); + foreach (DataColumn col in dt.Columns) { - var name = element.Attribute("name")!.Value; - var type = element.Attribute("type")!.Value; - dt.Columns.Add(name, ConvertElementType(type)); + var value = d.GetValue(col.ColumnName); + var v = value?.Parse(col.DataType) ?? DBNull.Value; + row[col.ColumnName] = v; } - - foreach (var d in datas) - { - var row = dt.NewRow(); - foreach (DataColumn col in dt.Columns) - { - var value = d.GetValue(col.ColumnName); - var v = value?.Parse(col.DataType) ?? DBNull.Value; - row[col.ColumnName] = v; - } - dt.Rows.Add(row); - } - return dt; + dt.Rows.Add(row); } + return dt; + } - private static Type ConvertElementType(string type) + private static Type ConvertElementType(string type) + { + return type switch { - return type switch - { - "xs:dateTime" => typeof(DateTime), - "xs:boolean" => typeof(bool), - "xs:integer" or "xs:int" => typeof(int), - "xs:decimal" => typeof(decimal), - "xs:long" => typeof(long), - "xs:short" => typeof(short), - _ => typeof(string), - }; - } + "xs:dateTime" => typeof(DateTime), + "xs:boolean" => typeof(bool), + "xs:integer" or "xs:int" => typeof(int), + "xs:decimal" => typeof(decimal), + "xs:long" => typeof(long), + "xs:short" => typeof(short), + _ => typeof(string), + }; } } \ No newline at end of file diff --git a/src/Toolkit/HttpHelper/SoapServiceConfiguration.cs b/src/Toolkit/HttpHelper/SoapServiceConfiguration.cs index c17bcb9..42e7978 100644 --- a/src/Toolkit/HttpHelper/SoapServiceConfiguration.cs +++ b/src/Toolkit/HttpHelper/SoapServiceConfiguration.cs @@ -19,6 +19,8 @@ namespace MT.Toolkit.HttpHelper /// /// SOAP服务配置 /// +#pragma warning disable + [Obsolete("please use LoggerProviderExtensions instead.")] public class SoapServiceConfiguration { public const int DEFAULT_CONCURRENCY_LIMIT = 10; diff --git a/src/Toolkit/HttpHelper/SoapServiceManager.cs b/src/Toolkit/HttpHelper/SoapServiceManager.cs index 97e5391..7eb7d31 100644 --- a/src/Toolkit/HttpHelper/SoapServiceManager.cs +++ b/src/Toolkit/HttpHelper/SoapServiceManager.cs @@ -3,35 +3,35 @@ #if NET6_0_OR_GREATER || NETCOREAPP3_1_OR_GREATER -namespace MT.Toolkit.HttpHelper +namespace MT.Toolkit.HttpHelper; + +[Obsolete("please use LoggerProviderExtensions instead.")] +internal class SoapServiceManager : ISoapServiceManager { - internal class SoapServiceManager : ISoapServiceManager - { - private readonly ConcurrentDictionary configs = new(); - private string? defaultKey; - public ConcurrentDictionary Configs => configs; - public string? DefaultKey => defaultKey; + private readonly ConcurrentDictionary configs = new(); + private string? defaultKey; + public ConcurrentDictionary Configs => configs; + public string? DefaultKey => defaultKey; - public ISoapServiceManager AddSoapService(string name, Action config) + public ISoapServiceManager AddSoapService(string name, Action config) + { + if (!configs.ContainsKey(name)) { - if (!configs.ContainsKey(name)) + var c = new SoapServiceConfiguration(name); + config.Invoke(c); + if (string.IsNullOrEmpty(c.Url)) { - var c = new SoapServiceConfiguration(name); - config.Invoke(c); - if (string.IsNullOrEmpty(c.Url)) - { - throw new ArgumentNullException("AddSoapService Url is null"); - } - configs[name] = c; + throw new ArgumentNullException("AddSoapService Url is null"); } - return this; + configs[name] = c; } + return this; + } - public ISoapServiceManager SetDefault(string key) - { - defaultKey = key; - return this; - } + public ISoapServiceManager SetDefault(string key) + { + defaultKey = key; + return this; } } #endif \ No newline at end of file diff --git a/src/Toolkit/HttpHelper/SoapVersion.cs b/src/Toolkit/HttpHelper/SoapVersion.cs index 37c6a8a..9dbafd4 100644 --- a/src/Toolkit/HttpHelper/SoapVersion.cs +++ b/src/Toolkit/HttpHelper/SoapVersion.cs @@ -1,8 +1,13 @@ -namespace MT.Toolkit.HttpHelper + +#pragma warning disable + +using System; + +namespace MT.Toolkit.HttpHelper; + +[Obsolete("Use SoapRequestHelper Package instead.", true)] +public enum SoapVersion { - public enum SoapVersion - { - Soap11, - Soap12, - } + Soap11, + Soap12, } diff --git a/src/Toolkit/LogTool/ConsoleLogger.cs b/src/Toolkit/LogTool/ConsoleLogger.cs index 8ed9eb6..c0f478b 100644 --- a/src/Toolkit/LogTool/ConsoleLogger.cs +++ b/src/Toolkit/LogTool/ConsoleLogger.cs @@ -1,28 +1,28 @@ using Microsoft.Extensions.Logging; using System; -namespace MT.Toolkit.LogTool +namespace MT.Toolkit.LogTool; +#pragma warning disable +[Obsolete("ConsoleLogger is deprecated, please use LoggerProviderExtensions instead.")] +public class ConsoleLogger : ISimpleLogger { - public class ConsoleLogger : ISimpleLogger + public ConsoleLogger(LoggerSetting configuration) { - public ConsoleLogger(LoggerSetting configuration) - { - LogConfig = configuration; - } - public LoggerSetting LogConfig { get; set; } + LogConfig = configuration; + } + public LoggerSetting LogConfig { get; set; } - - public void WriteLog(LogInfo logInfo) + + public void WriteLog(LogInfo logInfo) + { + if (!LogConfig.ConsoleColor.TryGetValue(logInfo.LogLevel, out var color)) { - if (!LogConfig.ConsoleColor.TryGetValue(logInfo.LogLevel, out var color)) - { - color = ConsoleColor.White; - } - Console.ForegroundColor = color; - Console.Write(logInfo.LogHeader()); - Console.ForegroundColor = ConsoleColor.White; - Console.Write(logInfo.LogCategory()); - Console.Write(logInfo.LogBody()); + color = ConsoleColor.White; } + Console.ForegroundColor = color; + Console.Write(logInfo.LogHeader()); + Console.ForegroundColor = ConsoleColor.White; + Console.Write(logInfo.LogCategory()); + Console.Write(logInfo.LogBody()); } } diff --git a/src/Toolkit/LogTool/DatabaseLogger.cs b/src/Toolkit/LogTool/DatabaseLogger.cs index 41148dd..6ea71ae 100644 --- a/src/Toolkit/LogTool/DatabaseLogger.cs +++ b/src/Toolkit/LogTool/DatabaseLogger.cs @@ -8,49 +8,49 @@ using System.Threading; using System.Threading.Tasks; -namespace MT.Toolkit.LogTool +namespace MT.Toolkit.LogTool; +#pragma warning disable +[Obsolete("ConsoleLogger is deprecated, please use LoggerProviderExtensions instead.")] +public class DatabaseLogger : ISimpleLogger { - public class DatabaseLogger : ISimpleLogger + private static Lazy? _instance; + private Lazy? _dbLogger; + private Lazy DbLogger => _dbLogger ??= new Lazy(() => { - private static Lazy? _instance; - private Lazy? _dbLogger; - private Lazy DbLogger => _dbLogger ??= new Lazy(() => + return LogConfig.DbLoggerFacotry?.Invoke() ?? throw new InvalidOperationException(); + }); + public static Lazy GetDbLogger(LoggerSetting setting) + { + _instance ??= new Lazy(() => { - return LogConfig.DbLoggerFacotry?.Invoke() ?? throw new InvalidOperationException(); + return new DatabaseLogger(setting); }); - public static Lazy GetDbLogger(LoggerSetting setting) - { - _instance ??= new Lazy(() => - { - return new DatabaseLogger(setting); - }); - return _instance; - } - static readonly ConcurrentQueue logQueue = new(); - public LoggerSetting LogConfig { get; set; } - private readonly CancellationTokenSource CancellationTokenSource = new CancellationTokenSource(); - Task dbTask; - private DatabaseLogger(LoggerSetting loggerSetting) + return _instance; + } + static readonly ConcurrentQueue logQueue = new(); + public LoggerSetting LogConfig { get; set; } + private readonly CancellationTokenSource CancellationTokenSource = new CancellationTokenSource(); + Task dbTask; + private DatabaseLogger(LoggerSetting loggerSetting) + { + LogConfig = loggerSetting; + var token = CancellationTokenSource.Token; + dbTask = new Task(async () => { - LogConfig = loggerSetting; - var token = CancellationTokenSource.Token; - dbTask = new Task(async () => + while (!CancellationTokenSource.IsCancellationRequested) { - while (!CancellationTokenSource.IsCancellationRequested) + token.WaitHandle.WaitOne(TimeSpan.FromSeconds(1)); + while (logQueue.TryDequeue(out var logInfo)) { - token.WaitHandle.WaitOne(TimeSpan.FromSeconds(1)); - while (logQueue.TryDequeue(out var logInfo)) - { - await DbLogger.Value.LogAsync(logInfo, token); - } + await DbLogger.Value.LogAsync(logInfo, token); } - }, token, TaskCreationOptions.LongRunning); - dbTask.Start(); - } + } + }, token, TaskCreationOptions.LongRunning); + dbTask.Start(); + } - public void WriteLog(LogInfo logInfo) - { - logQueue.Enqueue(logInfo); - } + public void WriteLog(LogInfo logInfo) + { + logQueue.Enqueue(logInfo); } } diff --git a/src/Toolkit/LogTool/DbLogger/DbLoggerProvider.cs b/src/Toolkit/LogTool/DbLogger/DbLoggerProvider.cs index 4db2f1f..9c16d9d 100644 --- a/src/Toolkit/LogTool/DbLogger/DbLoggerProvider.cs +++ b/src/Toolkit/LogTool/DbLogger/DbLoggerProvider.cs @@ -13,6 +13,8 @@ namespace MT.Toolkit.LogTool.DbLogger; +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] internal class DbLoggerProvider : ILoggerProvider { private readonly ConcurrentDictionary loggers = new(); diff --git a/src/Toolkit/LogTool/DbLogger/DbLoggerSetting.cs b/src/Toolkit/LogTool/DbLogger/DbLoggerSetting.cs index 4eb239f..d1160ec 100644 --- a/src/Toolkit/LogTool/DbLogger/DbLoggerSetting.cs +++ b/src/Toolkit/LogTool/DbLogger/DbLoggerSetting.cs @@ -5,15 +5,16 @@ using System.Text; using System.Threading.Tasks; -namespace MT.Toolkit.LogTool.DbLogger +namespace MT.Toolkit.LogTool.DbLogger; + +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +public interface IDbLoggerSetting { - public interface IDbLoggerSetting - { - void SetDbWriteLevel(string category, LogLevel logLevel); - void SetDbLogInfoFilter(Func filter); - /// - /// 指定如何获取IDbLogger实例,否则默认从Ioc容器中获取该实例 - /// - void SetDbLogger(Func factory); - } + void SetDbWriteLevel(string category, LogLevel logLevel); + void SetDbLogInfoFilter(Func filter); + /// + /// 指定如何获取IDbLogger实例,否则默认从Ioc容器中获取该实例 + /// + void SetDbLogger(Func factory); } diff --git a/src/Toolkit/LogTool/DbLogger/IDbLogger.cs b/src/Toolkit/LogTool/DbLogger/IDbLogger.cs index 1bd8043..31acece 100644 --- a/src/Toolkit/LogTool/DbLogger/IDbLogger.cs +++ b/src/Toolkit/LogTool/DbLogger/IDbLogger.cs @@ -5,10 +5,11 @@ using System.Threading; using System.Threading.Tasks; -namespace MT.Toolkit.LogTool.DbLogger +namespace MT.Toolkit.LogTool.DbLogger; + +#pragma warning disable +[Obsolete("ConsoleLogger is deprecated, please use LoggerProviderExtensions instead.")] +public interface IDbLogger { - public interface IDbLogger - { - Task LogAsync(LogInfo data, CancellationToken cancellationToken); - } + Task LogAsync(LogInfo data, CancellationToken cancellationToken); } diff --git a/src/Toolkit/LogTool/DbLogger/InternalDbLogger.cs b/src/Toolkit/LogTool/DbLogger/InternalDbLogger.cs index 0503c34..e1184c4 100644 --- a/src/Toolkit/LogTool/DbLogger/InternalDbLogger.cs +++ b/src/Toolkit/LogTool/DbLogger/InternalDbLogger.cs @@ -8,62 +8,63 @@ using System.Text; using System.Threading.Tasks; -namespace MT.Toolkit.LogTool.DbLogger +namespace MT.Toolkit.LogTool.DbLogger; + +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +internal class InternalDbLogger : ILogger { - internal class InternalDbLogger : ILogger + private readonly string category; + private LogLevel enableLevel; + private readonly DatabaseLogger dbLogger; + private readonly LoggerExternalScopeProvider scopeProvider = new LoggerExternalScopeProvider(); + + public InternalDbLogger(string category, IOptions options, DatabaseLogger dbLogger) { - private readonly string category; - private LogLevel enableLevel; - private readonly DatabaseLogger dbLogger; - private readonly LoggerExternalScopeProvider scopeProvider = new LoggerExternalScopeProvider(); + this.category = category; + this.dbLogger = dbLogger; + Setting = options.Value; + Setting.LogLevelSettingChanged += Setting_Changed; + this.enableLevel = Setting.GetLogLevel(LogType.Database, category); + } - public InternalDbLogger(string category, IOptions options, DatabaseLogger dbLogger) - { - this.category = category; - this.dbLogger = dbLogger; - Setting = options.Value; - Setting.LogLevelSettingChanged += Setting_Changed; - this.enableLevel = Setting.GetLogLevel(LogType.Database, category); - } + private void Setting_Changed() + { + this.enableLevel = Setting.GetLogLevel(LogType.Database, category); + } - private void Setting_Changed() - { - this.enableLevel = Setting.GetLogLevel(LogType.Database, category); - } + private LoggerSetting Setting { get; } + public IDisposable? BeginScope(TState state) where TState : notnull + { + return scopeProvider.Push(state); + } - private LoggerSetting Setting { get; } - public IDisposable? BeginScope(TState state) where TState : notnull - { - return scopeProvider.Push(state); - } + public bool IsEnabled(LogLevel logLevel) + { + return logLevel >= enableLevel; + } - public bool IsEnabled(LogLevel logLevel) + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (!IsEnabled(logLevel)) { - return logLevel >= enableLevel; + return; } - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + var logInfo = new LogInfo { - if (!IsEnabled(logLevel)) - { - return; - } - - var logInfo = new LogInfo - { - LogLevel = logLevel, - Message = formatter.Invoke(state, exception), - State = state, - EventId = eventId.Id, - EventName = eventId.Name, - Category = category, - Exception = exception - }; - scopeProvider.ForEachScope((scope, list) => list.Add(scope), logInfo.Scopes); - if (Setting.DbLogInfoFilter(logInfo)) - { - dbLogger.WriteLog(logInfo); - } + LogLevel = logLevel, + Message = formatter.Invoke(state, exception), + State = state, + EventId = eventId.Id, + EventName = eventId.Name, + Category = category, + Exception = exception + }; + scopeProvider.ForEachScope((scope, list) => list.Add(scope), logInfo.Scopes); + if (Setting.DbLogInfoFilter(logInfo)) + { + dbLogger.WriteLog(logInfo); } } } diff --git a/src/Toolkit/LogTool/DebugLogger.cs b/src/Toolkit/LogTool/DebugLogger.cs index 4774a44..37ebe1a 100644 --- a/src/Toolkit/LogTool/DebugLogger.cs +++ b/src/Toolkit/LogTool/DebugLogger.cs @@ -2,22 +2,23 @@ using System; using System.Diagnostics; -namespace MT.Toolkit.LogTool +namespace MT.Toolkit.LogTool; + +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +public class DebugLogger : ISimpleLogger { - public class DebugLogger : ISimpleLogger - { - public LoggerSetting LogConfig { get; set; } + public LoggerSetting LogConfig { get; set; } + + public DebugLogger(LoggerSetting configuration) + { + LogConfig = configuration; + } - public DebugLogger(LoggerSetting configuration) - { - LogConfig = configuration; - } - - public void WriteLog(LogInfo logInfo) - { - Debug.Write(logInfo.LogHeader()); - Debug.Write(logInfo.LogCategory()); - Debug.Write(logInfo.LogBody()); - } - } + public void WriteLog(LogInfo logInfo) + { + Debug.Write(logInfo.LogHeader()); + Debug.Write(logInfo.LogCategory()); + Debug.Write(logInfo.LogBody()); + } } diff --git a/src/Toolkit/LogTool/FileLogger/DeleteLogFileService.cs b/src/Toolkit/LogTool/FileLogger/DeleteLogFileService.cs index f6b8ac7..4f757cf 100644 --- a/src/Toolkit/LogTool/FileLogger/DeleteLogFileService.cs +++ b/src/Toolkit/LogTool/FileLogger/DeleteLogFileService.cs @@ -8,49 +8,48 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -namespace MT.Toolkit.LogTool.FileLogger +namespace MT.Toolkit.LogTool.FileLogger; + +internal class DeleteLogFileService(IOptionsMonitor config) : BackgroundService { - internal class DeleteLogFileService(IOptionsMonitor config) : BackgroundService + private readonly int? savedDays = config.CurrentValue.FileSavedDays; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - private readonly int? savedDays = config.CurrentValue.FileSavedDays; + if (!savedDays.HasValue) + { + return ; + } - protected override async Task ExecuteAsync(CancellationToken stoppingToken) + if (savedDays.Value < 0) { - if (!savedDays.HasValue) - { - return ; - } + return ; + } - if (savedDays.Value < 0) + while (!stoppingToken.IsCancellationRequested) + { + var logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs"); + if (!Directory.Exists(logPath)) { - return ; + await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken); } - - while (!stoppingToken.IsCancellationRequested) + try { - var logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs"); - if (!Directory.Exists(logPath)) - { - await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken); - } - try + var files = Directory.EnumerateFiles(logPath); + var deadline = DateTime.Now.AddDays(-1 * savedDays.Value); + foreach (var file in files) { - var files = Directory.EnumerateFiles(logPath); - var deadline = DateTime.Now.AddDays(-1 * savedDays.Value); - foreach (var file in files) + var fileinfo = new FileInfo(file); + if (fileinfo.CreationTime < deadline) { - var fileinfo = new FileInfo(file); - if (fileinfo.CreationTime < deadline) - { - File.Delete(file); - } + File.Delete(file); } - await Task.Delay(TimeSpan.FromDays(1), stoppingToken); - } - catch (DirectoryNotFoundException) - { - await Task.Delay(TimeSpan.FromHours(1), stoppingToken); } + await Task.Delay(TimeSpan.FromDays(1), stoppingToken); + } + catch (DirectoryNotFoundException) + { + await Task.Delay(TimeSpan.FromHours(1), stoppingToken); } } } diff --git a/src/Toolkit/LogTool/FileLogger/FileLoggerProvider.cs b/src/Toolkit/LogTool/FileLogger/FileLoggerProvider.cs index a1170f7..d19bec5 100644 --- a/src/Toolkit/LogTool/FileLogger/FileLoggerProvider.cs +++ b/src/Toolkit/LogTool/FileLogger/FileLoggerProvider.cs @@ -10,51 +10,52 @@ using System.Text; using System.Threading.Tasks; -namespace MT.Toolkit.LogTool.FileLogger +namespace MT.Toolkit.LogTool.FileLogger; + +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +internal class FileLoggerProvider : ILoggerProvider { - internal class FileLoggerProvider : ILoggerProvider + private readonly ConcurrentDictionary loggers = new(); + private readonly Lazy fileLogger; + private readonly IOptions option; + private readonly IConfiguration configuration; + private IDisposable reload; + public FileLoggerProvider(IOptions option, IConfiguration configuration) { - private readonly ConcurrentDictionary loggers = new(); - private readonly Lazy fileLogger; - private readonly IOptions option; - private readonly IConfiguration configuration; - private IDisposable reload; - public FileLoggerProvider(IOptions option, IConfiguration configuration) - { - fileLogger = LocalFileLogger.GetFileLogger(option.Value); - this.option = option; - this.configuration = configuration; - Set(); - reload = ChangeToken.OnChange(() => this.configuration.GetReloadToken(), Set); - - } - private void Set() + fileLogger = LocalFileLogger.GetFileLogger(option.Value); + this.option = option; + this.configuration = configuration; + Set(); + reload = ChangeToken.OnChange(() => this.configuration.GetReloadToken(), Set); + + } + private void Set() + { + var set = configuration.GetSection("Logging:SimpleFileLogger").GetChildren(); + if (!set.Any()) return; + foreach (var item in set) { - var set = configuration.GetSection("Logging:SimpleFileLogger").GetChildren(); - if (!set.Any()) return; - foreach (var item in set) + var key = item.Key; + var value = item.Value; + if (key is null || value is null) continue; + if (Enum.TryParse(typeof(LogLevel), value, out var result) && result is LogLevel logLevel) { - var key = item.Key; - var value = item.Value; - if (key is null || value is null) continue; - if (Enum.TryParse(typeof(LogLevel), value, out var result) && result is LogLevel logLevel) - { - option.Value.AddOrUpdate(LogType.File, key, logLevel); - } + option.Value.AddOrUpdate(LogType.File, key, logLevel); } - option.Value.NotifyLogLevelSettingChanged(); - } - public ILogger CreateLogger(string categoryName) - { - return loggers.GetOrAdd(categoryName, new InternalFileLogger(categoryName, option, fileLogger.Value)); } + option.Value.NotifyLogLevelSettingChanged(); + } + public ILogger CreateLogger(string categoryName) + { + return loggers.GetOrAdd(categoryName, new InternalFileLogger(categoryName, option, fileLogger.Value)); + } - public void Dispose() - { - loggers.Clear(); - reload?.Dispose(); - GC.SuppressFinalize(this); - } + public void Dispose() + { + loggers.Clear(); + reload?.Dispose(); + GC.SuppressFinalize(this); } } #endif \ No newline at end of file diff --git a/src/Toolkit/LogTool/FileLogger/FileLoggerSetting.cs b/src/Toolkit/LogTool/FileLogger/FileLoggerSetting.cs index 4904361..08fcce3 100644 --- a/src/Toolkit/LogTool/FileLogger/FileLoggerSetting.cs +++ b/src/Toolkit/LogTool/FileLogger/FileLoggerSetting.cs @@ -5,30 +5,31 @@ using System.Text; using System.Threading.Tasks; -namespace MT.Toolkit.LogTool.FileLogger +namespace MT.Toolkit.LogTool.FileLogger; + +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +public interface IFileLoggerSetting { - public interface IFileLoggerSetting - { - /// - /// 文件保留天数,默认7天 - /// - int FileSavedDays { get; set; } - /// - /// 日志保存目录 - /// - string? LogFileFolder { get; set; } - /// - /// 文件大小,默认1m - /// - long LogFileSize { get; set; } - public bool SaveByCategory { get; set; } - /// - /// 设置写入文件的日志级别 - /// - void SetFileWriteLevel(string category, LogLevel logLevel); - /// - /// 设置写入文件的日志过滤 - /// - void SetFileLogInfoFilter(Func filter); - } + /// + /// 文件保留天数,默认7天 + /// + int FileSavedDays { get; set; } + /// + /// 日志保存目录 + /// + string? LogFileFolder { get; set; } + /// + /// 文件大小,默认1m + /// + long LogFileSize { get; set; } + public bool SaveByCategory { get; set; } + /// + /// 设置写入文件的日志级别 + /// + void SetFileWriteLevel(string category, LogLevel logLevel); + /// + /// 设置写入文件的日志过滤 + /// + void SetFileLogInfoFilter(Func filter); } diff --git a/src/Toolkit/LogTool/FileLogger/InternalFileLogger.cs b/src/Toolkit/LogTool/FileLogger/InternalFileLogger.cs index 66ac829..f8f5b21 100644 --- a/src/Toolkit/LogTool/FileLogger/InternalFileLogger.cs +++ b/src/Toolkit/LogTool/FileLogger/InternalFileLogger.cs @@ -9,6 +9,8 @@ namespace MT.Toolkit.LogTool.FileLogger; +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] internal class InternalFileLogger : ILogger { private readonly string category; diff --git a/src/Toolkit/LogTool/ISimpleLogger.cs b/src/Toolkit/LogTool/ISimpleLogger.cs index 26db8f7..564553b 100644 --- a/src/Toolkit/LogTool/ISimpleLogger.cs +++ b/src/Toolkit/LogTool/ISimpleLogger.cs @@ -1,11 +1,11 @@ using Microsoft.Extensions.Logging; using System; -namespace MT.Toolkit.LogTool +namespace MT.Toolkit.LogTool; +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +public interface ISimpleLogger { - public interface ISimpleLogger - { - //LoggerSetting LogConfig { get; set; } - void WriteLog(LogInfo logInfo); - } + //LoggerSetting LogConfig { get; set; } + void WriteLog(LogInfo logInfo); } diff --git a/src/Toolkit/LogTool/LocalFileLogger.cs b/src/Toolkit/LogTool/LocalFileLogger.cs index a297f3f..649046a 100644 --- a/src/Toolkit/LogTool/LocalFileLogger.cs +++ b/src/Toolkit/LogTool/LocalFileLogger.cs @@ -9,140 +9,141 @@ using System.Threading; using System.Threading.Tasks; -namespace MT.Toolkit.LogTool +namespace MT.Toolkit.LogTool; + +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +public class LocalFileLogger : ISimpleLogger { - public class LocalFileLogger : ISimpleLogger + struct LogItem { - struct LogItem - { - public string Path { get; set; } - public string Content { get; set; } - } - private static Lazy? _instance; + public string Path { get; set; } + public string Content { get; set; } + } + private static Lazy? _instance; - public static Lazy GetFileLogger(LoggerSetting configuration) + public static Lazy GetFileLogger(LoggerSetting configuration) + { + _instance ??= new Lazy(() => { - _instance ??= new Lazy(() => - { - return new LocalFileLogger(configuration); - }); - return _instance; - } + return new LocalFileLogger(configuration); + }); + return _instance; + } - public LoggerSetting LogConfig { get; set; } + public LoggerSetting LogConfig { get; set; } - static readonly ConcurrentQueue logQueue = new ConcurrentQueue(); + static readonly ConcurrentQueue logQueue = new ConcurrentQueue(); - private string separator = "----------------------------------------------------------------------------------------------------------------------"; - Task writeTask; - CancellationTokenSource CancellationTokenSource = new CancellationTokenSource(); - private LocalFileLogger(LoggerSetting configuration) - { - LogConfig = configuration; - var token = CancellationTokenSource.Token; - writeTask = new Task(() => + private string separator = "----------------------------------------------------------------------------------------------------------------------"; + Task writeTask; + CancellationTokenSource CancellationTokenSource = new CancellationTokenSource(); + private LocalFileLogger(LoggerSetting configuration) + { + LogConfig = configuration; + var token = CancellationTokenSource.Token; + writeTask = new Task(() => + { + while (!CancellationTokenSource.IsCancellationRequested) { - while (!CancellationTokenSource.IsCancellationRequested) + // 阻塞1秒 + token.WaitHandle.WaitOne(TimeSpan.FromSeconds(1)); + List temp = new List(); + + while(logQueue.TryDequeue(out var logItem)) { - // 阻塞1秒 - token.WaitHandle.WaitOne(TimeSpan.FromSeconds(1)); - List temp = new List(); - - while(logQueue.TryDequeue(out var logItem)) + string logPath = logItem.Path; + string logMergeContent = $"{logItem.Content}{separator}{Environment.NewLine}"; + string[]? logArr = temp.FirstOrDefault(d => d[0].Equals(logPath)); + if (logArr != null) { - string logPath = logItem.Path; - string logMergeContent = $"{logItem.Content}{separator}{Environment.NewLine}"; - string[]? logArr = temp.FirstOrDefault(d => d[0].Equals(logPath)); - if (logArr != null) - { - logArr[1] = string.Concat(logArr[1], logMergeContent); - } - else - { - logArr = - [ - logPath, - logMergeContent - ]; - temp.Add(logArr); - } + logArr[1] = string.Concat(logArr[1], logMergeContent); } - - foreach (var item in temp) + else { - WriteText(item[0], item[1]); + logArr = + [ + logPath, + logMergeContent + ]; + temp.Add(logArr); } } - }, token, TaskCreationOptions.LongRunning); - writeTask.Start(); - } - public void WriteLog(LogInfo logInfo) - { - logQueue.Enqueue(new LogItem - { - Path = GetLogPath(LogConfig, logInfo.Category), - Content = logInfo.FormatLogMessage() - }); - } - private static string GetLogPath(LoggerSetting setting, string? category) + foreach (var item in temp) + { + WriteText(item[0], item[1]); + } + } + }, token, TaskCreationOptions.LongRunning); + writeTask.Start(); + } + public void WriteLog(LogInfo logInfo) + { + logQueue.Enqueue(new LogItem { - string newFilePath; - var logDir = setting.LogFileFolder ?? Path.Combine(Environment.CurrentDirectory, "logs"); - Directory.CreateDirectory(logDir); - string extension = ".log"; - string fileNameNotExt = !string.IsNullOrEmpty(category) && setting.SaveByCategory ? $"{DateTime.Now:yyyy-MM-dd}_{category}_Part" : $"{DateTime.Now:yyyy-MM-dd}_Part"; - string fileNamePattern = string.Concat(fileNameNotExt, "*", extension); - string[] filePaths = Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly); + Path = GetLogPath(LogConfig, logInfo.Category), + Content = logInfo.FormatLogMessage() + }); + } + + private static string GetLogPath(LoggerSetting setting, string? category) + { + string newFilePath; + var logDir = setting.LogFileFolder ?? Path.Combine(Environment.CurrentDirectory, "logs"); + Directory.CreateDirectory(logDir); + string extension = ".log"; + string fileNameNotExt = !string.IsNullOrEmpty(category) && setting.SaveByCategory ? $"{DateTime.Now:yyyy-MM-dd}_{category}_Part" : $"{DateTime.Now:yyyy-MM-dd}_Part"; + string fileNamePattern = string.Concat(fileNameNotExt, "*", extension); + string[] filePaths = Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly); - if (filePaths.Length > 0) + if (filePaths.Length > 0) + { + int fileMaxLen = filePaths.Max(d => d.Length); + string lastFilePath = filePaths.Where(d => d.Length == fileMaxLen).OrderByDescending(d => d).First(); + if (new FileInfo(lastFilePath).Length > setting.LogFileSize) { - int fileMaxLen = filePaths.Max(d => d.Length); - string lastFilePath = filePaths.Where(d => d.Length == fileMaxLen).OrderByDescending(d => d).First(); - if (new FileInfo(lastFilePath).Length > setting.LogFileSize) - { - var no = new Regex(@"(?<=Part)(\d+)").Match(Path.GetFileName(lastFilePath)).Value; - var parse = int.TryParse(no, out int tempno); - var formatno = $"{(parse ? tempno + 1 : tempno)}"; - var newFileName = string.Concat(fileNameNotExt, formatno, extension); - newFilePath = Path.Combine(logDir, newFileName); - } - else - { - newFilePath = lastFilePath; - } + var no = new Regex(@"(?<=Part)(\d+)").Match(Path.GetFileName(lastFilePath)).Value; + var parse = int.TryParse(no, out int tempno); + var formatno = $"{(parse ? tempno + 1 : tempno)}"; + var newFileName = string.Concat(fileNameNotExt, formatno, extension); + newFilePath = Path.Combine(logDir, newFileName); } else { - var newFileName = string.Concat(fileNameNotExt, $"{0}", extension); - newFilePath = Path.Combine(logDir, newFileName); + newFilePath = lastFilePath; } - - return newFilePath; + } + else + { + var newFileName = string.Concat(fileNameNotExt, $"{0}", extension); + newFilePath = Path.Combine(logDir, newFileName); } - private static void WriteText(string logPath, string logContent) + return newFilePath; + } + + private static void WriteText(string logPath, string logContent) + { + try { - try - { - if (!File.Exists(logPath)) - { - File.CreateText(logPath).Close(); - } - File.AppendAllText(logPath, logContent); - } - catch (Exception) + if (!File.Exists(logPath)) { - // ignored - //Console.Write(ex.Message); + File.CreateText(logPath).Close(); } + File.AppendAllText(logPath, logContent); } - - ~LocalFileLogger() + catch (Exception) { - CancellationTokenSource.Cancel(); - writeTask.Wait(); - writeTask.Dispose(); + // ignored + //Console.Write(ex.Message); } } + + ~LocalFileLogger() + { + CancellationTokenSource.Cancel(); + writeTask.Wait(); + writeTask.Dispose(); + } } diff --git a/src/Toolkit/LogTool/LogExtension/InternalLogger.cs b/src/Toolkit/LogTool/LogExtension/InternalLogger.cs index a5ef2cd..8c13334 100644 --- a/src/Toolkit/LogTool/LogExtension/InternalLogger.cs +++ b/src/Toolkit/LogTool/LogExtension/InternalLogger.cs @@ -3,52 +3,52 @@ using System; using Microsoft.Extensions.Logging; -namespace MT.Toolkit.LogTool.LogExtension -{ +namespace MT.Toolkit.LogTool.LogExtension; - internal class InternalLogger : ILogger - { - private readonly string name; - private readonly Func getCurrentConfig; - private readonly Logger logger; - public InternalLogger(string name, Func getCurrentConfig) - { - this.name = name; - this.getCurrentConfig = getCurrentConfig; - logger = new Logger(this.getCurrentConfig()); - } - public IDisposable BeginScope(TState state) where TState : notnull - { - return NullScope.Instance; - } - - public bool IsEnabled(LogLevel logLevel) - { - return logger.IsEnabled(logLevel); - } - - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) - { - if (!IsEnabled(logLevel)) - { - return; - } - logger.Log(logLevel, state, formatter, name, eventId.Id, eventId.Name, exception); - } - - internal sealed class NullScope : IDisposable - { - public static NullScope Instance { get; } = new NullScope(); - - - private NullScope() - { - } - - public void Dispose() - { - } - } - } +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +internal class InternalLogger : ILogger +{ + private readonly string name; + private readonly Func getCurrentConfig; + private readonly Logger logger; + public InternalLogger(string name, Func getCurrentConfig) + { + this.name = name; + this.getCurrentConfig = getCurrentConfig; + logger = new Logger(this.getCurrentConfig()); + } + public IDisposable BeginScope(TState state) where TState : notnull + { + return NullScope.Instance; + } + + public bool IsEnabled(LogLevel logLevel) + { + return logger.IsEnabled(logLevel); + } + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + { + if (!IsEnabled(logLevel)) + { + return; + } + logger.Log(logLevel, state, formatter, name, eventId.Id, eventId.Name, exception); + } + + internal sealed class NullScope : IDisposable + { + public static NullScope Instance { get; } = new NullScope(); + + + private NullScope() + { + } + + public void Dispose() + { + } + } } #endif diff --git a/src/Toolkit/LogTool/LogExtension/SimpleLogProvider.cs b/src/Toolkit/LogTool/LogExtension/SimpleLogProvider.cs index f417178..aec8da4 100644 --- a/src/Toolkit/LogTool/LogExtension/SimpleLogProvider.cs +++ b/src/Toolkit/LogTool/LogExtension/SimpleLogProvider.cs @@ -7,59 +7,59 @@ using System; using System.Collections.Concurrent; -namespace MT.Toolkit.LogTool.LogExtension -{ +namespace MT.Toolkit.LogTool.LogExtension; - [ProviderAlias("SimgleLog")] - public class SimpleLogProvider : ILoggerProvider - { - private bool disposedValue; - private readonly IDisposable? _onChangeToken; - private LoggerSetting _currentConfig; - private readonly ConcurrentDictionary _loggers = - new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +[ProviderAlias("SimgleLog")] +public class SimpleLogProvider : ILoggerProvider +{ + private bool disposedValue; + private readonly IDisposable? _onChangeToken; + private LoggerSetting _currentConfig; + private readonly ConcurrentDictionary _loggers = + new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - public SimpleLogProvider(IOptionsMonitor config) - { - _currentConfig = config.CurrentValue; - _onChangeToken = config.OnChange(updatedConfig => _currentConfig = updatedConfig); - } + public SimpleLogProvider(IOptionsMonitor config) + { + _currentConfig = config.CurrentValue; + _onChangeToken = config.OnChange(updatedConfig => _currentConfig = updatedConfig); + } - public ILogger CreateLogger(string categoryName) => - _loggers.GetOrAdd(categoryName, name => new InternalLogger(name, GetCurrentConfig)); + public ILogger CreateLogger(string categoryName) => + _loggers.GetOrAdd(categoryName, name => new InternalLogger(name, GetCurrentConfig)); - LoggerSetting GetCurrentConfig() => _currentConfig; + LoggerSetting GetCurrentConfig() => _currentConfig; - protected virtual void Dispose(bool disposing) - { - if (!disposedValue) - { - if (disposing) - { - // 释放托管状态(托管对象) - _loggers.Clear(); - _onChangeToken?.Dispose(); - } + protected virtual void Dispose(bool disposing) + { + if (!disposedValue) + { + if (disposing) + { + // 释放托管状态(托管对象) + _loggers.Clear(); + _onChangeToken?.Dispose(); + } - // 释放未托管的资源(未托管的对象)并重写终结器 - // 将大型字段设置为 null - disposedValue = true; - } - } + // 释放未托管的资源(未托管的对象)并重写终结器 + // 将大型字段设置为 null + disposedValue = true; + } + } - // // 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器 - // ~SimpleLogProvider() - // { - // // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中 - // Dispose(disposing: false); - // } + // // 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器 + // ~SimpleLogProvider() + // { + // // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中 + // Dispose(disposing: false); + // } - public void Dispose() - { - // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中 - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - } + public void Dispose() + { + // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中 + Dispose(disposing: true); + GC.SuppressFinalize(this); + } } #endif diff --git a/src/Toolkit/LogTool/LogInfo.cs b/src/Toolkit/LogTool/LogInfo.cs index 3ea65e3..2cc5194 100644 --- a/src/Toolkit/LogTool/LogInfo.cs +++ b/src/Toolkit/LogTool/LogInfo.cs @@ -3,92 +3,92 @@ using System.Collections; using System.Collections.Generic; -namespace MT.Toolkit.LogTool +namespace MT.Toolkit.LogTool; +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +public class LogInfo { - public class LogInfo - { - /// - /// 时间 - /// - public DateTime Time { get; set; } = DateTime.Now; - /// - /// 线程id - /// - public int ThreadId { get; set; } - /// - /// 日志级别 - /// - public LogLevel LogLevel { get; set; } - /// - /// 异常信息 - /// - public string? Message { get; set; } + /// + /// 时间 + /// + public DateTime Time { get; set; } = DateTime.Now; + /// + /// 线程id + /// + public int ThreadId { get; set; } + /// + /// 日志级别 + /// + public LogLevel LogLevel { get; set; } + /// + /// 异常信息 + /// + public string? Message { get; set; } - /// - /// 异常对象 - /// - public Exception? Exception { get; set; } - public int EventId { get; set; } - public string? EventName { get; set; } - public string? Category { get; set; } + /// + /// 异常对象 + /// + public Exception? Exception { get; set; } + public int EventId { get; set; } + public string? EventName { get; set; } + public string? Category { get; set; } - public object? State { get; set; } - public string? Source { get; set; } - /// - /// 触发日志的行数 - /// - public int LogLine { get; set; } - /// - /// 触发日志的方法 - /// - public string? LogMember { get; set; } - public bool Handled { get; set; } - public List Scopes { get; set; } = []; - } + public object? State { get; set; } + public string? Source { get; set; } + /// + /// 触发日志的行数 + /// + public int LogLine { get; set; } /// - /// 日志信息 + /// 触发日志的方法 /// - public class LogInfo : LogInfo + public string? LogMember { get; set; } + public bool Handled { get; set; } + public List Scopes { get; set; } = []; +} +/// +/// 日志信息 +/// +public class LogInfo : LogInfo +{ + public new TState? State { get; set; } +} + +public static class LogInfoExtensions +{ + public static string FormatLogMessage(this LogInfo self) { - public new TState? State { get; set; } + //[TId:{self.ThreadId.ToString().PadLeft(5, '0')}] + return $"{self.LogHeader()}{self.LogCategory()}{self.LogScope()}{self.LogBody()}"; } - - public static class LogInfoExtensions + public static string LogScope(this LogInfo self) { - public static string FormatLogMessage(this LogInfo self) - { - //[TId:{self.ThreadId.ToString().PadLeft(5, '0')}] - return $"{self.LogHeader()}{self.LogCategory()}{self.LogScope()}{self.LogBody()}"; - } - public static string LogScope(this LogInfo self) - { - if (self.Scopes?.Count > 0) - { - return $" {string.Join(" => ", self.Scopes)}{Environment.NewLine}"; - } - return string.Empty; - } - public static string LogHeader(this LogInfo self) + if (self.Scopes?.Count > 0) { - return $"[{self.Time:yyyy-MM-dd HH:mm:ss}][{self.LogLevel}]:"; - } - public static string LogCategory(this LogInfo self) - { - return $"{self.Category}[{self.EventId}]{Environment.NewLine}"; - } - public static string LogBody(this LogInfo self) - { - return $" {self.LogException()}{self.LogTrace()}"; + return $" {string.Join(" => ", self.Scopes)}{Environment.NewLine}"; } + return string.Empty; + } + public static string LogHeader(this LogInfo self) + { + return $"[{self.Time:yyyy-MM-dd HH:mm:ss}][{self.LogLevel}]:"; + } + public static string LogCategory(this LogInfo self) + { + return $"{self.Category}[{self.EventId}]{Environment.NewLine}"; + } + public static string LogBody(this LogInfo self) + { + return $" {self.LogException()}{self.LogTrace()}"; + } - public static string LogException(this LogInfo self) - { - return $"{self.Message}{(self.Exception == null ? "" : Environment.NewLine)}"; - } + public static string LogException(this LogInfo self) + { + return $"{self.Message}{(self.Exception == null ? "" : Environment.NewLine)}"; + } - public static string LogTrace(this LogInfo self) - { - return $"{self.Exception?.StackTrace}{Environment.NewLine}"; - } + public static string LogTrace(this LogInfo self) + { + return $"{self.Exception?.StackTrace}{Environment.NewLine}"; } } diff --git a/src/Toolkit/LogTool/Logger.cs b/src/Toolkit/LogTool/Logger.cs index af2edbb..ad029b6 100644 --- a/src/Toolkit/LogTool/Logger.cs +++ b/src/Toolkit/LogTool/Logger.cs @@ -2,81 +2,82 @@ using System; using System.Collections.Generic; -namespace MT.Toolkit.LogTool +namespace MT.Toolkit.LogTool; + +#pragma warning disable +[Obsolete("please use LoggerProviderExtensions instead.")] +internal class Logger { - internal class Logger + internal Dictionary LoggerDict { get; } = new Dictionary(); + private LoggerSetting logConfig; + + public Logger(LoggerSetting config) { - internal Dictionary LoggerDict { get; } = new Dictionary(); - private LoggerSetting logConfig; + logConfig = config; + Enable(config.EnabledLogType); + } - public Logger(LoggerSetting config) + public void Enable(LogType logType) + { + if (logType.HasFlag(LogType.Console)) { - logConfig = config; - Enable(config.EnabledLogType); + LoggerDict[LogType.Console] = new ConsoleLogger(logConfig); } - - public void Enable(LogType logType) + if (logType.HasFlag(LogType.Debug)) { - if (logType.HasFlag(LogType.Console)) - { - LoggerDict[LogType.Console] = new ConsoleLogger(logConfig); - } - if (logType.HasFlag(LogType.Debug)) - { - LoggerDict[LogType.Debug] = new DebugLogger(logConfig); - } - if (logType.HasFlag(LogType.File)) - { - LoggerDict[LogType.File] = LocalFileLogger.GetFileLogger(logConfig).Value; - } - if (logType.HasFlag(LogType.Database)) - { - LoggerDict[LogType.Database] = DatabaseLogger.GetDbLogger(logConfig).Value; - } - if (logType.HasFlag(LogType.Custom)) - { - LoggerDict[LogType.Custom] = logConfig.CustomLogger?.Invoke(logConfig) ?? throw new Exception("未设置自定义日志对象"); - } + LoggerDict[LogType.Debug] = new DebugLogger(logConfig); } - - public bool IsEnabled(LogLevel logLevel) + if (logType.HasFlag(LogType.File)) { - return true; + LoggerDict[LogType.File] = LocalFileLogger.GetFileLogger(logConfig).Value; } - - public void Log(LogLevel logLevel, TState state, Func formatter, string category = "", int eventId = 0, string eventName = "", Exception? exception = null) + if (logType.HasFlag(LogType.Database)) { - var logInfo = new LogInfo() - { - LogLevel = logLevel, - Message = formatter.Invoke(state, exception), - EventId = eventId, - EventName = eventName, - Category = category, - Exception = exception - }; - Write(logLevel, logInfo); + LoggerDict[LogType.Database] = DatabaseLogger.GetDbLogger(logConfig).Value; + } + if (logType.HasFlag(LogType.Custom)) + { + LoggerDict[LogType.Custom] = logConfig.CustomLogger?.Invoke(logConfig) ?? throw new Exception("未设置自定义日志对象"); } + } + + public bool IsEnabled(LogLevel logLevel) + { + return true; + } + + public void Log(LogLevel logLevel, TState state, Func formatter, string category = "", int eventId = 0, string eventName = "", Exception? exception = null) + { + var logInfo = new LogInfo() + { + LogLevel = logLevel, + Message = formatter.Invoke(state, exception), + EventId = eventId, + EventName = eventName, + Category = category, + Exception = exception + }; + Write(logLevel, logInfo); + } - object locker = new object(); - public void Write(LogLevel level, LogInfo logInfo) + object locker = new object(); + public void Write(LogLevel level, LogInfo logInfo) + { + lock (locker) { - lock (locker) + logConfig.LogActionIntercept?.Invoke(logInfo); + if (logInfo.Handled) { - logConfig.LogActionIntercept?.Invoke(logInfo); - if (logInfo.Handled) - { - return; - } + return; + } - foreach (var item in LoggerDict) + foreach (var item in LoggerDict) + { + if (!logConfig.IsEnabled(item.Key, logInfo.Category, level)) { - if (!logConfig.IsEnabled(item.Key, logInfo.Category, level)) - { - continue; - } - item.Value.WriteLog(logInfo); + continue; } + item.Value.WriteLog(logInfo); } } } diff --git a/src/Toolkit/LogTool/LoggerSetting.cs b/src/Toolkit/LogTool/LoggerSetting.cs index b09d839..8ec5cfe 100644 --- a/src/Toolkit/LogTool/LoggerSetting.cs +++ b/src/Toolkit/LogTool/LoggerSetting.cs @@ -6,9 +6,10 @@ using System.Collections.Generic; using System.Linq; #pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释 - +#pragma warning disable namespace MT.Toolkit.LogTool { + [Obsolete("please use LoggerProviderExtensions instead.")] public static class LoggerSettingExtensions { public static bool IsEnabled(this LoggerSetting loggerSetting, LogType logType, string? category, LogLevel logLevel) diff --git a/src/Toolkit/LogTool/SerivceExtension.cs b/src/Toolkit/LogTool/SerivceExtension.cs index 34d4439..a07e704 100644 --- a/src/Toolkit/LogTool/SerivceExtension.cs +++ b/src/Toolkit/LogTool/SerivceExtension.cs @@ -7,9 +7,8 @@ namespace MT.Toolkit.LogTool { - /// - /// - /// +#pragma warning disable + [Obsolete("please use LoggerProviderExtensions instead.")] public static class SerivceExtension { [Obsolete] diff --git a/src/Toolkit/LogTool/SimpleLogLevel.cs b/src/Toolkit/LogTool/SimpleLogLevel.cs index 305bd12..c7301db 100644 --- a/src/Toolkit/LogTool/SimpleLogLevel.cs +++ b/src/Toolkit/LogTool/SimpleLogLevel.cs @@ -2,7 +2,9 @@ namespace MT.Toolkit.LogTool { - [Flags] +#pragma warning disable + [Obsolete("please use LoggerProviderExtensions instead.")] + [Flags] public enum LogType { Console = 1, @@ -14,8 +16,9 @@ public enum LogType /// /// 日志级别 /// + [Obsolete("please use LoggerProviderExtensions instead.")] public enum SimpleLogLevel - { + { Trace, /// /// 信息级别 diff --git a/src/Toolkit/LogTool/SimpleLogger.cs b/src/Toolkit/LogTool/SimpleLogger.cs index 9201573..9aaa3e5 100644 --- a/src/Toolkit/LogTool/SimpleLogger.cs +++ b/src/Toolkit/LogTool/SimpleLogger.cs @@ -4,7 +4,9 @@ namespace MT.Toolkit.LogTool { - public class SimpleLogger +#pragma warning disable + [Obsolete("please use LoggerProviderExtensions instead.")] + public class SimpleLogger { static Logger? logger; public static void Config(Action action) diff --git a/src/Toolkit/Machine/CpuHelper.cs b/src/Toolkit/Machine/CpuHelper.cs index dbdea8e..9fd4bad 100644 --- a/src/Toolkit/Machine/CpuHelper.cs +++ b/src/Toolkit/Machine/CpuHelper.cs @@ -8,7 +8,10 @@ namespace MT.Toolkit.Machine { - public static class CpuHelper + /// + /// Cpu相关帮助类 + /// + public static class CpuHelper { private static ICpu cpuHelper = PlatformHelper.GetCpuHelper(); /// diff --git a/src/Toolkit/Machine/DiskHelper.cs b/src/Toolkit/Machine/DiskHelper.cs index 2a7b632..35ff479 100644 --- a/src/Toolkit/Machine/DiskHelper.cs +++ b/src/Toolkit/Machine/DiskHelper.cs @@ -4,13 +4,19 @@ using System.Text; using System.Threading.Tasks; -namespace MT.Toolkit.Machine +namespace MT.Toolkit.Machine; + +/// +/// 硬盘相关工具类 +/// +public static class DiskHelper { - public static class DiskHelper - { - public static void GetDisk() - { - Environment.GetLogicalDrives(); - } - } + /// + /// 获取所有逻辑驱动器 + /// + /// + public static string[] GetDrives() + { + return Environment.GetLogicalDrives(); + } } diff --git a/src/Toolkit/Machine/MemoryHelper.cs b/src/Toolkit/Machine/MemoryHelper.cs index 486c195..54fb483 100644 --- a/src/Toolkit/Machine/MemoryHelper.cs +++ b/src/Toolkit/Machine/MemoryHelper.cs @@ -7,7 +7,10 @@ namespace MT.Toolkit.Machine { - public static class MemoryHelper + /// + /// 内存相关工具类 + /// + public static class MemoryHelper { /// /// 机器总内存 @@ -18,13 +21,21 @@ public static double TotalMemory() return 0; } - public static long ProcessMemoryUsage() + /// + /// 进程内存使用量 + /// + /// + public static long ProcessMemoryUsage() { //return Process.GetCurrentProcess().WorkingSet64; return Environment.WorkingSet; } - public static long TotalUsage() + /// + /// 总内存使用量 + /// + /// + public static long TotalUsage() { var process = Process.GetProcesses(); long totalB = 0; diff --git a/src/Toolkit/Machine/SysHelper.cs b/src/Toolkit/Machine/SysHelper.cs index 35627fd..6cd6e29 100644 --- a/src/Toolkit/Machine/SysHelper.cs +++ b/src/Toolkit/Machine/SysHelper.cs @@ -7,77 +7,113 @@ #else using System.Runtime.InteropServices; #endif -namespace MT.Toolkit.Machine +namespace MT.Toolkit.Machine; + +/// +/// 系统信息帮助类 +/// +public static class SysHelper { - public static class SysHelper - { - public static string OsPlatform() - { + /// + /// 获取操作系统平台 + /// + /// + /// + public static string OsPlatform() + { #if NET40_OR_GREATER - return "Windows"; + return "Windows"; #else - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return "Windows"; - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return "Linux"; - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return "OS X"; - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) - { - return "FreeBSD"; - } - else - throw new Exception("Unknow OsPlatform"); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return "Windows"; + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return "Linux"; + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + return "OS X"; + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) + { + return "FreeBSD"; + } + else + throw new Exception("Unknow OsPlatform"); #endif - } - public static string OSArchitecture() - { + } + + /// + /// 获取操作系统架构 + /// + /// + public static string OSArchitecture() + { #if NET40_OR_GREATER - return Environment.Is64BitOperatingSystem ? "X64" : "X86"; + return Environment.Is64BitOperatingSystem ? "X64" : "X86"; #else - return RuntimeInformation.OSArchitecture.ToString(); + return RuntimeInformation.OSArchitecture.ToString(); #endif - } + } #if NET5_0_OR_GREATER - public static string OSDescription() - { - return RuntimeInformation.OSDescription; - } - public static string ProcessArchitecture() - { - return RuntimeInformation.ProcessArchitecture.ToString(); - } + /// + /// 获取操作系统描述 + /// + /// + public static string OSDescription() + { + return RuntimeInformation.OSDescription; + } + /// + /// 获取当前进程架构 + /// + /// + public static string ProcessArchitecture() + { + return RuntimeInformation.ProcessArchitecture.ToString(); + } #endif - public static string SystemBit() - { - return Environment.Is64BitOperatingSystem ? "x64" : "x86"; - } + /// + /// 获取系统位数 + /// + /// + public static string SystemBit() + { + return Environment.Is64BitOperatingSystem ? "x64" : "x86"; + } - public static string OSVersion() - { - return $"{Environment.OSVersion.Platform}:{Environment.Version}"; - } + /// + /// 获取系统版本 + /// + /// + public static string OSVersion() + { + return $"{Environment.OSVersion.Platform}:{Environment.Version}"; + } - public static string HostName() - { - return Environment.MachineName; - } + /// + /// 获取机器名称 + /// + /// + public static string HostName() + { + return Environment.MachineName; + } - public static TimeSpan RunningTime() - { + /// + /// 获取运行时间 + /// + /// + public static TimeSpan RunningTime() + { #if NET40_OR_GREATER - var tick = Environment.TickCount; + var tick = Environment.TickCount; #else - var tick = Environment.TickCount64; + var tick = Environment.TickCount64; #endif - return new TimeSpan(tick); - } - } + return new TimeSpan(tick); + } } diff --git a/src/Toolkit/Mapper/ExpressionCore/CreateExpression.ClassMap.cs b/src/Toolkit/Mapper/ExpressionCore/CreateExpression.ClassMap.cs index 9b05f14..ff91ac5 100644 --- a/src/Toolkit/Mapper/ExpressionCore/CreateExpression.ClassMap.cs +++ b/src/Toolkit/Mapper/ExpressionCore/CreateExpression.ClassMap.cs @@ -7,84 +7,84 @@ using System.Text; using System.Threading.Tasks; -namespace MT.KitTools.Mapper.ExpressionCore +namespace MT.KitTools.Mapper.ExpressionCore; + +#pragma warning disable +internal partial class CreateExpression { - internal partial class CreateExpression + internal static void ClassMap(MapInfo p, List body) { - internal static void ClassMap(MapInfo p, List body) + Type targetType = p.TargetType; + var rules = p.MapRule.Maps; + if (p.TargetExpression == null) { - Type targetType = p.TargetType; - var rules = p.MapRule.Maps; - if (p.TargetExpression == null) - { - p.TargetExpression = Expression.Variable(targetType, "tar"); - body.Add(Expression.Assign(p.TargetExpression, Expression.New(targetType))); - p.Variables.Add(p.TargetExpression as ParameterExpression); - } - - foreach (var rule in rules) - { - Expression valueExp = GetValueExpression(p.SourceExpression, rule); - MethodCallExpression setPropExp = Expression.Call(p.TargetExpression, rule.MapTo.SetMethod, valueExp); - body.Add(setPropExp); - } - - if (p.MapRule.MapPostAction != null) - { - var dyInvoke = typeof(Delegate).GetMethod("DynamicInvoke", new[] { typeof(object[]) })!; - var actionExp = Expression.Constant(p.MapRule.MapPostAction, typeof(Delegate)); - - MethodCallExpression postExp = Expression.Call(actionExp, dyInvoke, Expression.NewArrayInit(typeof(object), p.SourceExpression, p.TargetExpression)); - body.Add(postExp); - } - - if (p.ActionType == ActionType.NewObj) - body.Add(Expression.Convert(p.TargetExpression, p.TargetType)); - - //var targetProps = targetType.GetProperties(); - //var fromProps = fromType.GetProperties(); - //foreach (var tar in targetProps) - //{ - // if (!tar.CanWrite) continue; - // var from = fromProps.FirstOrDefault(f => f.Name.ToLower() == tar.Name.ToLower()); - // if (from == null) continue; - // //MemberExpression tarProp = Expression.Property(targetExp, tar); - // MemberExpression fromProp = Expression.Property(p.SourceExpression, from); - // var converted = DataTypeConvert.GetConversionExpression(fromProp, tar.PropertyType, from.PropertyType); - // MethodCallExpression setPropExp = Expression.Call(p.TargetExpression, tar.SetMethod, converted); - // body.Add(setPropExp); - //} - //var source = p.SourceExpression as ParameterExpression; - //List bindings = new List(); - //initBindings(ref bindings, source, p.Rules); - //MemberInitExpression init = Expression.MemberInit(Expression.New(p.TargetElementType), bindings); - //body.Add(init); + p.TargetExpression = Expression.Variable(targetType, "tar"); + body.Add(Expression.Assign(p.TargetExpression, Expression.New(targetType))); + p.Variables.Add(p.TargetExpression as ParameterExpression); } - internal static MemberInitExpression ClassMap(List rules, Type sourceType, Type targetType, object source) + foreach (var rule in rules) { - ParameterExpression parameterExpression = Expression.Variable(sourceType, "source"); - Expression.Assign(parameterExpression, Expression.Constant(source, sourceType)); - List bindings = new List(); - initBindings(ref bindings, parameterExpression, rules); - return Expression.MemberInit(Expression.New(targetType), bindings); + Expression valueExp = GetValueExpression(p.SourceExpression, rule); + MethodCallExpression setPropExp = Expression.Call(p.TargetExpression, rule.MapTo.SetMethod, valueExp); + body.Add(setPropExp); } - private static void initBindings(ref List memberBindings, ParameterExpression parameterExpression, IList rules) + if (p.MapRule.MapPostAction != null) { - foreach (var rule in rules) - { - Expression valueExp = GetValueExpression(parameterExpression, rule); - MemberAssignment bind = Expression.Bind(rule.MapTo, valueExp); - memberBindings.Add(bind); - } + var dyInvoke = typeof(Delegate).GetMethod("DynamicInvoke", new[] { typeof(object[]) })!; + var actionExp = Expression.Constant(p.MapRule.MapPostAction, typeof(Delegate)); + + MethodCallExpression postExp = Expression.Call(actionExp, dyInvoke, Expression.NewArrayInit(typeof(object), p.SourceExpression, p.TargetExpression)); + body.Add(postExp); } - private static Expression GetValueExpression(Expression parameter, MappingInfo rule) + + if (p.ActionType == ActionType.NewObj) + body.Add(Expression.Convert(p.TargetExpression, p.TargetType)); + + //var targetProps = targetType.GetProperties(); + //var fromProps = fromType.GetProperties(); + //foreach (var tar in targetProps) + //{ + // if (!tar.CanWrite) continue; + // var from = fromProps.FirstOrDefault(f => f.Name.ToLower() == tar.Name.ToLower()); + // if (from == null) continue; + // //MemberExpression tarProp = Expression.Property(targetExp, tar); + // MemberExpression fromProp = Expression.Property(p.SourceExpression, from); + // var converted = DataTypeConvert.GetConversionExpression(fromProp, tar.PropertyType, from.PropertyType); + // MethodCallExpression setPropExp = Expression.Call(p.TargetExpression, tar.SetMethod, converted); + // body.Add(setPropExp); + //} + //var source = p.SourceExpression as ParameterExpression; + //List bindings = new List(); + //initBindings(ref bindings, source, p.Rules); + //MemberInitExpression init = Expression.MemberInit(Expression.New(p.TargetElementType), bindings); + //body.Add(init); + } + + internal static MemberInitExpression ClassMap(List rules, Type sourceType, Type targetType, object source) + { + ParameterExpression parameterExpression = Expression.Variable(sourceType, "source"); + Expression.Assign(parameterExpression, Expression.Constant(source, sourceType)); + List bindings = new List(); + initBindings(ref bindings, parameterExpression, rules); + return Expression.MemberInit(Expression.New(targetType), bindings); + } + + private static void initBindings(ref List memberBindings, ParameterExpression parameterExpression, IList rules) + { + foreach (var rule in rules) { - var prop = rule.MapFrom; - var bind = Expression.Property(parameter, prop); - Expression convertedBind = DataTypeConvert.GetConversionExpression(bind, rule.MapFrom.PropertyType, rule.MapTo.PropertyType); - return convertedBind; + Expression valueExp = GetValueExpression(parameterExpression, rule); + MemberAssignment bind = Expression.Bind(rule.MapTo, valueExp); + memberBindings.Add(bind); } } + private static Expression GetValueExpression(Expression parameter, MappingInfo rule) + { + var prop = rule.MapFrom; + var bind = Expression.Property(parameter, prop); + Expression convertedBind = DataTypeConvert.GetConversionExpression(bind, rule.MapFrom.PropertyType, rule.MapTo.PropertyType); + return convertedBind; + } } diff --git a/src/Toolkit/Mapper/ExpressionCore/CreateExpression.CollectionMap.cs b/src/Toolkit/Mapper/ExpressionCore/CreateExpression.CollectionMap.cs index af43ba8..6abd374 100644 --- a/src/Toolkit/Mapper/ExpressionCore/CreateExpression.CollectionMap.cs +++ b/src/Toolkit/Mapper/ExpressionCore/CreateExpression.CollectionMap.cs @@ -5,139 +5,139 @@ using System.Collections; using System.Diagnostics; -namespace MT.KitTools.Mapper.ExpressionCore +namespace MT.KitTools.Mapper.ExpressionCore; + +#pragma warning disable +internal partial class CreateExpression { - internal partial class CreateExpression + internal static void CollectionMap(MapInfo p, List body) { - internal static void CollectionMap(MapInfo p, List body) - { - var moveNext = typeof(IEnumerator).GetMethod("MoveNext"); - var getEnumerator = p.SourceType.GetMethod("GetEnumerator"); + var moveNext = typeof(IEnumerator).GetMethod("MoveNext"); + var getEnumerator = p.SourceType.GetMethod("GetEnumerator"); - Type? enumeratorType; - if (p.SourceType.IsGenericType) - { - var innerType = p.SourceType.GetNestedType("Enumerator"); - if (innerType != null) - { - enumeratorType = innerType.MakeGenericType(p.SourceElementType); - } - else - { - enumeratorType = typeof(IEnumerator<>).MakeGenericType(p.SourceElementType); - } - } - else if (p.SourceType.IsArray) + Type? enumeratorType; + if (p.SourceType.IsGenericType) + { + var innerType = p.SourceType.GetNestedType("Enumerator"); + if (innerType != null) { - enumeratorType = typeof(IEnumerator); + enumeratorType = innerType.MakeGenericType(p.SourceElementType); } else { - throw new Exception("Unkonw Enumerator"); + enumeratorType = typeof(IEnumerator<>).MakeGenericType(p.SourceElementType); } + } + else if (p.SourceType.IsArray) + { + enumeratorType = typeof(IEnumerator); + } + else + { + throw new Exception("Unkonw Enumerator"); + } - /* - * var enumerator = source.GetEnumerator(); - * var ret = new T() - * while(true) { - * if (enumerator.MoveNext()) { - * var t = enumerator.Current; - * var n = MapperLink<,>.Map(t); - * ret.Add(n); - * // ret.Add(MapperLink<,>.Map(enumerator.Current)); - * } - * else - * { - * goto endLabel - * } - * } - * endLabel: - */ - LabelTarget endLabel = Expression.Label("end"); - var linkMap = typeof(MapperExtensions.MapperLink<,>).MakeGenericType(p.SourceElementType, p.TargetElementType).GetMethod("Create"); - var listType = typeof(List<>).MakeGenericType(p.TargetElementType); - var templist = Expression.Variable(listType); - body.Add(Expression.Assign(templist, Expression.New(listType))); - p.Variables.Add(templist); - var addMethod = listType.GetMethod("Add"); - - var enumeratorExpression = Expression.Variable(enumeratorType, "enumerator"); - p.Variables.Add(enumeratorExpression); - body.Add(Expression.Assign(enumeratorExpression, Expression.Call(p.SourceExpression, getEnumerator!))); - var loop = Expression.Loop(Expression.Block(Expression.IfThenElse(Expression.Call(enumeratorExpression, moveNext!) - , Expression.Block(Expression.Call(templist, addMethod!, Expression.Call(linkMap!, ValueExpression(enumeratorExpression, p.SourceElementType)) - )) - , Expression.Break(endLabel) - )), endLabel); - ; - body.Add(loop); - - if (p.TargetExpression == null) - { - p.TargetExpression = Expression.Variable(p.TargetType, "tar"); - p.Variables.Add(p.TargetExpression as ParameterExpression); - } + /* + * var enumerator = source.GetEnumerator(); + * var ret = new T() + * while(true) { + * if (enumerator.MoveNext()) { + * var t = enumerator.Current; + * var n = MapperLink<,>.Map(t); + * ret.Add(n); + * // ret.Add(MapperLink<,>.Map(enumerator.Current)); + * } + * else + * { + * goto endLabel + * } + * } + * endLabel: + */ + LabelTarget endLabel = Expression.Label("end"); + var linkMap = typeof(MapperExtensions.MapperLink<,>).MakeGenericType(p.SourceElementType, p.TargetElementType).GetMethod("Create"); + var listType = typeof(List<>).MakeGenericType(p.TargetElementType); + var templist = Expression.Variable(listType); + body.Add(Expression.Assign(templist, Expression.New(listType))); + p.Variables.Add(templist); + var addMethod = listType.GetMethod("Add"); - if (p.ActionType == ActionType.NewObj) - { - if (p.TargetType.IsArray) - { - var toArray = listType.GetMethod("ToArray")!; - body.Add(Expression.Assign(p.TargetExpression, Expression.Call(templist, toArray))); - } - else - { - body.Add(Expression.Assign(p.TargetExpression, templist)); - body.Add(Expression.Convert(p.TargetExpression, p.TargetType)); - } - } + var enumeratorExpression = Expression.Variable(enumeratorType, "enumerator"); + p.Variables.Add(enumeratorExpression); + body.Add(Expression.Assign(enumeratorExpression, Expression.Call(p.SourceExpression, getEnumerator!))); + var loop = Expression.Loop(Expression.Block(Expression.IfThenElse(Expression.Call(enumeratorExpression, moveNext!) + , Expression.Block(Expression.Call(templist, addMethod!, Expression.Call(linkMap!, ValueExpression(enumeratorExpression, p.SourceElementType)) + )) + , Expression.Break(endLabel) + )), endLabel); + ; + body.Add(loop); + if (p.TargetExpression == null) + { + p.TargetExpression = Expression.Variable(p.TargetType, "tar"); + p.Variables.Add(p.TargetExpression as ParameterExpression); + } - Expression ValueExpression(Expression enumerator, Type targetType) + if (p.ActionType == ActionType.NewObj) + { + if (p.TargetType.IsArray) { - var current = Expression.Property(enumerator, nameof(IEnumerator.Current)); - return Expression.Convert(current, targetType); + var toArray = listType.GetMethod("ToArray")!; + body.Add(Expression.Assign(p.TargetExpression, Expression.Call(templist, toArray))); + } + else + { + body.Add(Expression.Assign(p.TargetExpression, templist)); + body.Add(Expression.Convert(p.TargetExpression, p.TargetType)); } - } - //private static void CreateArray(MapInfo p, List body) - //{ - // if (p.TargetExpression == null) - // { - // p.TargetExpression = Expression.Variable(p.TargetType, "tar"); - // body.Add(Expression.Assign(p.TargetExpression, Expression.NewArrayInit(p.SourceElementType))); - // p.Variables.Add(p.TargetExpression as ParameterExpression); - // } - // /* - // * var length = source.Length; - // * var ret = new T[length]; - // * while(true) - // * { - // * if ( - // * } - // */ - // var linkMap = typeof(MapperExtensions.MapperLink<,>).MakeGenericType(p.SourceElementType, p.TargetElementType).GetMethod("Create"); - - // var index = Expression.Variable(typeof(int)); - // p.Variables.Add(index); - // var length = Expression.Property(p.SourceExpression, nameof(Array.Length)); - // var breakLabel = Expression.Label(); - // Expression.Loop(Expression.Block( - // Expression.IfThenElse( - // Expression.LessThan(index, length), - // Expression.Block(Expression.arr - // ,Expression.PostIncrementAssign(index)), - // Expression.Break(breakLabel) - // ) - // ), breakLabel); - //} - - private static void CreateList(MapInfo p, List body) - { + Expression ValueExpression(Expression enumerator, Type targetType) + { + var current = Expression.Property(enumerator, nameof(IEnumerator.Current)); + return Expression.Convert(current, targetType); } + + } + + //private static void CreateArray(MapInfo p, List body) + //{ + // if (p.TargetExpression == null) + // { + // p.TargetExpression = Expression.Variable(p.TargetType, "tar"); + // body.Add(Expression.Assign(p.TargetExpression, Expression.NewArrayInit(p.SourceElementType))); + // p.Variables.Add(p.TargetExpression as ParameterExpression); + // } + // /* + // * var length = source.Length; + // * var ret = new T[length]; + // * while(true) + // * { + // * if ( + // * } + // */ + // var linkMap = typeof(MapperExtensions.MapperLink<,>).MakeGenericType(p.SourceElementType, p.TargetElementType).GetMethod("Create"); + + // var index = Expression.Variable(typeof(int)); + // p.Variables.Add(index); + // var length = Expression.Property(p.SourceExpression, nameof(Array.Length)); + // var breakLabel = Expression.Label(); + // Expression.Loop(Expression.Block( + // Expression.IfThenElse( + // Expression.LessThan(index, length), + // Expression.Block(Expression.arr + // ,Expression.PostIncrementAssign(index)), + // Expression.Break(breakLabel) + // ) + // ), breakLabel); + //} + + private static void CreateList(MapInfo p, List body) + { + } } diff --git a/src/Toolkit/Mapper/ExpressionCore/CreateExpression.FromDictionary.cs b/src/Toolkit/Mapper/ExpressionCore/CreateExpression.FromDictionary.cs index 1e72774..ea1eb4e 100644 --- a/src/Toolkit/Mapper/ExpressionCore/CreateExpression.FromDictionary.cs +++ b/src/Toolkit/Mapper/ExpressionCore/CreateExpression.FromDictionary.cs @@ -7,52 +7,51 @@ using System.Text; using System.Threading.Tasks; -namespace MT.KitTools.Mapper.ExpressionCore +namespace MT.KitTools.Mapper.ExpressionCore; +#pragma warning disable +internal partial class CreateExpression { - internal partial class CreateExpression + internal static void MapFromDictionary(MapInfo p, List body) { - internal static void MapFromDictionary(MapInfo p, List body) + var genericArgs = p.SourceType.GetGenericArguments(); + var keyType = genericArgs[0]; + var valueType = genericArgs[1]; + if (keyType != typeof(string)) { - var genericArgs = p.SourceType.GetGenericArguments(); - var keyType = genericArgs[0]; - var valueType = genericArgs[1]; - if (keyType != typeof(string)) - { - throw new ArgumentException("key type must be string"); - } - if (p.TargetExpression == null) - { - p.TargetExpression = Expression.Variable(p.TargetType, "tar"); - body.Add(Expression.Assign(p.TargetExpression, Expression.New(p.TargetType))); - p.Variables.Add(p.TargetExpression as ParameterExpression); - } - // 索引器 => dic[key] - var getItem = p.SourceType.GetMethod("get_Item")!; - var contain = p.SourceType.GetMethod("ContainsKey")!; - var props = p.TargetType.GetProperties(); - foreach (var prop in props) - { - if (!prop.CanWrite) continue; - var name = prop.Name; - /* - * if (!source.ContainsKey(name) - * { - * tar.XXX = ConvertType(dic[key]); - * } - */ - var assign = Expression.IfThen( - Expression.Call(p.SourceExpression, contain, Expression.Constant(name)) - , Expression.Call(p.TargetExpression, prop.SetMethod!, ConvertType(Expression.Call(p.SourceExpression, getItem, Expression.Constant(name)), prop.PropertyType) - )); - body.Add(assign); - } - if (p.ActionType == ActionType.NewObj) - body.Add(Expression.Convert(p.TargetExpression, p.TargetType)); + throw new ArgumentException("key type must be string"); } - - private static Expression ConvertType(Expression valueExpression, Type targetType) + if (p.TargetExpression == null) + { + p.TargetExpression = Expression.Variable(p.TargetType, "tar"); + body.Add(Expression.Assign(p.TargetExpression, Expression.New(p.TargetType))); + p.Variables.Add(p.TargetExpression as ParameterExpression); + } + // 索引器 => dic[key] + var getItem = p.SourceType.GetMethod("get_Item")!; + var contain = p.SourceType.GetMethod("ContainsKey")!; + var props = p.TargetType.GetProperties(); + foreach (var prop in props) { - return DataTypeConvert.GetConversionExpression(valueExpression, typeof(object), targetType); + if (!prop.CanWrite) continue; + var name = prop.Name; + /* + * if (!source.ContainsKey(name) + * { + * tar.XXX = ConvertType(dic[key]); + * } + */ + var assign = Expression.IfThen( + Expression.Call(p.SourceExpression, contain, Expression.Constant(name)) + , Expression.Call(p.TargetExpression, prop.SetMethod!, ConvertType(Expression.Call(p.SourceExpression, getItem, Expression.Constant(name)), prop.PropertyType) + )); + body.Add(assign); } + if (p.ActionType == ActionType.NewObj) + body.Add(Expression.Convert(p.TargetExpression, p.TargetType)); + } + + private static Expression ConvertType(Expression valueExpression, Type targetType) + { + return DataTypeConvert.GetConversionExpression(valueExpression, typeof(object), targetType); } } diff --git a/src/Toolkit/Mapper/ExpressionCore/CreateExpression.ToDictionary.cs b/src/Toolkit/Mapper/ExpressionCore/CreateExpression.ToDictionary.cs index e0d0037..7ed1872 100644 --- a/src/Toolkit/Mapper/ExpressionCore/CreateExpression.ToDictionary.cs +++ b/src/Toolkit/Mapper/ExpressionCore/CreateExpression.ToDictionary.cs @@ -7,48 +7,48 @@ using System.Text; using System.Threading.Tasks; -namespace MT.KitTools.Mapper.ExpressionCore +namespace MT.KitTools.Mapper.ExpressionCore; + +#pragma warning disable +internal partial class CreateExpression { - internal partial class CreateExpression + internal static void MapToDictionary(MapInfo p, List body) { - internal static void MapToDictionary(MapInfo p, List body) + var genericArgs = p.TargetType.GetGenericArguments(); + var keyType = genericArgs[0]; + var valueType = genericArgs[1]; + if (keyType != typeof(string)) { - var genericArgs = p.TargetType.GetGenericArguments(); - var keyType = genericArgs[0]; - var valueType = genericArgs[1]; - if (keyType != typeof(string)) - { - throw new ArgumentException("key type must be string"); - } - var dicType = typeof(Dictionary<,>).MakeGenericType(genericArgs); - MethodInfo addMethod = dicType.GetMethod("Add", genericArgs)!; - var props = p.SourceType.GetProperties(); + throw new ArgumentException("key type must be string"); + } + var dicType = typeof(Dictionary<,>).MakeGenericType(genericArgs); + MethodInfo addMethod = dicType.GetMethod("Add", genericArgs)!; + var props = p.SourceType.GetProperties(); - // var dic = new Dictionary(); - //ParameterExpression dicExpression = Expression.Variable(dicType, "dic"); - //body.Add(dicExpression); - //body.Add(Expression.Assign(dicExpression, Expression.New(dicType))); - // dic.Add(); - if (p.TargetExpression == null) - { - p.TargetExpression = Expression.Variable(dicType, "dic"); - body.Add(Expression.Assign(p.TargetExpression, Expression.New(dicType))); - p.Variables.Add(p.TargetExpression as ParameterExpression); - } - foreach (PropertyInfo property in props) + // var dic = new Dictionary(); + //ParameterExpression dicExpression = Expression.Variable(dicType, "dic"); + //body.Add(dicExpression); + //body.Add(Expression.Assign(dicExpression, Expression.New(dicType))); + // dic.Add(); + if (p.TargetExpression == null) + { + p.TargetExpression = Expression.Variable(dicType, "dic"); + body.Add(Expression.Assign(p.TargetExpression, Expression.New(dicType))); + p.Variables.Add(p.TargetExpression as ParameterExpression); + } + foreach (PropertyInfo property in props) + { + if (!property.CanRead) continue; + if (valueType == typeof(object) || valueType == property.PropertyType) { - if (!property.CanRead) continue; - if (valueType == typeof(object) || valueType == property.PropertyType) - { - var key = Expression.Constant(property.Name, keyType); - var value = Expression.Property(p.SourceExpression, property); - MethodCallExpression callAdd = Expression.Call(p.TargetExpression, addMethod, key, Expression.Convert(value, valueType)); - body.Add(callAdd); - } + var key = Expression.Constant(property.Name, keyType); + var value = Expression.Property(p.SourceExpression, property); + MethodCallExpression callAdd = Expression.Call(p.TargetExpression, addMethod, key, Expression.Convert(value, valueType)); + body.Add(callAdd); } - // Func 需要 return dic; - if (p.ActionType == ActionType.NewObj) - body.Add(Expression.Convert(p.TargetExpression, p.TargetType)); } + // Func 需要 return dic; + if (p.ActionType == ActionType.NewObj) + body.Add(Expression.Convert(p.TargetExpression, p.TargetType)); } } diff --git a/src/Toolkit/Mapper/ExpressionCore/CreateExpression.cs b/src/Toolkit/Mapper/ExpressionCore/CreateExpression.cs index a2fe817..b918b19 100644 --- a/src/Toolkit/Mapper/ExpressionCore/CreateExpression.cs +++ b/src/Toolkit/Mapper/ExpressionCore/CreateExpression.cs @@ -4,58 +4,58 @@ using System.Collections.Generic; using System.Linq.Expressions; -namespace MT.KitTools.Mapper.ExpressionCore +namespace MT.KitTools.Mapper.ExpressionCore; + +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +internal partial class CreateExpression { - internal partial class CreateExpression + internal static LambdaExpression ExpressionBuilder(MapInfo p) { - internal static LambdaExpression ExpressionBuilder(MapInfo p) + var body = new List(); + if (p.ActionType == ActionType.NewObj) { - var body = new List(); - if (p.ActionType == ActionType.NewObj) + var pExp = Expression.Parameter(typeof(object), "p"); + p.SourceExpression = Expression.Variable(p.SourceType, "source"); + if (p.SourceType.IsValueType) { - var pExp = Expression.Parameter(typeof(object), "p"); - p.SourceExpression = Expression.Variable(p.SourceType, "source"); - if (p.SourceType.IsValueType) - { - body.Add(Expression.Assign(p.SourceExpression, Expression.Unbox(pExp, p.SourceType))); - } - else - { - body.Add(Expression.Assign(p.SourceExpression, Expression.TypeAs(pExp, p.SourceType))); - } - p.Parameters.Add(pExp); - p.Variables.Add(p.SourceExpression as ParameterExpression); + body.Add(Expression.Assign(p.SourceExpression, Expression.Unbox(pExp, p.SourceType))); } - else if (p.ActionType == ActionType.Ref) + else { - p.TargetExpression = Expression.Parameter(p.TargetType, "tar"); - p.SourceExpression = Expression.Parameter(p.SourceType, "from"); - p.Parameters.Add(p.SourceExpression as ParameterExpression); - p.Parameters.Add(p.TargetExpression as ParameterExpression); + body.Add(Expression.Assign(p.SourceExpression, Expression.TypeAs(pExp, p.SourceType))); } - else - throw new ArgumentException($"Unknow ActionType {p.ActionType}"); - - var action = GetHandler(p); - action.Invoke(p, body); - BlockExpression block = Expression.Block(p.Variables, body); - LambdaExpression lambda = Expression.Lambda(block, p.Parameters); - return lambda; + p.Parameters.Add(pExp); + p.Variables.Add(p.SourceExpression as ParameterExpression); } - internal static Action> GetHandler(MapInfo p) + else if (p.ActionType == ActionType.Ref) { - var sourceType = p.SourceType; - var targetType = p.TargetType; - if (sourceType.IsDictionary()) - return MapFromDictionary; - else if (targetType.IsDictionary()) - return MapToDictionary; - else if ((sourceType.IsICollectionType() || sourceType.IsIEnumerableType()) && (targetType.IsICollectionType()|| targetType.IsIEnumerableType())) - return CollectionMap; - else if (sourceType.IsClass && targetType.IsClass) - return ClassMap; - throw new NotImplementedException($"not implement map between {sourceType.Name} and {targetType.Name}"); + p.TargetExpression = Expression.Parameter(p.TargetType, "tar"); + p.SourceExpression = Expression.Parameter(p.SourceType, "from"); + p.Parameters.Add(p.SourceExpression as ParameterExpression); + p.Parameters.Add(p.TargetExpression as ParameterExpression); } - } + else + throw new ArgumentException($"Unknow ActionType {p.ActionType}"); + var action = GetHandler(p); + action.Invoke(p, body); + BlockExpression block = Expression.Block(p.Variables, body); + LambdaExpression lambda = Expression.Lambda(block, p.Parameters); + return lambda; + } + internal static Action> GetHandler(MapInfo p) + { + var sourceType = p.SourceType; + var targetType = p.TargetType; + if (sourceType.IsDictionary()) + return MapFromDictionary; + else if (targetType.IsDictionary()) + return MapToDictionary; + else if ((sourceType.IsICollectionType() || sourceType.IsIEnumerableType()) && (targetType.IsICollectionType() || targetType.IsIEnumerableType())) + return CollectionMap; + else if (sourceType.IsClass && targetType.IsClass) + return ClassMap; + throw new NotImplementedException($"not implement map between {sourceType.Name} and {targetType.Name}"); + } } diff --git a/src/Toolkit/Mapper/Extensions/MapperServiceExtension.cs b/src/Toolkit/Mapper/Extensions/MapperServiceExtension.cs index 10c1829..c12b513 100644 --- a/src/Toolkit/Mapper/Extensions/MapperServiceExtension.cs +++ b/src/Toolkit/Mapper/Extensions/MapperServiceExtension.cs @@ -6,25 +6,25 @@ using System.Text; using System.Threading.Tasks; -namespace MT.Toolkit.Mapper.Extensions +namespace MT.Toolkit.Mapper.Extensions; + +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +public static class MapperServiceExtension { - [Obsolete("使用AutoGenMapperGenerator代替")] - public static class MapperServiceExtension + public static IServiceCollection AddSimpleMapper(this IServiceCollection services) { - public static IServiceCollection AddSimpleMapper(this IServiceCollection services) - { - var mapper = new SimpleMapper(); - services.AddSingleton(mapper); - return services; - } + var mapper = new SimpleMapper(); + services.AddSingleton(mapper); + return services; + } - public static IServiceCollection AddSimpleMapper(this IServiceCollection services, Action config) - { - var mapper = new SimpleMapper(); - config.Invoke(mapper.Configuration); - services.AddSingleton(mapper); - return services; - } - } + public static IServiceCollection AddSimpleMapper(this IServiceCollection services, Action config) + { + var mapper = new SimpleMapper(); + config.Invoke(mapper.Configuration); + services.AddSingleton(mapper); + return services; + } } #endif \ No newline at end of file diff --git a/src/Toolkit/Mapper/MapInfo.cs b/src/Toolkit/Mapper/MapInfo.cs index 1fd16ad..0906d48 100644 --- a/src/Toolkit/Mapper/MapInfo.cs +++ b/src/Toolkit/Mapper/MapInfo.cs @@ -4,24 +4,25 @@ using System.Linq.Expressions; #nullable disable -namespace MT.Toolkit.Mapper +namespace MT.Toolkit.Mapper; +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +public enum ActionType { - public enum ActionType - { - NewObj, - Ref - } - internal class MapInfo - { - public Type SourceType { get; set; } - public Type TargetType { get; set; } - public Type SourceElementType { get; set; } - public Type TargetElementType { get; set; } - public Expression SourceExpression { get; set; } - public Expression TargetExpression { get; set; } - public IMapperRule MapRule { get; set; } - public ActionType ActionType { get; set; } - public List Parameters { get; set; } = new List(); - public List Variables { get; set; } = new List(); - } + NewObj, + Ref +} +[Obsolete("使用AutoGenMapperGenerator代替")] +internal class MapInfo +{ + public Type SourceType { get; set; } + public Type TargetType { get; set; } + public Type SourceElementType { get; set; } + public Type TargetElementType { get; set; } + public Expression SourceExpression { get; set; } + public Expression TargetExpression { get; set; } + public IMapperRule MapRule { get; set; } + public ActionType ActionType { get; set; } + public List Parameters { get; set; } = new List(); + public List Variables { get; set; } = new List(); } \ No newline at end of file diff --git a/src/Toolkit/Mapper/MapRuleProvider.cs b/src/Toolkit/Mapper/MapRuleProvider.cs index 11a2c84..04a131f 100644 --- a/src/Toolkit/Mapper/MapRuleProvider.cs +++ b/src/Toolkit/Mapper/MapRuleProvider.cs @@ -4,43 +4,44 @@ using System.Linq.Expressions; using System.Text; -namespace MT.Toolkit.Mapper +namespace MT.Toolkit.Mapper; + +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +public static class MapRuleProvider { - public static class MapRuleProvider - { - private static IList cache = new List(); + private static IList cache = new List(); - public static void Cache(IMapperRule profiles, Type sourceType, Type targetType) - { - bool contain = cache.Any(p => p.Equal(sourceType, targetType)); - if (!contain) - { - cache.Add(profiles); - //throw new ArgumentException($"mapping between {sourceType.Name} and {targetType.Name} had been created"); - } - } + public static void Cache(IMapperRule profiles, Type sourceType, Type targetType) + { + bool contain = cache.Any(p => p.Equal(sourceType, targetType)); + if (!contain) + { + cache.Add(profiles); + //throw new ArgumentException($"mapping between {sourceType.Name} and {targetType.Name} had been created"); + } + } - public static IMapperRule GetMapRule() - { - return GetMapRule(typeof(TSource), typeof(TTarget)); - } + public static IMapperRule GetMapRule() + { + return GetMapRule(typeof(TSource), typeof(TTarget)); + } - public static IMapperRule GetMapRule(Type sourceType, Type targetType) - { - var profile = cache.FirstOrDefault(p => p.Equal(sourceType, targetType)); - if (profile == null) - { - profile = CreateMapRule(sourceType, targetType); - cache.Add(profile); - } - return profile; - } + public static IMapperRule GetMapRule(Type sourceType, Type targetType) + { + var profile = cache.FirstOrDefault(p => p.Equal(sourceType, targetType)); + if (profile == null) + { + profile = CreateMapRule(sourceType, targetType); + cache.Add(profile); + } + return profile; + } - public static IMapperRule CreateMapRule(Type sourceType, Type targetType) - { - Type genericType = typeof(MapperRule<,>).MakeGenericType(sourceType, targetType); - var exp = Expression.New(genericType); - return (IMapperRule)Expression.Lambda(exp).Compile().DynamicInvoke()!; - } - } + public static IMapperRule CreateMapRule(Type sourceType, Type targetType) + { + Type genericType = typeof(MapperRule<,>).MakeGenericType(sourceType, targetType); + var exp = Expression.New(genericType); + return (IMapperRule)Expression.Lambda(exp).Compile().DynamicInvoke()!; + } } diff --git a/src/Toolkit/Mapper/Mapper.cs b/src/Toolkit/Mapper/Mapper.cs index 6f36f8b..c49c297 100644 --- a/src/Toolkit/Mapper/Mapper.cs +++ b/src/Toolkit/Mapper/Mapper.cs @@ -1,97 +1,97 @@ using System; using System.Collections.Generic; -namespace MT.Toolkit.Mapper +namespace MT.Toolkit.Mapper; + +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +public interface ISimpleMapper { - [Obsolete("使用AutoGenMapperGenerator代替")] - public interface ISimpleMapper + TTarget Map(TFrom source); + IEnumerable Map(IEnumerable sources); + MapperConfig Configuration { get; } +} + +[Obsolete("使用AutoGenMapperGenerator代替")] +public class SimpleMapper : ISimpleMapper +{ + private readonly Mapper _map; + public SimpleMapper() { - TTarget Map(TFrom source); - IEnumerable Map(IEnumerable sources); - MapperConfig Configuration { get; } + _map = Mapper.Default; } - - [Obsolete("使用AutoGenMapperGenerator代替")] - public class SimpleMapper : ISimpleMapper - { - private readonly Mapper _map; - public SimpleMapper() - { - _map = Mapper.Default; - } - public MapperConfig Configuration => _map.Config; + public MapperConfig Configuration => _map.Config; - public TTarget Map(TFrom source) - { - return _map.NewMap(source); - } + public TTarget Map(TFrom source) + { + return _map.NewMap(source); + } - public IEnumerable Map(IEnumerable sources) + public IEnumerable Map(IEnumerable sources) + { + foreach (var item in sources) { - foreach (var item in sources) - { - yield return Map(item); - } + yield return Map(item); } } +} - [Obsolete("使用AutoGenMapperGenerator代替")] - public class Mapper +[Obsolete("使用AutoGenMapperGenerator代替")] +public class Mapper +{ + public static TValue Map(TValue source) { - public static TValue Map(TValue source) - { - return Default.NewMap(source); - } - public static TTarget Map(TFrom source) - { - return Default.NewMap(source); - } - public static IEnumerable Map(IEnumerable sources) + return Default.NewMap(source); + } + public static TTarget Map(TFrom source) + { + return Default.NewMap(source); + } + public static IEnumerable Map(IEnumerable sources) + { + foreach (var item in sources) { - foreach (var item in sources) - { - yield return Map(item); - } + yield return Map(item); } - /// - /// 创建 MappingProfile,并检查是否重复 - /// - /// - /// - /// - //internal static MapperRule CreateMappingRule() - //{ - // var rule = new MapperRule(); - // MapRuleProvider.Cache(rule, typeof(TFrom), typeof(TTarget)); - // return rule; - //} - public static Mapper Default => new Mapper(); + } + /// + /// 创建 MappingProfile,并检查是否重复 + /// + /// + /// + /// + //internal static MapperRule CreateMappingRule() + //{ + // var rule = new MapperRule(); + // MapRuleProvider.Cache(rule, typeof(TFrom), typeof(TTarget)); + // return rule; + //} + public static Mapper Default => new Mapper(); - internal MapperConfig Config => MapperConfigProvider.GetMapperConfig(); - internal Mapper() { } + internal MapperConfig Config => MapperConfigProvider.GetMapperConfig(); + internal Mapper() { } - public Mapper Configuration(Action config) - { - config?.Invoke(Config); - return this; - } + public Mapper Configuration(Action config) + { + config?.Invoke(Config); + return this; + } - /// - /// 配置映射 - /// - /// - /// - /// - public Mapper CreateMap(Action> context = null) - { - var map = (MapperRule)MapRuleProvider.GetMapRule(); - context?.Invoke(map); - return this; - } - public TTarget NewMap(TFrom source) - { - return MapperExtensions.MapperLink.Create(source); - } + /// + /// 配置映射 + /// + /// + /// + /// + public Mapper CreateMap(Action> context = null) + { + var map = (MapperRule)MapRuleProvider.GetMapRule(); + context?.Invoke(map); + return this; + } + public TTarget NewMap(TFrom source) + { + return MapperExtensions.MapperLink.Create(source); } } diff --git a/src/Toolkit/Mapper/MapperConfig.cs b/src/Toolkit/Mapper/MapperConfig.cs index 015b65a..e5f7622 100644 --- a/src/Toolkit/Mapper/MapperConfig.cs +++ b/src/Toolkit/Mapper/MapperConfig.cs @@ -6,57 +6,59 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; -namespace MT.Toolkit.Mapper +namespace MT.Toolkit.Mapper; + +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +public class MapperConfig { - public class MapperConfig - { - private string prefix; - private bool matchPrefix = false; - public StringComparison StringComparison { get; set; } = StringComparison.Ordinal; - public ClassMemberHandleMode ClassMemberHandleMode { get; set; } = ClassMemberHandleMode.Ref; - public Func PropertyMappingRule { get; set; } + private string prefix; + private bool matchPrefix = false; + public StringComparison StringComparison { get; set; } = StringComparison.Ordinal; + public ClassMemberHandleMode ClassMemberHandleMode { get; set; } = ClassMemberHandleMode.Ref; + public Func PropertyMappingRule { get; set; } - public void EnablePrefixMatch(string prefix) - { - this.prefix = prefix; - matchPrefix = true; - } + public void EnablePrefixMatch(string prefix) + { + this.prefix = prefix; + matchPrefix = true; + } - public MapperConfig CreateMap(Action> context = null) - { - var map = (MapperRule)MapRuleProvider.GetMapRule(); - context?.Invoke(map); - return this; - } + public MapperConfig CreateMap(Action> context = null) + { + var map = (MapperRule)MapRuleProvider.GetMapRule(); + context?.Invoke(map); + return this; + } - internal bool Match(PropertyInfo source, PropertyInfo target) - { - if (source == null || target == null) - { - return true; - } - bool matched = false; - string sourceName = source.Name; - string targetName = target.Name; - matched = string.Equals(sourceName, targetName, StringComparison); - if (matchPrefix) - { - var temp = string.Equals(prefix + sourceName, targetName, StringComparison) || - string.Equals(sourceName, prefix + targetName, StringComparison); - matched = matched || temp; - } - if (PropertyMappingRule != null) - { - return matched && PropertyMappingRule.Invoke(source, target); - } - return matched; - } - } + internal bool Match(PropertyInfo source, PropertyInfo target) + { + if (source == null || target == null) + { + return true; + } + bool matched = false; + string sourceName = source.Name; + string targetName = target.Name; + matched = string.Equals(sourceName, targetName, StringComparison); + if (matchPrefix) + { + var temp = string.Equals(prefix + sourceName, targetName, StringComparison) || + string.Equals(sourceName, prefix + targetName, StringComparison); + matched = matched || temp; + } + if (PropertyMappingRule != null) + { + return matched && PropertyMappingRule.Invoke(source, target); + } + return matched; + } +} - public enum ClassMemberHandleMode - { - None, - NewObj, - Ref - } +[Obsolete("使用AutoGenMapperGenerator代替")] +public enum ClassMemberHandleMode +{ + None, + NewObj, + Ref } diff --git a/src/Toolkit/Mapper/MapperConfigProvider.cs b/src/Toolkit/Mapper/MapperConfigProvider.cs index 387ccc1..7fc820a 100644 --- a/src/Toolkit/Mapper/MapperConfigProvider.cs +++ b/src/Toolkit/Mapper/MapperConfigProvider.cs @@ -4,16 +4,17 @@ using System.Text; using System.Threading.Tasks; -namespace MT.Toolkit.Mapper +namespace MT.Toolkit.Mapper; + +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +public class MapperConfigProvider { - public class MapperConfigProvider - { - private static MapperConfig Config = new MapperConfig(); - public static MapperConfig GetMapperConfig() - { - return Config; - } + private static MapperConfig Config = new MapperConfig(); + public static MapperConfig GetMapperConfig() + { + return Config; + } - } } diff --git a/src/Toolkit/Mapper/MapperExtensions.cs b/src/Toolkit/Mapper/MapperExtensions.cs index 76bc4bb..0f1b6e5 100644 --- a/src/Toolkit/Mapper/MapperExtensions.cs +++ b/src/Toolkit/Mapper/MapperExtensions.cs @@ -1,59 +1,59 @@ using System; -namespace MT.Toolkit.Mapper +namespace MT.Toolkit.Mapper; + +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +public static partial class MapperExtensions { - [Obsolete("使用AutoGenMapperGenerator代替")] - public static partial class MapperExtensions + /// + /// 为现有的对象赋值 + /// + /// + /// + /// + /// + public static void Map(this TTarget self, TFrom source) + { + InnerMapper.Invoke(source, self); + } + + + /// + /// 泛型缓存 + /// + /// + /// + internal static class MapperLink { - /// - /// 为现有的对象赋值 - /// - /// - /// - /// - /// - public static void Map(this TTarget self, TFrom source) + private static readonly Func converter; + private static Profiles profile = null; + static MapperLink() { - InnerMapper.Invoke(source, self); + profile = new MappingProfile(); + converter = (Func)profile.CreateDelegate(ActionType.NewObj); } + public static TTarget Create(TFrom source) + { + return converter.Invoke(source); + } + } + + internal static class InnerMapper + { + private static readonly Action action; + private static Profiles profile = null; - /// - /// 泛型缓存 - /// - /// - /// - internal static class MapperLink + static InnerMapper() { - private static readonly Func converter; - private static Profiles profile = null; - static MapperLink() - { - profile = new MappingProfile(); - converter = (Func)profile.CreateDelegate(ActionType.NewObj); - } - - public static TTarget Create(TFrom source) - { - return converter.Invoke(source); - } + profile = new MappingProfile(); + action = (Action)profile.CreateDelegate(ActionType.Ref); } - internal static class InnerMapper + public static void Invoke(TFrom source, TTarget target) { - private static readonly Action action; - private static Profiles profile = null; - - static InnerMapper() - { - profile = new MappingProfile(); - action = (Action)profile.CreateDelegate(ActionType.Ref); - } - - public static void Invoke(TFrom source, TTarget target) - { - action?.Invoke(source, target); - } + action?.Invoke(source, target); } } } diff --git a/src/Toolkit/Mapper/MappingProfile.cs b/src/Toolkit/Mapper/MappingProfile.cs index 7060693..eafa468 100644 --- a/src/Toolkit/Mapper/MappingProfile.cs +++ b/src/Toolkit/Mapper/MappingProfile.cs @@ -7,52 +7,55 @@ using MT.KitTools.Mapper.ExpressionCore; using MT.Toolkit.TypeExtensions; -namespace MT.Toolkit.Mapper +namespace MT.Toolkit.Mapper; + +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +public enum MapperType +{ + ClassObjectToClassObject, + ClassObjectToDictionary, + DictionaryToClassObject +} + +[Obsolete("使用AutoGenMapperGenerator代替")] +public class MappingProfile : Profiles { - public enum MapperType - { - ClassObjectToClassObject, - ClassObjectToDictionary, - DictionaryToClassObject - } - public class MappingProfile : Profiles - { - internal MappingProfile() - { - types = new[] { typeof(TFrom), typeof(TTarget) }; - } - - public bool Exit(Type source, Type target) - { - var b1 = isTypeEquals(); - var b2 = isElementTypeEquals(); - return b1 || b2; - - bool isTypeEquals() - { - return ReferenceEquals(source, SourceType) && ReferenceEquals(target, TargetType); - } - - bool isElementTypeEquals() - { - var requestSourceType = source.IsICollectionType() ? source.GetCollectionElementType() : source; - var requestTargetType = target.IsICollectionType() ? target.GetCollectionElementType() : target; - return ReferenceEquals(requestSourceType, SourceElementType) && ReferenceEquals(requestTargetType, TargetElementType); - } - } - - - public override Delegate CreateDelegate(ActionType actionType) - { - MapInfo p = new MapInfo(); - p.SourceType = SourceType; - p.TargetType = TargetType; - p.SourceElementType = SourceElementType; - p.TargetElementType = TargetElementType; - p.ActionType = actionType; - p.MapRule = MapRuleProvider.GetMapRule(p.SourceElementType, p.TargetElementType); - var lambda = CreateExpression.ExpressionBuilder(p); - return lambda.Compile(); - } - } + internal MappingProfile() + { + types = new[] { typeof(TFrom), typeof(TTarget) }; + } + + public bool Exit(Type source, Type target) + { + var b1 = isTypeEquals(); + var b2 = isElementTypeEquals(); + return b1 || b2; + + bool isTypeEquals() + { + return ReferenceEquals(source, SourceType) && ReferenceEquals(target, TargetType); + } + + bool isElementTypeEquals() + { + var requestSourceType = source.IsICollectionType() ? source.GetCollectionElementType() : source; + var requestTargetType = target.IsICollectionType() ? target.GetCollectionElementType() : target; + return ReferenceEquals(requestSourceType, SourceElementType) && ReferenceEquals(requestTargetType, TargetElementType); + } + } + + + public override Delegate CreateDelegate(ActionType actionType) + { + MapInfo p = new MapInfo(); + p.SourceType = SourceType; + p.TargetType = TargetType; + p.SourceElementType = SourceElementType; + p.TargetElementType = TargetElementType; + p.ActionType = actionType; + p.MapRule = MapRuleProvider.GetMapRule(p.SourceElementType, p.TargetElementType); + var lambda = CreateExpression.ExpressionBuilder(p); + return lambda.Compile(); + } } \ No newline at end of file diff --git a/src/Toolkit/Mapper/MappingRule.cs b/src/Toolkit/Mapper/MappingRule.cs index dada858..a0f8f0d 100644 --- a/src/Toolkit/Mapper/MappingRule.cs +++ b/src/Toolkit/Mapper/MappingRule.cs @@ -5,77 +5,81 @@ using System.Reflection; using System.Text; -namespace MT.Toolkit.Mapper +namespace MT.Toolkit.Mapper; +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +public static class TypeExtensions { - public static class TypeExtensions - { - public static bool Equal(this IMapperRule self, Type source, Type target) - { - return ReferenceEquals(self.SourceType, source) && ReferenceEquals(self.TargetType, target); - } - } - public interface IMapperRule - { - List Maps { get; set; } - Delegate MapPostAction { get; set; } - Type SourceType { get; set; } - Type TargetType { get; set; } - } + public static bool Equal(this IMapperRule self, Type source, Type target) + { + return ReferenceEquals(self.SourceType, source) && ReferenceEquals(self.TargetType, target); + } +} - public class MapperRule : IMapperRule - { - public Type SourceType { get; set; } - public Type TargetType { get; set; } - public Delegate? MapPostAction { get; set; } - public List Maps { get; set; } - private MapperConfig Config => MapperConfigProvider.GetMapperConfig(); - public MapperRule() - { - SourceType = typeof(TSource); - TargetType = typeof(TTarget); - Maps = new List(); - AutoMap(); - } +[Obsolete("使用AutoGenMapperGenerator代替")] +public interface IMapperRule +{ + List Maps { get; set; } + Delegate MapPostAction { get; set; } + Type SourceType { get; set; } + Type TargetType { get; set; } +} - public void Mapping(Action action) - { - MapPostAction = action; - } +[Obsolete("使用AutoGenMapperGenerator代替")] +public class MapperRule : IMapperRule +{ + public Type SourceType { get; set; } + public Type TargetType { get; set; } + public Delegate? MapPostAction { get; set; } + public List Maps { get; set; } + private MapperConfig Config => MapperConfigProvider.GetMapperConfig(); + public MapperRule() + { + SourceType = typeof(TSource); + TargetType = typeof(TTarget); + Maps = new List(); + AutoMap(); + } - public void AutoMap() - { - if (SourceType.IsDictionary() || TargetType.IsDictionary()) - { - return; - } - Maps.Clear(); - var targetProps = TargetType.GetProperties(); - var sourceProps = SourceType.GetProperties(); - foreach (var tar in targetProps) - { - var source = sourceProps.FirstOrDefault(p => Config.Match(p, tar)); - if (tar.CanWrite && !Maps.Any(r => r.MapTo == tar) && source != null) - AddMap(tar, source); - } - } - private void AddMap(PropertyInfo to, PropertyInfo from, string? formatter = null) - { - MappingInfo rule = new MappingInfo(to, from, formatter); - Maps.Add(rule); - } - } + public void Mapping(Action action) + { + MapPostAction = action; + } - public class MappingInfo - { - public MappingInfo(PropertyInfo mapTo, PropertyInfo mapFrom, string? formatter) - { - MapTo = mapTo; - MapFrom = mapFrom; - Formatter = formatter; - } - public int Index { get; set; } - public string? Formatter { get; set; } - public PropertyInfo MapTo { get; set; } - public PropertyInfo MapFrom { get; set; } - } + public void AutoMap() + { + if (SourceType.IsDictionary() || TargetType.IsDictionary()) + { + return; + } + Maps.Clear(); + var targetProps = TargetType.GetProperties(); + var sourceProps = SourceType.GetProperties(); + foreach (var tar in targetProps) + { + var source = sourceProps.FirstOrDefault(p => Config.Match(p, tar)); + if (tar.CanWrite && !Maps.Any(r => r.MapTo == tar) && source != null) + AddMap(tar, source); + } + } + private void AddMap(PropertyInfo to, PropertyInfo from, string? formatter = null) + { + MappingInfo rule = new MappingInfo(to, from, formatter); + Maps.Add(rule); + } +} + +[Obsolete("使用AutoGenMapperGenerator代替")] +public class MappingInfo +{ + public MappingInfo(PropertyInfo mapTo, PropertyInfo mapFrom, string? formatter) + { + MapTo = mapTo; + MapFrom = mapFrom; + Formatter = formatter; + } + public int Index { get; set; } + public string? Formatter { get; set; } + public PropertyInfo MapTo { get; set; } + public PropertyInfo MapFrom { get; set; } } diff --git a/src/Toolkit/Mapper/Profiles.cs b/src/Toolkit/Mapper/Profiles.cs index eb66ba5..32d3cdc 100644 --- a/src/Toolkit/Mapper/Profiles.cs +++ b/src/Toolkit/Mapper/Profiles.cs @@ -7,22 +7,24 @@ using System.Reflection; using System.Text; -namespace MT.Toolkit.Mapper +namespace MT.Toolkit.Mapper; + +#pragma warning disable +[Obsolete("使用AutoGenMapperGenerator代替")] +public abstract class Profiles { - public abstract class Profiles - { - protected Type[] types; - protected Type SourceType => types[0]; - protected Type TargetType => types[1]; - protected Type SourceElementType => SourceType.IsICollectionType() || SourceType.IsIEnumerableType() ? SourceType.GetCollectionElementType() : SourceType; - protected Type TargetElementType => TargetType.IsICollectionType() || SourceType.IsIEnumerableType() ? TargetType.GetCollectionElementType() : TargetType; - public abstract Delegate CreateDelegate(ActionType actionType); - } + protected Type[] types; + protected Type SourceType => types[0]; + protected Type TargetType => types[1]; + protected Type SourceElementType => SourceType.IsICollectionType() || SourceType.IsIEnumerableType() ? SourceType.GetCollectionElementType() : SourceType; + protected Type TargetElementType => TargetType.IsICollectionType() || SourceType.IsIEnumerableType() ? TargetType.GetCollectionElementType() : TargetType; + public abstract Delegate CreateDelegate(ActionType actionType); +} - public enum Direction - { - Forward, - Backward - } +[Obsolete("使用AutoGenMapperGenerator代替")] +public enum Direction +{ + Forward, + Backward } diff --git a/src/Toolkit/ReflectionExtension/MemberInfoExtension.cs b/src/Toolkit/ReflectionExtension/MemberInfoExtension.cs index 43d62ac..f1f5e3f 100644 --- a/src/Toolkit/ReflectionExtension/MemberInfoExtension.cs +++ b/src/Toolkit/ReflectionExtension/MemberInfoExtension.cs @@ -1,157 +1,246 @@ using System; -using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; -using System.Text; using System.Linq; +using System.Diagnostics.CodeAnalysis; -namespace MT.Toolkit.ReflectionExtension +namespace MT.Toolkit.ReflectionExtension; + +/// +/// +/// +public static class MemberInfoExtension { /// - /// + /// 调用方法 /// - public static class MemberInfoExtension + /// + /// + /// +#if NET8_0_OR_GREATER + [UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "Expression.Lambda")] + [UnconditionalSuppressMessage("AOT", "IL2075:Calling members from object.GetType() may break functionality when AOT compiling.", Justification = "GetMethod")] +#endif + public static void Invoke(this object obj, string methodName, params object[] args) { + var type = obj.GetType(); + var method = type.GetMethod(methodName, [.. args.Select(o => o.GetType())]); + if (method == null) return; + var parameter = Expression.Parameter(type, "e"); + var callExpression = Expression.Call(parameter, method, args.Select(Expression.Constant)); + Expression.Lambda(callExpression, parameter).Compile().DynamicInvoke(obj); + } - /// - /// 调用方法 - /// - /// - /// - /// - public static void Invoke(this object obj, string methodName, params object[] args) - { - var type = obj.GetType(); - var method = type.GetMethod(methodName, args.Select(o => o.GetType()).ToArray()); - if (method == null) return; - var parameter = Expression.Parameter(type, "e"); - var callExpression = Expression.Call(parameter, method, args.Select(Expression.Constant)); - Expression.Lambda(callExpression, parameter).Compile().DynamicInvoke(obj); - } + /// + /// 调用方法(泛型) + /// + /// + /// + /// +#if NET8_0_OR_GREATER + [UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "Expression.Lambda")] +#endif + public static void Invoke< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] +#endif + T>(this T obj, string methodName, params object[] args) + { + var type = typeof(T); + var method = type.GetMethod(methodName, [.. args.Select(o => o.GetType())]); + if (method == null) return; + var parameter = Expression.Parameter(type, "e"); + var callExpression = Expression.Call(parameter, method, args.Select(Expression.Constant)); + Expression.Lambda(callExpression, parameter).Compile().DynamicInvoke(obj); + } - /// - /// 调用方法(有返回值) - /// - /// - /// - /// - /// - /// - public static T Invoke(this object obj, string methodName, params object[] args) - { - var type = obj.GetType(); - var method = type.GetMethod(methodName, args.Select(o => o.GetType()).ToArray()); - if (method == null) return default!; - var parameter = Expression.Parameter(type, "e"); - var callExpression = Expression.Call(parameter, method, args.Select(Expression.Constant)); - return (T)Expression.Lambda(callExpression, parameter).Compile().DynamicInvoke(obj)!; - } + /// + /// 调用方法(有返回值) + /// + /// + /// + /// + /// + /// +#if NET8_0_OR_GREATER + [UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "Expression.Lambda")] + [UnconditionalSuppressMessage("AOT", "IL2075:Calling members from object.GetType() may break functionality when AOT compiling.", Justification = "GetMethod")] +#endif + public static T Invoke(this object obj, string methodName, params object[] args) + { + var type = obj.GetType(); + var method = type.GetMethod(methodName, [.. args.Select(o => o.GetType())]); + if (method == null) return default!; + var parameter = Expression.Parameter(type, "e"); + var callExpression = Expression.Call(parameter, method, args.Select(Expression.Constant)); + return (T)Expression.Lambda(callExpression, parameter).Compile().DynamicInvoke(obj)!; + } - /// - /// 根据类型调用静态方法 - /// - /// - /// - /// - public static void Invoke(this Type type, string methodName, params object[] args) - { - var method = type.GetMethod(methodName, args.Select(o => o.GetType()).ToArray()); - MethodCallExpression methodCallExpression = Expression.Call(method, args.Select(Expression.Constant)); - Expression.Lambda(methodCallExpression).Compile().DynamicInvoke(); - } + /// + /// 调用方法(有返回值) + /// + /// + /// + /// + /// + /// + /// +#if NET8_0_OR_GREATER + [UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "Expression.Lambda")] +#endif + public static T Invoke< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] +#endif + TObj, T>(this TObj obj, string methodName, params object[] args) + { + var type = typeof(TObj); + var method = type.GetMethod(methodName, [.. args.Select(o => o.GetType())]); + if (method == null) return default!; + var parameter = Expression.Parameter(type, "e"); + var callExpression = Expression.Call(parameter, method, args.Select(Expression.Constant)); + return (T)Expression.Lambda(callExpression, parameter).Compile().DynamicInvoke(obj)!; + } - /// - /// 根据类型调用静态方法(有返回值) - /// - /// - /// - /// - public static T Invoke(this Type type, string methodName, params object[] args) - { - var method = type.GetMethod(methodName, args.Select(o => o.GetType()).ToArray()); - if (method == null) - return default!; - MethodCallExpression methodCallExpression = Expression.Call(method, args.Select(Expression.Constant)); - return (T)Expression.Lambda(methodCallExpression).Compile().DynamicInvoke()!; - } - public static object Invoke(this Type type, Type genericType, string methodName, params object[] args) - { - var method = type.GetMethod(methodName, args.Select(o => o.GetType()).ToArray()); - if (method == null) return default!; - method = method.MakeGenericMethod(genericType); - MethodCallExpression methodCallExpression = Expression.Call(method, args.Select(Expression.Constant)); - return Expression.Lambda(methodCallExpression).Compile().DynamicInvoke()!; - } + /// + /// 根据类型调用静态方法 + /// + /// + /// + /// +#if NET8_0_OR_GREATER + [UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "Expression.Lambda")] +#endif + public static void Invoke( +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] +#endif + this Type type, string methodName, params object[] args) + { + var method = type.GetMethod(methodName, [.. args.Select(o => o.GetType())]); + if (method is null) return; + MethodCallExpression methodCallExpression = Expression.Call(method, args.Select(Expression.Constant)); + Expression.Lambda(methodCallExpression).Compile().DynamicInvoke(); + } - /// - /// 创建获取属性值的委托 - /// - /// - /// - /// - public static Func GetPropertyAccessor(this PropertyInfo prop) - { - /* - * p => (object)p.XXX; - */ - if (prop.DeclaringType == null || !prop.CanRead) return NullGetter; - var p = Expression.Parameter(typeof(object), "p"); - var instance = Expression.Convert(p, prop.DeclaringType); - var propExp = Expression.Property(instance, prop); - Expression body = propExp; - if (typeof(TProp) == typeof(object)) - { - body = Expression.Convert(propExp, typeof(object)); - } - var lambda = Expression.Lambda>(body, p); - return lambda.Compile(); - } - /// - /// 创建获取属性值的委托 - /// - /// - /// - /// - /// - public static Func GetPropertyAccessor(this object entity, string propName) - { - var prop = entity.GetType().GetProperty(propName); - if (prop == null) return NullGetter; - return prop.GetPropertyAccessor(); - } + /// + /// 根据类型调用静态方法(有返回值) + /// + /// + /// + /// +#if NET8_0_OR_GREATER + [UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "Expression.Lambda")] +#endif + public static T Invoke( +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] +#endif + this Type type, string methodName, params object[] args) + { + var method = type.GetMethod(methodName, args.Select(o => o.GetType()).ToArray()); + if (method == null) + return default!; + MethodCallExpression methodCallExpression = Expression.Call(method, args.Select(Expression.Constant)); + return (T)Expression.Lambda(methodCallExpression).Compile().DynamicInvoke()!; + } - static TProp NullGetter(object entity) => default!; - /// - /// 创建属性赋值的委托 - /// - /// - /// - public static Action GetPropertySetter(this PropertyInfo prop) - { - /* - * (p, v) => ((T)p).XXX = (TProp)v; - */ - if (prop.DeclaringType == null || !prop.CanWrite) return NullSetter; - var p = Expression.Parameter(typeof(object), "p"); - var val = Expression.Parameter(typeof(object), "v"); - var cp = Expression.Convert(p, prop.DeclaringType); - var setMethod = prop.SetMethod!; - var set = Expression.Call(cp, setMethod, Expression.Convert(val, prop.PropertyType)); - var lambda = Expression.Lambda>(set, p, val); - return lambda.Compile(); - } - /// - /// 创建属性赋值的委托 - /// - /// - /// - /// - public static Action GetPropertySetter(this object entity, string propName) + /// + /// 反射调用指定方法(有返回值) + /// + /// + /// + /// + /// + /// +#if NET8_0_OR_GREATER + [UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "Expression.Lambda")] + [UnconditionalSuppressMessage("AOT", "IL2060:Calling MakeGenericMethod may break functionality when AOT compiling.", Justification = "")] +#endif + public static object Invoke( +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] +#endif + this Type type, Type genericType, string methodName, params object[] args) + { + var method = type.GetMethod(methodName, [.. args.Select(o => o.GetType())]); + if (method == null) return default!; + method = method.MakeGenericMethod(genericType); + MethodCallExpression methodCallExpression = Expression.Call(method, args.Select(Expression.Constant)); + return Expression.Lambda(methodCallExpression).Compile().DynamicInvoke()!; + } + + /// + /// 创建获取属性值的委托 + /// + /// + /// + /// + public static Func GetPropertyAccessor(this PropertyInfo prop) + { + /* + * p => (object)p.XXX; + */ + if (prop.DeclaringType == null || !prop.CanRead) return NullGetter; + var p = Expression.Parameter(typeof(object), "p"); + var instance = Expression.Convert(p, prop.DeclaringType); + var propExp = Expression.Property(instance, prop); + Expression body = propExp; + if (typeof(TProp) == typeof(object)) { - var prop = entity.GetType().GetProperty(propName); - if (prop == null) return NullSetter; - return prop.GetPropertySetter(); + body = Expression.Convert(propExp, typeof(object)); } - static void NullSetter(object _1, object _2) { } + var lambda = Expression.Lambda>(body, p); + return lambda.Compile(); + } + /// + /// 创建获取属性值的委托 + /// + /// + public static Func GetPropertyAccessor< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] +#endif + TEntity, TProp>(this TEntity _, string propName) + { + var prop = typeof(TEntity).GetProperty(propName); + if (prop == null) return NullGetter; + return prop.GetPropertyAccessor(); + } + + static TProp NullGetter(object entity) => default!; + /// + /// 创建属性赋值的委托 + /// + /// + /// + public static Action GetPropertySetter(this PropertyInfo prop) + { + /* + * (p, v) => ((T)p).XXX = (TProp)v; + */ + if (prop.DeclaringType == null || !prop.CanWrite) return NullSetter; + var p = Expression.Parameter(typeof(object), "p"); + var val = Expression.Parameter(typeof(object), "v"); + var cp = Expression.Convert(p, prop.DeclaringType); + var setMethod = prop.SetMethod!; + var set = Expression.Call(cp, setMethod, Expression.Convert(val, prop.PropertyType)); + var lambda = Expression.Lambda>(set, p, val); + return lambda.Compile(); + } + /// + /// 创建属性赋值的委托 + /// + /// + public static Action GetPropertySetter< +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] +#endif + T>(this T _, string propName) + { + var prop = typeof(T).GetProperty(propName); + if (prop == null) return NullSetter; + return prop.GetPropertySetter(); } + static void NullSetter(object _1, object _2) { } } diff --git a/src/Toolkit/StringExtension/StringExtensions.cs b/src/Toolkit/StringExtension/StringExtensions.cs index 464ab87..fbd2d42 100644 --- a/src/Toolkit/StringExtension/StringExtensions.cs +++ b/src/Toolkit/StringExtension/StringExtensions.cs @@ -1,17 +1,29 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Numerics; using System.Text; using System.Text.RegularExpressions; namespace MT.Toolkit.StringExtension; +/// +/// 扩展方法 +/// public static partial class StringExtensions { + /// + /// Returns the original string if the specified condition evaluates to true; otherwise, returns an empty string. + /// + /// The original string if the condition is true; otherwise, an empty string. public static string If(this string? self, Func condition) { return self.If(condition.Invoke()); } - + /// + /// Returns the original string if the specified condition evaluates to true; otherwise, returns an empty string. + /// + /// The original string if the condition is true; otherwise, an empty string. public static string If(this string? self, bool condition) { if (string.IsNullOrEmpty(self)) @@ -20,39 +32,59 @@ public static string If(this string? self, bool condition) } if (condition) { - return self; + return self!; } return string.Empty; } + /// + /// 字符串是否合法,如果rule不为null,则根据rule判断字符串是否合法,否则只要字符串不为null或空白就合法 + /// + /// public static bool IsEnable(this string? self, Func? rule = null) { - if (string.IsNullOrEmpty(self)) + if (string.IsNullOrWhiteSpace(self)) { return false; } - if (rule is null) - { - return true; - } - var b = rule?.Invoke(self); - return b.HasValue && b.Value; + return rule?.Invoke(self!) ?? true; } - public static bool IsNumeric(this string? self, out T value) + /// + /// 是否是数字字符串,如果是数字字符串则将其转换为对应的数字类型,否则返回默认值,优先使用.NET 8.0的INumber接口进行转换,如果不支持则使用正则表达式判断字符串是否合法并进行转换 + /// + /// + /// + /// + /// + public static bool IsNumeric(this string? self, +#if NET6_0_OR_GREATER + [NotNullWhen(true)] +#endif + out T? value) +#if NET8_0_OR_GREATER + where T : INumber +#endif { - var match = self.IsNumeric(); +#if NET8_0_OR_GREATER + return T.TryParse(self, null, out value); +#else + var match = self.IsNumeric(); if (match) { value = (T)StringTo(self!, typeof(T)); } else value = default!; - return match; - +#endif } + /// + /// 检测是否是数字 + /// + /// + /// public static bool IsNumeric(this string? self) { if (string.IsNullOrEmpty(self)) @@ -71,6 +103,11 @@ public static bool IsNumeric(this string? self) private static partial Regex NumberMatchRegex(); #endif + /// + /// 追加字符串到StringBuilder,如果字符串不合法则不追加 + /// + /// + /// public static void AppendTo(this string str, StringBuilder builder) { if (str.IsEnable()) diff --git a/src/Toolkit/Toolkit.csproj b/src/Toolkit/Toolkit.csproj index b35f195..0cb5fbd 100644 --- a/src/Toolkit/Toolkit.csproj +++ b/src/Toolkit/Toolkit.csproj @@ -7,7 +7,7 @@ MarvelTiter https://github.com/MarvelTiter/MT.Toolkit MT.Toolkit - 2.1.9.0 + 2026.06.02.1 MIT MT.Toolkit latest diff --git a/src/Toolkit/TypeConvertHelper/ObjectConvertHelper.cs b/src/Toolkit/TypeConvertHelper/ObjectConvertHelper.cs index fa246ed..afe54d9 100644 --- a/src/Toolkit/TypeConvertHelper/ObjectConvertHelper.cs +++ b/src/Toolkit/TypeConvertHelper/ObjectConvertHelper.cs @@ -4,23 +4,37 @@ using System.Text; using System.Threading.Tasks; -namespace MT.Toolkit.TypeConvertHelper +namespace MT.Toolkit.TypeConvertHelper; + +/// +/// +/// +public static class ObjectConvertHelper { - public static class ObjectConvertHelper + /// + /// 类型转换 + /// + /// + /// + /// + public static T? ChangeType(this object self) { - public static T? ChangeType(this object self) - { - return (T?)ChangeType(self, typeof(T)); - } + return (T?)ChangeType(self, typeof(T)); + } - public static object? ChangeType(this object self, Type type) + /// + /// 类型转换 + /// + /// + /// + /// + public static object? ChangeType(this object self, Type type) + { + if (self is null) { - if (self is null) - { - return default; - } - type = Nullable.GetUnderlyingType(type) ?? type; - return Convert.ChangeType(self, type); + return default; } + type = Nullable.GetUnderlyingType(type) ?? type; + return Convert.ChangeType(self, type); } } diff --git a/src/Toolkit/TypeConvertHelper/StringConvertHelper.cs b/src/Toolkit/TypeConvertHelper/StringConvertHelper.cs index 72787ec..86cb6a0 100644 --- a/src/Toolkit/TypeConvertHelper/StringConvertHelper.cs +++ b/src/Toolkit/TypeConvertHelper/StringConvertHelper.cs @@ -2,39 +2,55 @@ using System.Collections.Concurrent; using System.Reflection; -namespace MT.Toolkit.TypeConvertHelper +namespace MT.Toolkit.TypeConvertHelper; + +#pragma warning disable +/// +/// +/// +public static class StringConvertHelper { - public static class StringConvertHelper + static readonly ConcurrentDictionary tryParseCache = []; + /// + /// + /// + /// + /// + /// + [Obsolete("use StringExtensions.IsNumeric{T}(string?, out T?) instead")] + public static T? Parse(this string input) + { + return (T?)Parse(input, typeof(T)); + } + /// + /// + /// + /// + /// + /// + [Obsolete("use StringExtensions.IsNumeric{T}(string?, out T?) instead")] + public static object? Parse(this string input, Type type) { - static readonly ConcurrentDictionary tryParseCache = []; - public static T? Parse(this string input) + if (type == typeof(string)) { - return (T?)Parse(input, typeof(T)); + return input.Trim(); } - - public static object? Parse(this string input, Type type) + type = Nullable.GetUnderlyingType(type) ?? type; + var method = tryParseCache.GetOrAdd(type, t => + { + return t.GetMethod("TryParse", [typeof(string), t.MakeByRefType()]); + }); + if (method == null) { - if (type == typeof(string)) - { - return input.Trim(); - } - type = Nullable.GetUnderlyingType(type) ?? type; - var method = tryParseCache.GetOrAdd(type, t => - { - return t.GetMethod("TryParse", [typeof(string), t.MakeByRefType()]); - }); - if (method == null) - { - return default; - } - object?[] parameters = [input, default]; - var r = method.Invoke(null, parameters); - if (r is bool b && b == true) - { - return parameters[1]; - } return default; } - + object?[] parameters = [input, default]; + var r = method.Invoke(null, parameters); + if (r is bool b && b == true) + { + return parameters[1]; + } + return default; } + } diff --git a/src/Toolkit/TypeExtensions/TypeExtensions.cs b/src/Toolkit/TypeExtensions/TypeExtensions.cs index 6473c92..005ffce 100644 --- a/src/Toolkit/TypeExtensions/TypeExtensions.cs +++ b/src/Toolkit/TypeExtensions/TypeExtensions.cs @@ -1,54 +1,104 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace MT.Toolkit.TypeExtensions +namespace MT.Toolkit.TypeExtensions; + +/// +/// 类型扩展方法 +/// +public static class TypeExtensions { - public static class TypeExtensions + private static readonly string System_Collections_Generic_Dictionary = "System.Collections.Generic.Dictionary"; + private static readonly string System_Collections_Generic_IDictionary = "System.Collections.Generic.IDictionary"; + private static readonly string System_Collections_Generic_ICollection_1 = "System.Collections.Generic.ICollection`1"; + private static readonly string System_Collections_Generic_IEnumerable_1 = "System.Collections.Generic.IEnumerable`1"; + + /// + /// 是否是字典类型 + /// + /// + /// + public static bool IsDictionary( +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] +#endif + this Type type) + { + var interfaces = type.GetInterfaces(); + return type.FullName?.StartsWith(System_Collections_Generic_Dictionary) == true || + type.FullName?.StartsWith(System_Collections_Generic_IDictionary) == true || + type.GetInterfaces().Any(tp => tp.FullName?.StartsWith(System_Collections_Generic_IDictionary) == true); + } + + /// + /// 是否是可枚举类型 + /// + /// + /// + public static bool IsIEnumerableType( +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] +#endif + this Type type) + { + return type.FullName?.StartsWith(System_Collections_Generic_IEnumerable_1) == true || + type.GetInterfaces().Any(tp => tp.FullName?.StartsWith(System_Collections_Generic_IEnumerable_1) == true); + } + + /// + /// 是否是集合类型 + /// + /// + /// + public static bool IsICollectionType( +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] +#endif + this Type type) + { + return type.FullName?.StartsWith(System_Collections_Generic_ICollection_1) == true || + type.GetInterfaces().Any(tp => tp.FullName?.StartsWith(System_Collections_Generic_ICollection_1) == true); + } + + /// + /// 是否是可空类型 + /// + /// + /// + public static bool IsNullableType(this Type type) + { + return type.FullName?.StartsWith("System.Nullable`1[") == true; + } + + /// + /// 获取集合元素类型 + /// + /// + /// + public static Type GetCollectionElementType( +#if NET8_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] +#endif + this Type type) + { + if (type.IsArray) { type.GetElementType(); } + if (type.IsGenericEnumerableType()) { return type.GetGenericArguments()[0]; } + var arrayType = Array.Find(type.GetInterfaces(), IsGenericEnumerableType); + if (arrayType == null) { return typeof(object); } + return arrayType.GetGenericArguments()[0]; + } + + /// + /// 是否是泛型枚举类型 + /// + /// + /// + private static bool IsGenericEnumerableType(this Type type) { - private static readonly string System_Collections_Generic_Dictionary = "System.Collections.Generic.Dictionary"; - private static readonly string System_Collections_Generic_IDictionary = "System.Collections.Generic.IDictionary"; - private static readonly string System_Collections_Generic_ICollection_1 = "System.Collections.Generic.ICollection`1"; - private static readonly string System_Collections_Generic_IEnumerable_1 = "System.Collections.Generic.IEnumerable`1"; - - public static bool IsDictionary(this Type type) - { - var interfaces = type.GetInterfaces(); - return type.FullName?.StartsWith(System_Collections_Generic_Dictionary) == true || - type.FullName?.StartsWith(System_Collections_Generic_IDictionary) == true || - type.GetInterfaces().Any(tp => tp.FullName?.StartsWith(System_Collections_Generic_IDictionary) == true); - } - public static bool IsIEnumerableType(this Type type) - { - return type.FullName?.StartsWith(System_Collections_Generic_IEnumerable_1) == true || - type.GetInterfaces().Any(tp => tp.FullName?.StartsWith(System_Collections_Generic_IEnumerable_1) == true); - } - - public static bool IsICollectionType(this Type type) - { - return type.FullName?.StartsWith(System_Collections_Generic_ICollection_1) == true || - type.GetInterfaces().Any(tp => tp.FullName?.StartsWith(System_Collections_Generic_ICollection_1) == true); - } - - public static bool IsNullableType(this Type type) - { - return type.FullName?.StartsWith("System.Nullable`1[") == true; - } - - public static Type GetCollectionElementType(this Type type) - { - if (type.IsArray) { type.GetElementType(); } - if (type.IsGenericEnumerableType()) { return type.GetGenericArguments()[0]; } - var arrayType = Array.Find(type.GetInterfaces(), IsGenericEnumerableType); - if (arrayType == null) { return typeof(object); } - return arrayType.GetGenericArguments()[0]; - } - - private static bool IsGenericEnumerableType(this Type type) - { - return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>); - } + return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>); } } diff --git a/src/Toolkit/XmlHelper/XmlString.cs b/src/Toolkit/XmlHelper/XmlString.cs index bb2cebd..921b789 100644 --- a/src/Toolkit/XmlHelper/XmlString.cs +++ b/src/Toolkit/XmlHelper/XmlString.cs @@ -15,7 +15,9 @@ namespace MT.Toolkit.XmlHelper public class XmlString { internal string? Value { get; private set; } - + /// + /// + /// public XmlString(string? str) { Value = str; @@ -40,6 +42,9 @@ public XmlString(string? str) internal Lazy Xml { get; } + /// + /// + /// public static implicit operator XmlString(string? str) => new(str); private static bool CheckRoot(string xml) { diff --git a/src/Toolkit/XmlHelper/XmlStringExtensions.cs b/src/Toolkit/XmlHelper/XmlStringExtensions.cs index ac361d4..83c32f1 100644 --- a/src/Toolkit/XmlHelper/XmlStringExtensions.cs +++ b/src/Toolkit/XmlHelper/XmlStringExtensions.cs @@ -1,39 +1,70 @@ - - -using System; -using System.Collections; -using System.Collections.Generic; +using System.Collections.Generic; using System.Xml; using System.Xml.Linq; -using System.Xml.XPath; -namespace MT.Toolkit.XmlHelper +namespace MT.Toolkit.XmlHelper; + +/// +/// 扩展方法 +/// +public static class XmlStringExtensions { - public static class XmlStringExtensions + /// + /// 根据XML path获取值 + /// + /// + /// + /// + /// + public static string? GetValue(this XmlString? xml, string path, XmlNamespaceManager? ns = null) { - public static string? GetValue(this XmlString? xml, string path, XmlNamespaceManager? ns = null) - { - return xml?.Xml.Value?.GetValue(path, ns); - } + return xml?.Xml.Value?.GetValue(path, ns); + } - public static T? GetValue(this XmlString? xml, string path, XmlNamespaceManager? ns = null) where T : struct - { - return xml?.Xml.Value?.GetValue(path, ns); - } + /// + /// 根据XML path获取值,并转换为指定类型 + /// + /// + /// + /// + /// + /// + public static T? GetValue(this XmlString? xml, string path, XmlNamespaceManager? ns = null) where T : struct + { + return xml?.Xml.Value?.GetValue(path, ns); + } - public static dynamic? AsDynamic(this XmlString? xml) - { - return xml?.Xml.Value?.AsDynamic(); - } + /// + /// 转成Dynamic对象 + /// + /// + /// + public static dynamic? AsDynamic(this XmlString? xml) + { + return xml?.Xml.Value?.AsDynamic(); + } - public static IEnumerable GetElementsAfterSelf(this XmlString? xml, string path, XmlNamespaceManager? ns = null) - { - return xml?.Xml.Value?.GetElementsAfterSelf(path, ns) ?? []; - } + /// + /// + /// + /// + /// + /// + /// + public static IEnumerable GetElementsAfterSelf(this XmlString? xml, string path, XmlNamespaceManager? ns = null) + { + return xml?.Xml.Value?.GetElementsAfterSelf(path, ns) ?? []; + } - public static XElement? GetElement(this XmlString? xml, string path, XmlNamespaceManager? nsManager = null) - { - return xml?.Xml.Value?.GetElement(path, nsManager); - } + /// + /// 根据XML path获取 + /// + /// + /// + /// + /// + public static XElement? GetElement(this XmlString? xml, string path, XmlNamespaceManager? nsManager = null) + { + return xml?.Xml.Value?.GetElement(path, nsManager); } }