😎代码清理及优化

This commit is contained in:
zuohuaijun 2024-12-30 02:20:39 +08:00
parent 681b8adb2f
commit be89e2f4d9
35 changed files with 225 additions and 298 deletions

View File

@ -167,7 +167,7 @@ dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
dotnet_style_namespace_match_folder = true:suggestion
dotnet_style_namespace_match_folder = true:none
dotnet_style_predefined_type_for_locals_parameters_members = true:silent
dotnet_style_predefined_type_for_member_access = true:silent
indent_size = 4

View File

@ -13,7 +13,7 @@ namespace Admin.NET.Core;
public class CommonValidationAttribute : ValidationAttribute
{
private readonly Dictionary<string, string> _conditions;
private static readonly Dictionary<string, Delegate> CompiledConditions = new();
private static readonly Dictionary<string, Delegate> CompiledConditions = [];
/// <summary>
/// </summary>
@ -76,7 +76,7 @@ public class CommonValidationAttribute : ValidationAttribute
var parameter = Expression.Parameter(typeof(object), "x");
// 构建 Lambda 表达式
var lambda = DynamicExpressionParser.ParseLambda(new[] { Expression.Parameter(modelType, "x") }, typeof(bool), expression);
var lambda = DynamicExpressionParser.ParseLambda([Expression.Parameter(modelType, "x")], typeof(bool), expression);
// 创建新的 Lambda 表达式,接受 object 参数并调用编译后的表达式
var invokeExpression = Expression.Invoke(lambda, Expression.Convert(parameter, modelType));

View File

@ -25,9 +25,11 @@ public static class CacheSetup
{
Configuration = cacheOptions.Redis.Configuration,
Prefix = cacheOptions.Redis.Prefix
});
// 自动检测集群节点
redis.AutoDetect = App.GetConfig<bool>("Cache:Redis:AutoDetect", true);
})
{
// 自动检测集群节点
AutoDetect = App.GetConfig<bool>("Cache:Redis:AutoDetect", true)
};
// 最大消息大小
if (cacheOptions.Redis.MaxMessageSize > 0)
redis.MaxMessageSize = cacheOptions.Redis.MaxMessageSize;

View File

@ -130,5 +130,5 @@ public partial class SysMenu : EntityBase
/// 菜单子项
/// </summary>
[SugarColumn(IsIgnore = true)]
public List<SysMenu> Children { get; set; } = new();
public List<SysMenu> Children { get; set; } = [];
}

View File

@ -172,29 +172,16 @@ public static partial class ObjectExtension
else
{
int length = str.Length;
switch (length)
return length switch
{
case 4:
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
case 6:
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
case 8:
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
case 10:
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
case 12:
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
case 14:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
default:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
}
4 => DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture),
6 => DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture),
8 => DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture),
10 => DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture),
12 => DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture),
14 => DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture),
_ => DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture),
};
}
}
catch
@ -224,29 +211,16 @@ public static partial class ObjectExtension
else
{
int length = str.Length;
switch (length)
return length switch
{
case 4:
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
case 6:
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
case 8:
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
case 10:
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
case 12:
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
case 14:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
default:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
}
4 => DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture),
6 => DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture),
8 => DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture),
10 => DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture),
12 => DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture),
14 => DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture),
_ => DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture),
};
}
}
catch
@ -335,7 +309,7 @@ public static partial class ObjectExtension
{
if (!email.TryValidate(ValidationTypes.EmailAddress).IsValid) return email;
var pos = email.IndexOf("@");
var pos = email.IndexOf('@');
return Mask(email[..pos], mask) + email[pos..];
}
@ -351,10 +325,10 @@ public static partial class ObjectExtension
{
if (!string.IsNullOrWhiteSpace(str))
{
MethodInfo method = typeof(T).GetMethod("Parse", new Type[] { typeof(string) });
MethodInfo method = typeof(T).GetMethod("Parse", [typeof(string)]);
if (method != null)
{
T result = (T)method.Invoke(null, new string[] { str });
T result = (T)method.Invoke(null, [str]);
return result;
}
}
@ -384,14 +358,13 @@ public static partial class ObjectExtension
if (type.Name.StartsWith("Nullable"))
_type = type.GetGenericArguments()[0];
MethodInfo method = _type.GetMethod("Parse", new Type[] { typeof(string) });
MethodInfo method = _type.GetMethod("Parse", [typeof(string)]);
if (method != null)
return method.Invoke(null, new string[] { str });
return method.Invoke(null, [str]);
}
}
catch
{
}
{ }
return null;
}

View File

@ -369,7 +369,7 @@ public static class RepositoryExtension
/// <returns></returns>
public static List<T> Where<T>(this T thisValue, Func<T, bool> whereExpression) where T : class, new()
{
return new List<T>() { thisValue };
return [thisValue];
}
/// <summary>
@ -382,7 +382,7 @@ public static class RepositoryExtension
/// <returns></returns>
public static List<T> WhereIF<T>(this T thisValue, bool isWhere, Func<T, bool> whereExpression) where T : class, new()
{
return new List<T>() { thisValue };
return [thisValue];
}
/// <summary>
@ -395,7 +395,7 @@ public static class RepositoryExtension
public static IUpdateable<T> OnlyUpdateColumn<T, R>(this IUpdateable<T> updateable) where T : EntityBase, new() where R : class, new()
{
if (updateable.UpdateBuilder.UpdateColumns == null)
updateable.UpdateBuilder.UpdateColumns = new List<string>();
updateable.UpdateBuilder.UpdateColumns = [];
foreach (PropertyInfo info in typeof(R).GetProperties())
{

View File

@ -15,9 +15,7 @@ public static class SqlSugarExtension
{
public static ISugarQueryable<T> SearchBy<T>(this ISugarQueryable<T> queryable, BaseFilter filter)
{
return queryable.SearchByKeyword(filter.Keyword)
.AdvancedSearch(filter.Search)
.AdvancedFilter(filter.Filter);
return queryable.SearchByKeyword(filter.Keyword).AdvancedSearch(filter.Search).AdvancedFilter(filter.Filter);
}
public static ISugarQueryable<T> SearchByKeyword<T>(this ISugarQueryable<T> queryable, string keyword)
@ -33,36 +31,30 @@ public static class SqlSugarExtension
Expression right = Expression.Constant(false);
if (search.Fields?.Any() is true)
if (search.Fields?.Count != 0)
{
foreach (string field in search.Fields)
{
MemberExpression propertyExpr = GetPropertyExpression(field, paramExpr);
var left = AddSearchPropertyByKeyword<T>(propertyExpr, search.Keyword);
right = Expression.Or(left, right);
}
}
else
{
var properties = typeof(T).GetProperties()
.Where(prop => Nullable.GetUnderlyingType(prop.PropertyType) == null
&& !prop.PropertyType.IsEnum
&& Type.GetTypeCode(prop.PropertyType) != TypeCode.Object);
var properties = typeof(T).GetProperties().Where(prop => Nullable.GetUnderlyingType(prop.PropertyType) == null
&& !prop.PropertyType.IsEnum
&& Type.GetTypeCode(prop.PropertyType) != TypeCode.Object);
foreach (var property in properties)
{
var propertyExpr = Expression.Property(paramExpr, property);
var left = AddSearchPropertyByKeyword<T>(propertyExpr, search.Keyword);
right = Expression.Or(left, right);
}
}
var lambda = Expression.Lambda<Func<T, bool>>(right, paramExpr);
return queryable.Where(lambda);
}
@ -95,10 +87,7 @@ public static class SqlSugarExtension
return queryable;
}
private static Expression CombineFilter(
FilterLogicEnum filterLogic,
Expression bExpresionBase,
Expression bExpresion)
private static Expression CombineFilter(FilterLogicEnum filterLogic, Expression bExpresionBase, Expression bExpresion)
{
return filterLogic switch
{
@ -116,10 +105,7 @@ public static class SqlSugarExtension
return filter;
}
private static Expression CreateFilterExpression(
FilterLogicEnum filterLogic,
IEnumerable<Filter> filters,
ParameterExpression parameter)
private static Expression CreateFilterExpression(FilterLogicEnum filterLogic, IEnumerable<Filter> filters, ParameterExpression parameter)
{
Expression filterExpression = default!;
@ -144,21 +130,14 @@ public static class SqlSugarExtension
return filterExpression;
}
private static Expression CreateFilterExpression(
string field,
FilterOperatorEnum filterOperator,
object? value,
ParameterExpression parameter)
private static Expression CreateFilterExpression(string field, FilterOperatorEnum filterOperator, object? value, ParameterExpression parameter)
{
var propertyExpresion = GetPropertyExpression(field, parameter);
var valueExpresion = GeValuetExpression(field, value, propertyExpresion.Type);
return CreateFilterExpression(propertyExpresion, valueExpresion, filterOperator);
}
private static Expression CreateFilterExpression(
MemberExpression memberExpression,
ConstantExpression constantExpression,
FilterOperatorEnum filterOperator)
private static Expression CreateFilterExpression(MemberExpression memberExpression, ConstantExpression constantExpression, FilterOperatorEnum filterOperator)
{
return filterOperator switch
{
@ -177,15 +156,12 @@ public static class SqlSugarExtension
private static string GetStringFromJsonElement(object value)
{
if (value is JsonElement) return ((JsonElement)value).GetString()!;
if (value is string) return (string)value;
if (value is JsonElement element) return element.GetString()!;
if (value is string v) return v;
return value?.ToString();
}
private static ConstantExpression GeValuetExpression(
string field,
object? value,
Type propertyType)
private static ConstantExpression GeValuetExpression(string field, object? value, Type propertyType)
{
if (value == null) return Expression.Constant(null, propertyType);
@ -234,13 +210,10 @@ public static class SqlSugarExtension
private static dynamic? ChangeType(object value, Type conversion)
{
var t = conversion;
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}
t = Nullable.GetUnderlyingType(t);
}
@ -248,9 +221,7 @@ public static class SqlSugarExtension
return Convert.ChangeType(value, t!);
}
private static MemberExpression GetPropertyExpression(
string propertyName,
ParameterExpression parameter)
private static MemberExpression GetPropertyExpression(string propertyName, ParameterExpression parameter)
{
Expression propertyExpression = parameter;
foreach (string member in propertyName.Split('.'))
@ -261,33 +232,24 @@ public static class SqlSugarExtension
return (MemberExpression)propertyExpression;
}
private static Expression AddSearchPropertyByKeyword<T>(
Expression propertyExpr,
string keyword,
FilterOperatorEnum operatorSearch = FilterOperatorEnum.Contains)
private static Expression AddSearchPropertyByKeyword<T>(Expression propertyExpr, string keyword, FilterOperatorEnum operatorSearch = FilterOperatorEnum.Contains)
{
if (propertyExpr is not MemberExpression memberExpr || memberExpr.Member is not PropertyInfo property)
{
throw new ArgumentException("propertyExpr must be a property expression.", nameof(propertyExpr));
}
ConstantExpression constant = Expression.Constant(keyword);
MethodInfo method = operatorSearch switch
{
FilterOperatorEnum.Contains => typeof(string).GetMethod(nameof(FilterOperatorEnum.Contains), new Type[] { typeof(string) }),
FilterOperatorEnum.StartsWith => typeof(string).GetMethod(nameof(FilterOperatorEnum.StartsWith), new Type[] { typeof(string) }),
FilterOperatorEnum.EndsWith => typeof(string).GetMethod(nameof(FilterOperatorEnum.EndsWith), new Type[] { typeof(string) }),
FilterOperatorEnum.Contains => typeof(string).GetMethod(nameof(FilterOperatorEnum.Contains), [typeof(string)]),
FilterOperatorEnum.StartsWith => typeof(string).GetMethod(nameof(FilterOperatorEnum.StartsWith), [typeof(string)]),
FilterOperatorEnum.EndsWith => typeof(string).GetMethod(nameof(FilterOperatorEnum.EndsWith), [typeof(string)]),
_ => throw new ArgumentException("Filter Operator is not valid."),
};
Expression selectorExpr =
property.PropertyType == typeof(string)
? propertyExpr
: Expression.Condition(
Expression.Equal(Expression.Convert(propertyExpr, typeof(object)), Expression.Constant(null, typeof(object))),
Expression.Constant(null, typeof(string)),
Expression.Call(propertyExpr, "ToString", null, null));
Expression selectorExpr = property.PropertyType == typeof(string)
? propertyExpr
: Expression.Condition(Expression.Equal(Expression.Convert(propertyExpr, typeof(object)), Expression.Constant(null, typeof(object))), Expression.Constant(null, typeof(string)), Expression.Call(propertyExpr, "ToString", null, null));
return Expression.Call(selectorExpr, method, constant);
}

View File

@ -66,7 +66,7 @@ public static class YitIdHelperExtension
var tempWorkIds = _workIds;
foreach (var key in keys)
{
var tempWorkId = key[key.LastIndexOf(":", StringComparison.Ordinal)..];
var tempWorkId = key[key.LastIndexOf(':')..];
tempWorkIds.Remove(tempWorkId);
}

View File

@ -12,14 +12,13 @@ namespace Admin.NET.Core;
public class DatabaseLoggingWriter : IDatabaseLoggingWriter, IDisposable
{
private readonly IServiceScope _serviceScope;
private readonly ISqlSugarClient _db;
private readonly SqlSugarScopeProvider _db;
private readonly SysConfigService _sysConfigService; // 参数配置服务
private readonly ILogger<DatabaseLoggingWriter> _logger; // 日志组件
public DatabaseLoggingWriter(IServiceScopeFactory scopeFactory)
{
_serviceScope = scopeFactory.CreateScope();
//_db = _serviceScope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
_sysConfigService = _serviceScope.ServiceProvider.GetRequiredService<SysConfigService>();
_logger = _serviceScope.ServiceProvider.GetRequiredService<ILogger<DatabaseLoggingWriter>>();

View File

@ -17,8 +17,8 @@ public class SysConfigSeedData : ISqlSugarEntitySeedData<SysConfig>
/// <returns></returns>
public IEnumerable<SysConfig> HasData()
{
return new[]
{
return
[
new SysConfig{ Id=1300000000101, Name="演示环境", Code=ConfigConst.SysDemoEnv, Value="False", SysFlag=YesNoEnum.Y, Remark="演示环境", OrderNo=10, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1300000000111, Name="默认密码", Code=ConfigConst.SysPassword, Value="Admin.NET++010101", SysFlag=YesNoEnum.Y, Remark="默认密码", OrderNo=20, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1300000000121, Name="密码最大错误次数", Code=ConfigConst.SysPasswordMaxErrorTimes, Value="5", SysFlag=YesNoEnum.Y, Remark="允许密码最大输入错误次数", OrderNo=30, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
@ -51,6 +51,6 @@ public class SysConfigSeedData : ISqlSugarEntitySeedData<SysConfig>
new SysConfig{ Id=1310000000351, Name="系统图标", Code=ConfigConst.SysWebLogo, Value="/upload/logo.png", SysFlag=YesNoEnum.Y, Remark="系统图标", OrderNo=350, GroupCode=ConfigConst.SysWebConfigGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1310000000361, Name="ICP备案号", Code=ConfigConst.SysWebIcp, Value="省ICP备12345678号", SysFlag=YesNoEnum.Y, Remark="ICP备案号", OrderNo=360, GroupCode=ConfigConst.SysWebConfigGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1310000000371, Name="ICP地址", Code=ConfigConst.SysWebIcpUrl, Value="https://beian.miit.gov.cn", SysFlag=YesNoEnum.Y, Remark="ICP地址", OrderNo=370, GroupCode=ConfigConst.SysWebConfigGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
};
];
}
}

View File

@ -17,8 +17,8 @@ public class SysDictDataSeedData : ISqlSugarEntitySeedData<SysDictData>
/// <returns></returns>
public IEnumerable<SysDictData> HasData()
{
return new[]
{
return
[
new SysDictData{ Id=1300000000101, DictTypeId=1300000000101, Value="输入框", Code="Input", OrderNo=100, Remark="输入框", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysDictData{ Id=1300000000102, DictTypeId=1300000000101, Value="字典选择器", Code="DictSelector", OrderNo=100, Remark="字典选择器", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysDictData{ Id=1300000000103, DictTypeId=1300000000101, Value="常量选择器", Code="ConstSelector", OrderNo=100, Remark="常量选择器", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
@ -74,6 +74,6 @@ public class SysDictDataSeedData : ISqlSugarEntitySeedData<SysDictData>
new SysDictData{ Id=1300000000703, DictTypeId=1300000000201, Value="部门", Code="301", OrderNo=102, Remark="部门", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2023-02-10 00:00:00") },
new SysDictData{ Id=1300000000704, DictTypeId=1300000000201, Value="区域", Code="401", OrderNo=103, Remark="区域", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2023-02-10 00:00:00") },
new SysDictData{ Id=1300000000705, DictTypeId=1300000000201, Value="组", Code="501", OrderNo=104, Remark="组", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2023-02-10 00:00:00") },
};
];
}
}

View File

@ -17,8 +17,8 @@ public class SysDictTypeSeedData : ISqlSugarEntitySeedData<SysDictType>
/// <returns></returns>
public IEnumerable<SysDictType> HasData()
{
return new[]
{
return
[
new SysDictType{ Id=1300000000101, Name="代码生成控件类型", Code="code_gen_effect_type", OrderNo=100, Remark="代码生成控件类型", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysDictType{ Id=1300000000102, Name="代码生成查询类型", Code="code_gen_query_type", OrderNo=101, Remark="代码生成查询类型", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysDictType{ Id=1300000000103, Name="代码生成.NET类型", Code="code_gen_net_type", OrderNo=102, Remark="代码生成.NET类型", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
@ -26,6 +26,6 @@ public class SysDictTypeSeedData : ISqlSugarEntitySeedData<SysDictType>
new SysDictType{ Id=1300000000105, Name="代码生成基类", Code="code_gen_base_class", OrderNo=104, Remark="代码生成基类", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysDictType{ Id=1300000000106, Name="代码生成打印类型", Code="code_gen_print_type", OrderNo=105, Remark="代码生成打印类型", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2023-12-04 00:00:00") },
new SysDictType{ Id=1300000000201, Name="机构类型", Code="org_type", OrderNo=201, Remark="机构类型", Status=StatusEnum.Enable, CreateTime=DateTime.Parse("2023-02-10 00:00:00") },
};
];
}
}

View File

@ -17,8 +17,8 @@ public class SysMenuSeedData : ISqlSugarEntitySeedData<SysMenu>
/// <returns></returns>
public IEnumerable<SysMenu> HasData()
{
return new[]
{
return
[
new SysMenu{ Id=1300000000101, Pid=0, Title="工作台", Path="/dashboard", Name="dashboard", Component="Layout", Icon="ele-HomeFilled", Type=MenuTypeEnum.Dir, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=0 },
new SysMenu{ Id=1300000000111, Pid=1300000000101, Title="工作台", Path="/dashboard/home", Name="home", Component="/home/index", IsAffix=true, Icon="ele-HomeFilled", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=100 },
new SysMenu{ Id=1300000000121, Pid=1300000000101, Title="站内信", Path="/dashboard/notice", Name="notice", Component="/home/notice/index", Icon="ele-Bell", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=101 },
@ -217,6 +217,6 @@ public class SysMenuSeedData : ISqlSugarEntitySeedData<SysMenu>
new SysMenu{ Id=1310000000714, Pid=1310000000701, Title="SqlSugar", Path="/doc/SqlSugar", Name="sysSqlSugar", Component="layout/routerView/link", IsIframe=false, IsKeepAlive=false, OutLink="https://www.donet5.com/Home/Doc", Icon="ele-Coin", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=130 },
new SysMenu{ Id=1310000000801, Pid=0, Title="关于项目", Path="/about", Name="about", Component="/about/index", Icon="ele-InfoFilled", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2023-03-12 00:00:00"), OrderNo=15000 },
};
];
}
}

View File

@ -193,7 +193,7 @@ public class APIJSONService : IDynamicApiController, ITransient
parameters.Add(new SugarParameter($"@{f.Key}", FuncList.TransJObjectToSugarPara(f.Value)));
}
}
if (!parameters.Any())
if (parameters.Count == 0)
throw Oops.Bah("请输入删除条件");
var whereSql = sb.ToString().TrimEnd(" and ");

View File

@ -95,7 +95,7 @@ public class SelectTable : ISingleton
}
else // 列表
{
IList l = tb.ToList();
var l = tb.ToList();
return query == 0 ? new Tuple<dynamic, int>(l, 0) : new Tuple<dynamic, int>(l, l.Count);
}
}
@ -248,8 +248,8 @@ public class SelectTable : ISingleton
{
if (item.Value.IsNullOrEmpty())
{
var func = item.Value.ToString().Substring(0, item.Value.ToString().IndexOf("("));
var param = item.Value.ToString().Substring(item.Value.ToString().IndexOf("(") + 1).TrimEnd(')');
var func = item.Value.ToString()[..item.Value.ToString().IndexOf('(')];
var param = item.Value.ToString()[(item.Value.ToString().IndexOf('(') + 1)..].TrimEnd(')');
var types = new List<Type>();
var paramss = new List<object>();
foreach (var va in param.Split(','))
@ -257,7 +257,7 @@ public class SelectTable : ISingleton
types.Add(typeof(object));
paramss.Add(tb.Where(it => it.Key.Equals(va)).Select(i => i.Value));
}
dic[item.Name] = ExecFunc(func, paramss.ToArray(), types.ToArray());
dic[item.Name] = ExecFunc(func, [.. paramss], [.. types]);
}
}
return tb;
@ -335,7 +335,7 @@ public class SelectTable : ISingleton
var query = jb["query"] == null ? 2 : int.Parse(jb["query"].ToString()); // 默认输出数据和数量
jb.Remove("page"); jb.Remove("count"); jb.Remove("query");
var htt = new JArray();
List<string> tables = new List<string>(), where = new List<string>();
List<string> tables = [], where = [];
foreach (var t in jb)
{
tables.Add(t.Key); where.Add(t.Value.ToString());
@ -410,7 +410,7 @@ public class SelectTable : ISingleton
types.Add(typeof(object));
param.Add(va);
}
dataJObj.Add(f.Key, JToken.FromObject(ExecFunc(f.Key, param.ToArray(), types.ToArray())));
dataJObj.Add(f.Key, JToken.FromObject(ExecFunc(f.Key, [.. param], [.. types])));
}
resultObj.Add("func", dataJObj);
}
@ -512,11 +512,11 @@ public class SelectTable : ISingleton
{
string key = va.Key.Trim();
string fieldValue = va.Value.ToString();
if (key.StartsWith("@"))
if (key.StartsWith('@'))
{
continue;
}
if (key.EndsWith("$")) // 模糊查询
if (key.EndsWith('$')) // 模糊查询
{
FuzzyQuery(subtable, conModels, va);
}
@ -524,11 +524,11 @@ public class SelectTable : ISingleton
{
ConditionQuery(subtable, conModels, va);
}
else if (key.EndsWith("%")) // bwtween查询
else if (key.EndsWith('%')) // bwtween查询
{
ConditionBetween(subtable, conModels, va, tb);
}
else if (key.EndsWith("@")) // 关联上一个table
else if (key.EndsWith('@')) // 关联上一个table
{
if (dd == null)
continue;
@ -541,7 +541,7 @@ public class SelectTable : ISingleton
var value = lastTableRecord[str[^1]].ToString();
conModels.Add(new ConditionalModel() { FieldName = key.TrimEnd('@'), ConditionalType = ConditionalType.Equal, FieldValue = value });
}
else if (key.EndsWith("~")) // 不等于(应该是正则匹配)
else if (key.EndsWith('~')) // 不等于(应该是正则匹配)
{
//conModels.Add(new ConditionalModel() { FieldName = key.TrimEnd('~'), ConditionalType = ConditionalType.NoEqual, FieldValue = fieldValue });
}
@ -550,7 +550,7 @@ public class SelectTable : ISingleton
ConditionEqual(subtable, conModels, va);
}
}
if (conModels.Any())
if (conModels.Count != 0)
tb.Where(conModels);
}
@ -576,39 +576,39 @@ public class SelectTable : ISingleton
var model = new ConditionalModel();
if (and.Contains(">="))
{
model.FieldName = and.Split(new string[] { ">=" }, StringSplitOptions.RemoveEmptyEntries)[0];
model.FieldName = and.Split([">="], StringSplitOptions.RemoveEmptyEntries)[0];
model.ConditionalType = ConditionalType.GreaterThanOrEqual;
model.FieldValue = and.Split(new string[] { ">=" }, StringSplitOptions.RemoveEmptyEntries)[1];
model.FieldValue = and.Split([">="], StringSplitOptions.RemoveEmptyEntries)[1];
}
else if (and.Contains("<="))
{
model.FieldName = and.Split(new string[] { "<=" }, StringSplitOptions.RemoveEmptyEntries)[0];
model.FieldName = and.Split(["<="], StringSplitOptions.RemoveEmptyEntries)[0];
model.ConditionalType = ConditionalType.LessThanOrEqual;
model.FieldValue = and.Split(new string[] { "<=" }, StringSplitOptions.RemoveEmptyEntries)[1];
model.FieldValue = and.Split(["<="], StringSplitOptions.RemoveEmptyEntries)[1];
}
else if (and.Contains('>'))
{
model.FieldName = and.Split(new string[] { ">" }, StringSplitOptions.RemoveEmptyEntries)[0];
model.FieldName = and.Split([">"], StringSplitOptions.RemoveEmptyEntries)[0];
model.ConditionalType = ConditionalType.GreaterThan;
model.FieldValue = and.Split(new string[] { ">" }, StringSplitOptions.RemoveEmptyEntries)[1];
model.FieldValue = and.Split([">"], StringSplitOptions.RemoveEmptyEntries)[1];
}
else if (and.Contains('<'))
{
model.FieldName = and.Split(new string[] { "<" }, StringSplitOptions.RemoveEmptyEntries)[0];
model.FieldName = and.Split(["<"], StringSplitOptions.RemoveEmptyEntries)[0];
model.ConditionalType = ConditionalType.LessThan;
model.FieldValue = and.Split(new string[] { "<" }, StringSplitOptions.RemoveEmptyEntries)[1];
model.FieldValue = and.Split(["<"], StringSplitOptions.RemoveEmptyEntries)[1];
}
else if (and.Contains("!="))
{
model.FieldName = and.Split(new string[] { "!=" }, StringSplitOptions.RemoveEmptyEntries)[0];
model.FieldName = and.Split(["!="], StringSplitOptions.RemoveEmptyEntries)[0];
model.ConditionalType = ConditionalType.NoEqual;
model.FieldValue = and.Split(new string[] { "!=" }, StringSplitOptions.RemoveEmptyEntries)[1];
model.FieldValue = and.Split(["!="], StringSplitOptions.RemoveEmptyEntries)[1];
}
else if (and.Contains('='))
{
model.FieldName = and.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries)[0];
model.FieldName = and.Split(["="], StringSplitOptions.RemoveEmptyEntries)[0];
model.ConditionalType = ConditionalType.Equal;
model.FieldValue = and.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries)[1];
model.FieldValue = and.Split(["="], StringSplitOptions.RemoveEmptyEntries)[1];
}
hw.Add(model);
}
@ -634,7 +634,7 @@ public class SelectTable : ISingleton
groupList.Add(new GroupByModel() { FieldName = col });
}
}
if (groupList.Any())
if (groupList.Count != 0)
tb.GroupBy(groupList);
}
}
@ -653,12 +653,12 @@ public class SelectTable : ISingleton
orderList.Add(new OrderByModel()
{
FieldName = col,
OrderByType = item.EndsWith("-") || item.EndsWith(" desc") ? OrderByType.Desc : OrderByType.Asc
OrderByType = item.EndsWith('-') || item.EndsWith(" desc") ? OrderByType.Desc : OrderByType.Asc
});
}
}
if (orderList.Any())
if (orderList.Count != 0)
tb.OrderBy(orderList);
}
}
@ -687,7 +687,7 @@ public class SelectTable : ISingleton
{
var vakey = va.Key.Trim();
var field = vakey.TrimEnd("{}".ToCharArray());
var columnName = field.TrimEnd(new char[] { '&', '|' });
var columnName = field.TrimEnd(['&', '|']);
IsCol(subtable, columnName);
var ddt = new List<KeyValuePair<WhereType, ConditionalModel>>();
foreach (var and in va.Value.ToString().Split(','))
@ -707,18 +707,18 @@ public class SelectTable : ISingleton
model.ConditionalType = ConditionalType.LessThanOrEqual;
model.FieldValue = and.TrimStart("<=".ToCharArray());
}
else if (and.StartsWith(">"))
else if (and.StartsWith('>'))
{
model.ConditionalType = ConditionalType.GreaterThan;
model.FieldValue = and.TrimStart('>');
}
else if (and.StartsWith("<"))
else if (and.StartsWith('<'))
{
model.ConditionalType = ConditionalType.LessThan;
model.FieldValue = and.TrimStart('<');
}
model.CSharpTypeName = FuncList.GetValueCSharpType(model.FieldValue);
ddt.Add(new KeyValuePair<WhereType, ConditionalModel>(field.EndsWith("!") ? WhereType.Or : WhereType.And, model));
ddt.Add(new KeyValuePair<WhereType, ConditionalModel>(field.EndsWith('!') ? WhereType.Or : WhereType.And, model));
}
conModels.Add(new ConditionalCollections() { ConditionalList = ddt });
}
@ -776,7 +776,7 @@ public class SelectTable : ISingleton
conModels.Add(new ConditionalModel()
{
FieldName = key.TrimEnd('!'),
ConditionalType = key.EndsWith("!") ? ConditionalType.NotIn : ConditionalType.In,
ConditionalType = key.EndsWith('!') ? ConditionalType.NotIn : ConditionalType.In,
FieldValue = va.Value.ToObject<string[]>().Aggregate((a, b) => a + "," + b)
});
}
@ -785,7 +785,7 @@ public class SelectTable : ISingleton
if (string.IsNullOrEmpty(fieldValue))
{
// is not null or ''
if (key.EndsWith("!"))
if (key.EndsWith('!'))
{
conModels.Add(new ConditionalModel() { FieldName = key.TrimEnd('!'), ConditionalType = ConditionalType.IsNot, FieldValue = null });
conModels.Add(new ConditionalModel() { FieldName = key.TrimEnd('!'), ConditionalType = ConditionalType.IsNot, FieldValue = "" });
@ -802,7 +802,7 @@ public class SelectTable : ISingleton
conModels.Add(new ConditionalModel()
{
FieldName = key.TrimEnd('!'),
ConditionalType = key.EndsWith("!") ? ConditionalType.NoEqual : ConditionalType.Equal,
ConditionalType = key.EndsWith('!') ? ConditionalType.NoEqual : ConditionalType.Equal,
FieldValue = fieldValue
});
}
@ -818,19 +818,19 @@ public class SelectTable : ISingleton
if (IsCol(subtable, vakey.TrimEnd('$')))
{
// 支持三种like查询
if (fieldValue.StartsWith("%") && fieldValue.EndsWith("%"))
if (fieldValue.StartsWith('%') && fieldValue.EndsWith('%'))
{
conditionalType = ConditionalType.Like;
}
else if (fieldValue.StartsWith("%"))
else if (fieldValue.StartsWith('%'))
{
conditionalType = ConditionalType.LikeRight;
}
else if (fieldValue.EndsWith("%"))
else if (fieldValue.EndsWith('%'))
{
conditionalType = ConditionalType.LikeLeft;
}
conModels.Add(new ConditionalModel() { FieldName = vakey.TrimEnd('$'), ConditionalType = conditionalType, FieldValue = fieldValue.TrimEnd("%".ToArray()).TrimStart("%".ToArray()) });
conModels.Add(new ConditionalModel() { FieldName = vakey.TrimEnd('$'), ConditionalType = conditionalType, FieldValue = fieldValue.TrimEnd([.. "%"]).TrimStart([.. "%"]) });
}
}
@ -885,23 +885,23 @@ public class SelectTable : ISingleton
foreach (var f in cols) // 遍历字段
{
if (//f.Key.ToLower() != "id" && //是否一定要传id
if (//f.Key.ToLower() != "id" && // 是否一定要传id
IsCol(tableName, f.Key) &&
(role.Insert.Column.Contains("*") || role.Insert.Column.Contains(f.Key, StringComparer.CurrentCultureIgnoreCase)))
dt.Add(f.Key, FuncList.TransJObjectToSugarPara(f.Value));
}
// 如果外部没传Id就后端生成或使用数据库默认值如果都没有会出错
object id;
if (!dt.ContainsKey("id"))
if (!dt.TryGetValue("id", out object value))
{
id = YitIdHelper.NextId();//自己生成id的方法可以由外部传入
id = YitIdHelper.NextId(); // 自己生成id的方法可以由外部传入
dt.Add("id", id);
}
else
{
id = dt["id"];
id = value;
}
_db.Insertable(dt).AS(tableName).ExecuteCommand();//根据主键类型设置返回雪花或自增,目前返回条数
_db.Insertable(dt).AS(tableName).ExecuteCommand(); // 根据主键类型设置返回雪花或自增,目前返回条数
return id;
}
@ -922,7 +922,7 @@ public class SelectTable : ISingleton
var dt = new Dictionary<string, object>();
var sb = new StringBuilder(100);
object id = null;
foreach (var f in record)//遍历每个字段
foreach (var f in record) // 遍历每个字段
{
if (f.Key.Equals("id", StringComparison.OrdinalIgnoreCase))
{

View File

@ -29,8 +29,8 @@ public class AlipayErrorCode
/// <summary>
/// 错误码集
/// </summary>
private static readonly List<AlipayErrorCode> StatusCodes = new()
{
private static readonly List<AlipayErrorCode> StatusCodes =
[
new AlipayErrorCode { Code="SYSTEM_ERROR", Message="系统繁忙", Solution="可能是由于网络或者系统故障,请与技术人员联系以解决该问题。" },
new AlipayErrorCode { Code="INVALID_PARAMETER", Message="参数有误或没有参数", Solution="请检查并确认查询请求参数合法性。" },
new AlipayErrorCode { Code="AUTHORISE_NOT_MATCH", Message="授权失败,无法获取用户信息", Solution="检查账户与支付方关系主表关系,确认是否正确配置。" },
@ -129,7 +129,7 @@ public class AlipayErrorCode
new AlipayErrorCode { Code="USER_AGREEMENT_VERIFY_FAIL", Message="用户协议校验失败", Solution="确认入参中协议号是否正确" },
new AlipayErrorCode { Code="USER_NOT_EXIST", Message="用户不存在仅用于WorldFirst", Solution="用户不存在,请检查收付款方信息" },
new AlipayErrorCode { Code="USER_RISK_FREEZE", Message="账户异常被冻结无法付款请咨询支付宝客服95188", Solution="账户异常被冻结无法付款请咨询支付宝客服95188" }
};
];
/// <summary>
/// 根据错误码获取错误信息

View File

@ -111,7 +111,7 @@ public class AlipayService : IDynamicApiController, ITransient
[ApiDescriptionSettings(Name = "Notify"), HttpPost]
public string Notify()
{
SortedDictionary<string, string> sorted = new();
SortedDictionary<string, string> sorted = [];
foreach (string key in _httpContext.HttpContext!.Request.Form.Keys)
sorted.Add(key, _httpContext.HttpContext.Request.Form[key]);
@ -141,7 +141,7 @@ public class AlipayService : IDynamicApiController, ITransient
{
// 约定交易码前四位为类型码,后面为订单号
var tradeNo = long.Parse(outTradeNo);
var type = long.Parse(outTradeNo.Substring(0, 4));
var type = long.Parse(outTradeNo[..4]);
// 循环执行业务逻辑,若都未处理(回调全部返回false)则交易失败
var isError = true;
@ -221,26 +221,30 @@ public class AlipayService : IDynamicApiController, ITransient
{
// 构造请求参数以调用接口
AlipayFundTransUniTransferRequest request = new();
AlipayFundTransUniTransferModel model = new();
model.BizScene = AlipayConst.BizScene;
model.ProductCode = AlipayConst.ProductCode;
AlipayFundTransUniTransferModel model = new()
{
BizScene = AlipayConst.BizScene,
ProductCode = AlipayConst.ProductCode,
// 设置商家侧唯一订单号
model.OutBizNo = input.OutBizNo;
// 设置商家侧唯一订单号
OutBizNo = input.OutBizNo,
// 设置订单总金额
model.TransAmount = input.TransAmount.ToString();
// 设置订单总金额
TransAmount = input.TransAmount.ToString(),
// 设置转账业务的标题
model.OrderTitle = input.OrderTitle;
// 设置转账业务的标题
OrderTitle = input.OrderTitle
};
// 设置收款方信息
Participant payeeInfo = new();
payeeInfo.CertType = input.CertType.ToString();
payeeInfo.CertNo = input.CertNo;
payeeInfo.Identity = input.Identity;
payeeInfo.Name = input.Name;
payeeInfo.IdentityType = input.IdentityType.ToString();
Participant payeeInfo = new()
{
CertType = input.CertType.ToString(),
CertNo = input.CertNo,
Identity = input.Identity,
Name = input.Name,
IdentityType = input.IdentityType.ToString()
};
model.PayeeInfo = payeeInfo;
// 设置业务备注

View File

@ -112,7 +112,7 @@ public class SysAuthService : IDynamicApiController, ITransient
if (string.IsNullOrWhiteSpace(host) || host.StartsWith("localhost")) host = SqlSugarConst.DefaultTenantHost;
// 租户是否存在或已禁用
tenant = await _sysUserRep.ChangeRepository<SqlSugarRepository<SysTenant>>().GetFirstAsync(u => u.Host == host.ToLower());
tenant = await _sysUserRep.ChangeRepository<SqlSugarRepository<SysTenant>>().GetFirstAsync(u => u.Host.Equals(host, StringComparison.CurrentCultureIgnoreCase));
if (tenant?.Status != StatusEnum.Enable) throw Oops.Oh(ErrorCodeEnum.Z1003);
// 根据入参类型、租户查询登录用户

View File

@ -52,8 +52,8 @@ public class SysCacheService : IDynamicApiController, ISingleton
public List<string> GetKeyList()
{
return _cacheProvider.Cache == Cache.Default
? _cacheProvider.Cache.Keys.Where(u => u.StartsWith(_cacheOptions.Prefix)).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList()
: ((FullRedis)_cacheProvider.Cache).Search($"{_cacheOptions.Prefix}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList();
? [.. _cacheProvider.Cache.Keys.Where(u => u.StartsWith(_cacheOptions.Prefix)).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u)]
: [.. ((FullRedis)_cacheProvider.Cache).Search($"{_cacheOptions.Prefix}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u)];
}
/// <summary>
@ -81,24 +81,24 @@ public class SysCacheService : IDynamicApiController, ISingleton
return !string.IsNullOrWhiteSpace(key) && _cacheProvider.Cache.Set($"{_cacheOptions.Prefix}{key}", value, expire);
}
public async Task<TR> AdGetAsync<TR>(String cacheName, Func<Task<TR>> del, TimeSpan? expiry = default(TimeSpan?)) where TR : class
public async Task<TR> AdGetAsync<TR>(String cacheName, Func<Task<TR>> del, TimeSpan? expiry = default) where TR : class
{
return await AdGetAsync<TR>(cacheName, del, new object[] { }, expiry);
return await AdGetAsync<TR>(cacheName, del, [], expiry);
}
public async Task<TR> AdGetAsync<TR, T1>(String cacheName, Func<T1, Task<TR>> del, T1 t1, TimeSpan? expiry = default(TimeSpan?)) where TR : class
public async Task<TR> AdGetAsync<TR, T1>(String cacheName, Func<T1, Task<TR>> del, T1 t1, TimeSpan? expiry = default) where TR : class
{
return await AdGetAsync<TR>(cacheName, del, new object[] { t1 }, expiry);
return await AdGetAsync<TR>(cacheName, del, [t1], expiry);
}
public async Task<TR> AdGetAsync<TR, T1, T2>(String cacheName, Func<T1, T2, Task<TR>> del, T1 t1, T2 t2, TimeSpan? expiry = default(TimeSpan?)) where TR : class
public async Task<TR> AdGetAsync<TR, T1, T2>(String cacheName, Func<T1, T2, Task<TR>> del, T1 t1, T2 t2, TimeSpan? expiry = default) where TR : class
{
return await AdGetAsync<TR>(cacheName, del, new object[] { t1, t2 }, expiry);
return await AdGetAsync<TR>(cacheName, del, [t1, t2], expiry);
}
public async Task<TR> AdGetAsync<TR, T1, T2, T3>(String cacheName, Func<T1, T2, T3, Task<TR>> del, T1 t1, T2 t2, T3 t3, TimeSpan? expiry = default(TimeSpan?)) where TR : class
public async Task<TR> AdGetAsync<TR, T1, T2, T3>(String cacheName, Func<T1, T2, T3, Task<TR>> del, T1 t1, T2 t2, T3 t3, TimeSpan? expiry = default) where TR : class
{
return await AdGetAsync<TR>(cacheName, del, new object[] { t1, t2, t3 }, expiry);
return await AdGetAsync<TR>(cacheName, del, [t1, t2, t3], expiry);
}
private async Task<T> AdGetAsync<T>(string cacheName, Delegate del, Object[] obs, TimeSpan? expiry) where T : class
@ -116,17 +116,17 @@ public class SysCacheService : IDynamicApiController, ISingleton
public T Get<T>(String cacheName, object t1)
{
return Get<T>(cacheName, new object[] { t1 });
return Get<T>(cacheName, [t1]);
}
public T Get<T>(String cacheName, object t1, object t2)
{
return Get<T>(cacheName, new object[] { t1, t2 });
return Get<T>(cacheName, [t1, t2]);
}
public T Get<T>(String cacheName, object t1, object t2, object t3)
{
return Get<T>(cacheName, new object[] { t1, t2, t3 });
return Get<T>(cacheName, [t1, t2, t3]);
}
private T Get<T>(String cacheName, Object[] obs)
@ -353,7 +353,7 @@ public class SysCacheService : IDynamicApiController, ISingleton
public T HashGetOne<T>(string key, string field)
{
var hash = GetHashMap<T>(key);
return hash.ContainsKey(field) ? hash[field] : default(T);
return hash.TryGetValue(field, out T value) ? value : default;
}
/// <summary>

View File

@ -77,7 +77,7 @@ public class CustomViewEngine : ViewEngineModel
var config = App.GetOptions<DbConnectionOptions>().ConnectionConfigs.FirstOrDefault(u => u.ConfigId.ToString() == ConfigId);
ColumnList = GetColumnListByTableName(tbName.ToString());
var col = ColumnList.Where(c => (config.DbSettings.EnableUnderLine
? CodeGenUtil.CamelColumnName(c.ColumnName, Array.Empty<string>())
? CodeGenUtil.CamelColumnName(c.ColumnName, [])
: c.ColumnName) == colName.ToString()).FirstOrDefault();
return col.NetType;
}

View File

@ -123,10 +123,10 @@ public class SysCodeGenConfigService : IDynamicApiController, ITransient
#region
//添加校验规则
// 添加校验规则
codeGenConfig.Id = YitIdHelper.NextId();
//验证规则
List<VerifyRuleItem> ruleItems = new List<VerifyRuleItem>();
// 验证规则
List<VerifyRuleItem> ruleItems = [];
if (!tableColumn.IsNullable && !tableColumn.IsPrimarykey)
{
ruleItems.Add(new VerifyRuleItem()
@ -184,7 +184,6 @@ public class SysCodeGenConfigService : IDynamicApiController, ITransient
private static string? GetDefaultValue(string dataValue)
{
if (dataValue == null) return null;
string value = "";
// 正则表达式模式
// \( 和 \) 用来匹配字面量的括号
// .+ 用来匹配一个或多个任意字符,但不包括换行符
@ -193,6 +192,7 @@ public class SysCodeGenConfigService : IDynamicApiController, ITransient
// 使用 Regex 类进行匹配
Match match = Regex.Match(dataValue, pattern);
string value;
// 如果找到了匹配项
if (match.Success)
{

View File

@ -39,5 +39,5 @@ public class ApiOutput
/// <summary>
/// 接口列表
/// </summary>
public List<ApiOutput> Children { get; set; } = new List<ApiOutput>();
public List<ApiOutput> Children { get; set; } = [];
}

View File

@ -63,7 +63,7 @@ public class ExportProcInput2 : BaseProcInput
/// </summary>
public class ProcExporterHeaderFilter : IExporterHeaderFilter
{
private Dictionary<string, Tuple<string, int>> _includeHeader;
private readonly Dictionary<string, Tuple<string, int>> _includeHeader;
public ProcExporterHeaderFilter(Dictionary<string, Tuple<string, int>> includeHeader)
{
@ -75,9 +75,9 @@ public class ProcExporterHeaderFilter : IExporterHeaderFilter
if (_includeHeader != null && _includeHeader.Count > 0)
{
var key = exporterHeaderInfo.PropertyName.ToUpper();
if (_includeHeader.ContainsKey(key))
if (_includeHeader.TryGetValue(key, out Tuple<string, int> value))
{
exporterHeaderInfo.DisplayName = _includeHeader[key].Item1;
exporterHeaderInfo.DisplayName = value.Item1;
return exporterHeaderInfo;
}
else

View File

@ -18,13 +18,10 @@ namespace Admin.NET.Core.Service;
public class SysCommonService : IDynamicApiController, ITransient
{
private readonly IApiDescriptionGroupCollectionProvider _apiProvider;
private readonly UserManager _userManager;
public SysCommonService(IApiDescriptionGroupCollectionProvider apiProvider,
UserManager userManager)
public SysCommonService(IApiDescriptionGroupCollectionProvider apiProvider)
{
_apiProvider = apiProvider;
_userManager = userManager;
}
/// <summary>
@ -109,8 +106,7 @@ public class SysCommonService : IDynamicApiController, ITransient
route = route[(route.IndexOf('/') + 1)..]; // 去掉路由前缀
// 接口分组/控制器信息
var controllerActionDescriptor = action.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor == null)
if (action.ActionDescriptor is not ControllerActionDescriptor controllerActionDescriptor)
continue;
// 是否只获取所有的移动端/AppApi接口
@ -150,7 +146,7 @@ public class SysCommonService : IDynamicApiController, ITransient
});
// 接口分组/控制器排序
apiOuput.Children = apiOuput.Children.OrderByDescending(u => u.Order).ToList();
apiOuput.Children = [.. apiOuput.Children.OrderByDescending(u => u.Order)];
}
apiList.Add(apiOuput);
@ -169,8 +165,7 @@ public class SysCommonService : IDynamicApiController, ITransient
var apiList = sysCacheService.Get<List<string>>(CacheConst.KeyAppApi);
if (apiList == null)
{
apiList = new List<string>();
apiList = [];
var allApiList = GetApiList("", true);
foreach (var apiOutput in allApiList)
{
@ -190,9 +185,7 @@ public class SysCommonService : IDynamicApiController, ITransient
public async Task<IActionResult> DownloadErrorExcelTemp([FromQuery] string fileName = null)
{
var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
var resultStream = App.GetRequiredService<SysCacheService>().Get<MemoryStream>(CacheConst.KeyExcelTemp + userId);
if (resultStream == null) throw Oops.Oh("错误标记文件已过期。");
var resultStream = App.GetRequiredService<SysCacheService>().Get<MemoryStream>(CacheConst.KeyExcelTemp + userId) ?? throw Oops.Oh("错误标记文件已过期。");
return await Task.FromResult(new FileStreamResult(resultStream, "application/octet-stream")
{

View File

@ -178,7 +178,7 @@ public class SysFileService : IDynamicApiController, ITransient
if (App.Configuration["SSHProvider:Enabled"].ToBoolean())
{
var sysFile = await _sysFileRep.CopyNew().GetFirstAsync(u => u.Url == url) ?? throw Oops.Oh($"文件不存在");
using SSHHelper helper = new SSHHelper(App.Configuration["SSHProvider:Host"],
using SSHHelper helper = new(App.Configuration["SSHProvider:Host"],
App.Configuration["SSHProvider:Port"].ToInt(), App.Configuration["SSHProvider:Username"], App.Configuration["SSHProvider:Password"]);
return Convert.ToBase64String(helper.ReadAllBytes(sysFile.FilePath));
}

View File

@ -79,8 +79,7 @@ public class SysLogExService : IDynamicApiController, ITransient
.OrderBy(u => u.CreateTime, OrderByType.Desc)
.Select<ExportLogDto>().ToListAsync();
IExcelExporter excelExporter = new ExcelExporter();
var res = await excelExporter.ExportAsByteArray(logExList);
var res = await ((IExcelExporter)new ExcelExporter()).ExportAsByteArray(logExList);
return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "异常日志.xlsx" };
}
}

View File

@ -77,8 +77,7 @@ public class SysLogOpService : IDynamicApiController, ITransient
.OrderBy(u => u.CreateTime, OrderByType.Desc)
.Select<ExportLogDto>().ToListAsync();
IExcelExporter excelExporter = new ExcelExporter();
var res = await excelExporter.ExportAsByteArray(logOpList);
var res = await ((IExcelExporter)new ExcelExporter()).ExportAsByteArray(logOpList);
return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "操作日志.xlsx" };
}

View File

@ -287,7 +287,7 @@ public class SysOrgService : IDynamicApiController, ITransient
[NonAction]
public async Task<List<long>> GetUserOrgIdList()
{
if (_userManager.SuperAdmin) return new();
if (_userManager.SuperAdmin) return [];
return await GetUserOrgIdList(_userManager.UserId, _userManager.OrgId);
}
@ -325,7 +325,7 @@ public class SysOrgService : IDynamicApiController, ITransient
private async Task<List<long>> GetUserRoleOrgIdList(long userId, long userOrgId)
{
var roleList = await _sysUserRoleService.GetUserRoleList(userId);
if (roleList.Count < 1) return new(); // 空机构Id集合
if (roleList.Count < 1) return []; // 空机构Id集合
return await GetUserOrgIdList(roleList, userId, userOrgId);
}
@ -345,7 +345,7 @@ public class SysOrgService : IDynamicApiController, ITransient
var roleList = await _sysUserRoleService.GetUserRoleList(userId);
if (roleList != null && roleList.Exists(r => r.Code == role.Code)) return true;
roleList = new List<SysRole> { role };
roleList = [role];
var orgIds = await GetUserOrgIdList(roleList, userId, userOrgId);
return orgIds.Contains(userOrgId);
}

View File

@ -108,8 +108,7 @@ public class SysRegionService : IDynamicApiController, ITransient
input.Code = input.Code?.Trim() ?? "";
if (input.Code.Length != 12 && input.Code.Length != 9 && input.Code.Length != 6) throw Oops.Oh(ErrorCodeEnum.R2003);
var sysRegion = await _sysRegionRep.GetByIdAsync(input.Id);
if (sysRegion == null) throw Oops.Oh(ErrorCodeEnum.D1002);
var sysRegion = await _sysRegionRep.GetByIdAsync(input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
if (sysRegion.Pid != input.Pid && input.Pid != 0)
{

View File

@ -164,7 +164,7 @@ public class SysTenantService : IDynamicApiController, ITransient
if (tenant == null || tenant.ConfigId == SqlSugarConst.MainConfigId)
throw Oops.Oh(ErrorCodeEnum.Z1001);
if (!Enum.IsDefined(typeof(StatusEnum), input.Status))
if (!Enum.IsDefined(input.Status))
throw Oops.Oh(ErrorCodeEnum.D3005);
tenant.Status = input.Status;
@ -381,7 +381,7 @@ public class SysTenantService : IDynamicApiController, ITransient
public async Task<List<long>> GetOwnMenuList([FromQuery] TenantUserInput input)
{
var roleIds = await _sysUserRoleService.GetUserRoleIdList(input.UserId);
return await _sysRoleMenuService.GetRoleMenuIdList(new List<long> { roleIds[0] });
return await _sysRoleMenuService.GetRoleMenuIdList([roleIds[0]]);
}
/// <summary>

View File

@ -548,7 +548,7 @@ public static class SqlSugarSetup
{
var instance = Activator.CreateInstance(seedType);
var hasDataMethod = seedType.GetMethod("HasData");
var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>().ToList() ?? new List<object>();
var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>().ToList() ?? [];
if (seedData.Count == 0) continue;
var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();

View File

@ -229,12 +229,10 @@ public static class CommonUtil
/// <returns></returns>
public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file) where T : class, new()
{
IImporter importer = new ExcelImporter();
var res = await importer.Import<T>(file.OpenReadStream());
var message = string.Empty;
var res = await ((IImporter)new ExcelImporter()).Import<T>(file.OpenReadStream());
if (!res.HasError) return res.Data;
var message = string.Empty;
if (res.Exception != null)
message += $"\r\n{res.Exception.Message}";
foreach (DataRowErrorInfo drErrorInfo in res.RowErrors)
@ -256,20 +254,19 @@ public static class CommonUtil
/// <returns></returns>
public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file, Func<ImportResult<T>, ImportResult<T>> importResultCallback = null) where T : class, new()
{
IImporter importer = new ExcelImporter();
var resultStream = new MemoryStream();
var res = await importer.Import<T>(file.OpenReadStream(), resultStream, importResultCallback);
var res = await ((IImporter)new ExcelImporter()).Import<T>(file.OpenReadStream(), resultStream, importResultCallback);
resultStream.Seek(0, SeekOrigin.Begin);
var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
if (!res.HasError) return res.Data;
var message = string.Empty;
if (res.Exception != null)
message += $"\r\n{res.Exception.Message}";
var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
App.GetRequiredService<SysCacheService>().Remove(CacheConst.KeyExcelTemp + userId);
App.GetRequiredService<SysCacheService>().Set(CacheConst.KeyExcelTemp + userId, resultStream, TimeSpan.FromMinutes(5));
var message = string.Empty;
if (!res.HasError) return res.Data;
if (res.Exception != null)
message += $"\r\n{res.Exception.Message}";
foreach (DataRowErrorInfo drErrorInfo in res.RowErrors)
{
message = drErrorInfo.FieldErrors.Aggregate(message, (current, item) => current + $"\r\n{item.Key}{item.Value}(文件第{drErrorInfo.RowIndex}行)");
@ -278,7 +275,7 @@ public static class CommonUtil
message += "\r\n字段缺失" + string.Join("", res.TemplateErrors.Select(m => m.RequireColumnName).ToList());
if (message.Length > 200)
message = message.Substring(0, 200) + "...\r\n异常过多建议下载错误标记文件查看详细错误信息并重新导入。";
message = string.Concat(message.AsSpan(0, 200), "...\r\n异常过多建议下载错误标记文件查看详细错误信息并重新导入。");
throw Oops.Oh("导入异常:" + message);
}
@ -294,8 +291,7 @@ public static class CommonUtil
var newFile = await sysFileService.UploadFile(new UploadFileInput { File = file });
var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, newFile.FilePath!, newFile.Id + newFile.Suffix);
IImporter importer = new ExcelImporter();
var res = await importer.Import<T>(filePath);
var res = await ((IImporter)new ExcelImporter()).Import<T>(filePath);
// 删除文件
_ = sysFileService.DeleteFile(new DeleteFileInput { Id = newFile.Id });
@ -307,7 +303,7 @@ public static class CommonUtil
if (res.TemplateErrors?.Count > 0)
throw Oops.Oh("模板异常:" + res.TemplateErrors.Select(x => $"[{x.RequireColumnName}]{x.Message}").Join("\n"));
return res.Data.ToList();
return [.. res.Data];
}
// 例List<Dm_ApplyDemo> ls = CommonUtil.ParseList<Dm_ApplyDemoInport, Dm_ApplyDemo>(importResult.Data);

View File

@ -29,7 +29,7 @@ public class ExcelHelper
// 标记校验信息
tasks.Add(Task.Run(() =>
{
if (!storageable.TotalList.Any()) return;
if (storageable.TotalList.Count == 0) return;
// 通过Id标记校验信息
var itemMap = pageItems.ToDictionary(u => u.Id, u => u);
@ -46,11 +46,11 @@ public class ExcelHelper
// 仅导出错误记录
var errorList = result.Where(u => !string.IsNullOrWhiteSpace(u.Error));
return ExportData(errorList.Any() ? errorList : new List<IN>());
return ExportData(errorList.Any() ? errorList : []);
}
catch (Exception ex)
{
App.HttpContext.Response.Headers["Content-Type"] = "application/json; charset=utf-8";
App.HttpContext.Response.Headers.ContentType = "application/json; charset=utf-8";
throw Oops.Oh(new AdminResult<object>
{
Code = 500,

View File

@ -30,8 +30,8 @@ namespace Admin.NET.Core;
public class GM
{
private static X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
private static ECDomainParameters ecDomainParameters = new(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N);
private static readonly X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
private static readonly ECDomainParameters ecDomainParameters = new(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N);
/**
*
@ -162,7 +162,7 @@ public class GM
public static byte[] Sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey)
{
SM2Engine sm2Engine = new SM2Engine();
SM2Engine sm2Engine = new();
sm2Engine.Init(true, new ParametersWithRandom(pubkey, new SecureRandom()));
return sm2Engine.ProcessBlock(data, 0, data.Length);
}
@ -176,7 +176,7 @@ public class GM
public static byte[] Sm2DecryptOld(byte[] data, AsymmetricKeyParameter key)
{
SM2Engine sm2Engine = new SM2Engine();
SM2Engine sm2Engine = new();
sm2Engine.Init(false, key);
return sm2Engine.ProcessBlock(data, 0, data.Length);
}
@ -242,13 +242,13 @@ public class GM
private static byte[] RsPlainByteArrayToAsn1(byte[] sign)
{
if (sign.Length != RS_LEN * 2) throw new ArgumentException("err rs. ");
BigInteger r = new BigInteger(1, Arrays.CopyOfRange(sign, 0, RS_LEN));
BigInteger s = new BigInteger(1, Arrays.CopyOfRange(sign, RS_LEN, RS_LEN * 2));
Asn1EncodableVector v = new Asn1EncodableVector
{
BigInteger r = new(1, Arrays.CopyOfRange(sign, 0, RS_LEN));
BigInteger s = new(1, Arrays.CopyOfRange(sign, RS_LEN, RS_LEN * 2));
Asn1EncodableVector v =
[
new DerInteger(r),
new DerInteger(s)
};
];
return new DerSequence(v).GetEncoded("DER");
}
@ -287,8 +287,7 @@ public class GM
}
finally
{
if (fileStream != null)
fileStream.Close();
fileStream?.Close();
}
return null;
}
@ -302,11 +301,13 @@ public class GM
private static byte[] ToByteArray(int i)
{
byte[] byteArray = new byte[4];
byteArray[0] = (byte)(i >> 24);
byteArray[1] = (byte)((i & 0xFFFFFF) >> 16);
byteArray[2] = (byte)((i & 0xFFFF) >> 8);
byteArray[3] = (byte)(i & 0xFF);
byte[] byteArray =
[
(byte)(i >> 24),
(byte)((i & 0xFFFFFF) >> 16),
(byte)((i & 0xFFFF) >> 8),
(byte)(i & 0xFF),
];
return byteArray;
}
@ -319,12 +320,12 @@ public class GM
private static byte[] Join(params byte[][] byteArrays)
{
List<byte> byteSource = new();
List<byte> byteSource = [];
for (int i = 0; i < byteArrays.Length; i++)
{
byteSource.AddRange(byteArrays[i]);
}
byte[] data = byteSource.ToArray();
byte[] data = [.. byteSource];
return data;
}
@ -341,7 +342,7 @@ public class GM
{
int ct = 1;
int end = (int)Math.Ceiling(klen * 1.0 / 32);
List<byte> byteSource = new();
List<byte> byteSource = [];
for (int i = 1; i < end; i++)
{
@ -355,7 +356,7 @@ public class GM
}
else
byteSource.AddRange(Arrays.CopyOfRange(last, 0, klen % 32));
return byteSource.ToArray();
return [.. byteSource];
}
public static byte[] Sm4DecryptCBC(byte[] keyBytes, byte[] cipher, byte[] iv, string algo)
@ -365,7 +366,7 @@ public class GM
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
if (iv == null) iv = ZeroIv(algo);
iv ??= ZeroIv(algo);
c.Init(false, new ParametersWithIV(key, iv));
return c.DoFinal(cipher);
}
@ -377,7 +378,7 @@ public class GM
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
if (iv == null) iv = ZeroIv(algo);
iv ??= ZeroIv(algo);
c.Init(true, new ParametersWithIV(key, iv));
return c.DoFinal(plain);
}

View File

@ -241,13 +241,13 @@ public class Startup : AppStartup
options.EnableForHttps = true;
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
{
"text/html; charset=utf-8",
"application/xhtml+xml",
"application/atom+xml",
"image/svg+xml"
});
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
[
"text/html; charset=utf-8",
"application/xhtml+xml",
"application/atom+xml",
"image/svg+xml"
]);
});
// 注册虚拟文件系统服务
@ -286,7 +286,7 @@ public class Startup : AppStartup
var cpMappings = App.GetConfig<Dictionary<string, string>>("StaticContentTypeMappings");
if (cpMappings != null)
{
if (cpMappings.Keys.Contains(".*"))
if (cpMappings.TryGetValue(".*", out string value))
{
app.UseStaticFiles(new StaticFileOptions
{
@ -294,7 +294,7 @@ public class Startup : AppStartup
// RequestPath = "/static",
ServeUnknownFileTypes = true, // 允许服务未知文件类型,以便能处理.dll这种非默认的静态文件类型
// DefaultContentType = "application/octet-stream" // 为未知文件类型设置一个通用的内容类型
DefaultContentType = cpMappings[".*"]
DefaultContentType = value
});
}
else