From 7622668170f8341cd98e9a32d559f0073cedcc95 Mon Sep 17 00:00:00 2001 From: 移动系统liao <liaoxujun@qq.com> Date: 星期三, 14 八月 2024 10:38:40 +0800 Subject: [PATCH] no message --- cylsg/cylsg.Application/System/Dtos/Mapper.cs | 8 cylsg/cylsg.Application/System/Services/ISystemService.cs | 6 cylsg/cylsg.Web.Entry/appsettings.Development.json | 10 .gitignore | 14 cylsg/cylsg.Core/DbContext.cs | 22 cylsg/cylsg.Core/DbCoreUntil.cs | 34 cylsg/cylsg.Web.Core/cylsg.Web.Core.csproj | 20 cylsg/cylsg.Core/BaseModelBase.cs | 86 + cylsg/cylsg.sln | 55 + cylsg/cylsg.Core/Attributes/CoderFirstAttribute.cs | 16 cylsg/cylsg.utility/Extend/EmunEx.cs | 15 cylsg/cylsg.Web.Core/Startup.cs | 62 + cylsg/cylsg.utility/CommonHelper.cs | 850 ++++++++++++++++ cylsg/cylsg.Web.Entry/SingleFilePublish.cs | 22 cylsg/cylsg.Web.Entry/Views/Home/Index.cshtml | 9 cylsg/cylsg.Web.Entry/appsettings.json | 23 cylsg/cylsg.Application/cylsg.Application.xml | 19 cylsg/cylsg.Application/GlobalUsings.cs | 15 cylsg/cylsg.Web.Entry/Views/_ViewImports.cshtml | 2 cylsg/cylsg.Web.Core/cylsg.Web.Core.xml | 8 cylsg/cylsg.Application/cylsg.Application.csproj | 33 cylsg/cylsg.Web.Entry/Views/Shared/_Layout.cshtml | 11 cylsg/cylsg.Web.Core/Handlers/JwtHandler.cs | 16 cylsg/cylsg.utility/Extend/TypeAndExpressionEx.cs | 1021 +++++++++++++++++++ cylsg/cylsg.Model/UserModel/User.cs | 62 + cylsg/cylsg.Web.Entry/Views/_ViewStart.cshtml | 3 cylsg/cylsg.Web.Entry/Program.cs | 1 cylsg/cylsg.Application/applicationsettings.json | 31 cylsg/cylsg.Web.Entry/wwwroot/images/logo.png | 0 cylsg/cylsg.Core/cylsg.Core.csproj | 27 cylsg/cylsg.Model/cylsg.Model.csproj | 14 cylsg/cylsg.Application/System/SystemAppService.cs | 47 cylsg/cylsg.Web.Entry/Properties/launchSettings.json | 28 cylsg/cylsg.Core/BaseRepository.cs | 98 + cylsg/cylsg.Application/System/Services/SystemService.cs | 9 cylsg/cylsg.Web.Entry/cylsg.Web.Entry.csproj.user | 9 cylsg/cylsg.Core/cylsg.Core.xml | 119 ++ cylsg/cylsg.Web.Entry/Controllers/HomeController.cs | 23 cylsg/cylsg.Web.Entry/cylsg.Web.Entry.csproj | 17 cylsg/cylsg.utility/Extend/StringEx.cs | 236 ++++ cylsg/cylsg.utility/cylsg.utility.csproj | 13 41 files changed, 3,114 insertions(+), 0 deletions(-) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d625e6b --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +cylsg/.vs/ +cylsg/cylsg.Application/bin/ +cylsg/cylsg.Application/obj/ +cylsg/cylsg.Core/bin/ +cylsg/cylsg.Core/obj/ +cylsg/cylsg.Model/bin/Debug/net8.0/cylsg.Core.dll +cylsg/cylsg.Model/bin/ +cylsg/cylsg.Model/obj/ +cylsg/cylsg.utility/bin/ +cylsg/cylsg.utility/obj/ +cylsg/cylsg.Web.Core/bin/ +cylsg/cylsg.Web.Core/obj/ +cylsg/cylsg.Web.Entry/bin/ +cylsg/cylsg.Web.Entry/obj/ diff --git a/cylsg/cylsg.Application/GlobalUsings.cs b/cylsg/cylsg.Application/GlobalUsings.cs new file mode 100644 index 0000000..1f0aacd --- /dev/null +++ b/cylsg/cylsg.Application/GlobalUsings.cs @@ -0,0 +1,15 @@ +锘縢lobal using Furion; +global using Furion.DataEncryption; +global using Furion.DataValidation; +global using Furion.DependencyInjection; +global using Furion.DynamicApiController; +global using Furion.Extensions; +global using Furion.FriendlyException; +global using Furion.Logging; +global using Mapster; +global using Microsoft.AspNetCore.Authorization; +global using Microsoft.AspNetCore.Http; +global using Microsoft.AspNetCore.Mvc; +global using Microsoft.CodeAnalysis; +global using System.ComponentModel.DataAnnotations; +global using SqlSugar; \ No newline at end of file diff --git a/cylsg/cylsg.Application/System/Dtos/Mapper.cs b/cylsg/cylsg.Application/System/Dtos/Mapper.cs new file mode 100644 index 0000000..6d48d82 --- /dev/null +++ b/cylsg/cylsg.Application/System/Dtos/Mapper.cs @@ -0,0 +1,8 @@ +锘縩amespace cylsg.Application; + +public class Mapper : IRegister +{ + public void Register(TypeAdapterConfig config) + { + } +} diff --git a/cylsg/cylsg.Application/System/Services/ISystemService.cs b/cylsg/cylsg.Application/System/Services/ISystemService.cs new file mode 100644 index 0000000..6eefc39 --- /dev/null +++ b/cylsg/cylsg.Application/System/Services/ISystemService.cs @@ -0,0 +1,6 @@ +锘縩amespace cylsg.Application; + +public interface ISystemService +{ + string GetDescription(); +} diff --git a/cylsg/cylsg.Application/System/Services/SystemService.cs b/cylsg/cylsg.Application/System/Services/SystemService.cs new file mode 100644 index 0000000..81e7885 --- /dev/null +++ b/cylsg/cylsg.Application/System/Services/SystemService.cs @@ -0,0 +1,9 @@ +锘縩amespace cylsg.Application; + +public class SystemService : ISystemService, ITransient +{ + public string GetDescription() + { + return "璁� .NET 寮�鍙戞洿绠�鍗曪紝鏇撮�氱敤锛屾洿娴佽銆�"; + } +} diff --git a/cylsg/cylsg.Application/System/SystemAppService.cs b/cylsg/cylsg.Application/System/SystemAppService.cs new file mode 100644 index 0000000..492a54e --- /dev/null +++ b/cylsg/cylsg.Application/System/SystemAppService.cs @@ -0,0 +1,47 @@ +锘縰sing cylsg.Core.Attributes; +using cylsg.Core; + +namespace cylsg.Application; + +/// <summary> +/// 绯荤粺鏈嶅姟鎺ュ彛 +/// </summary> +public class SystemAppService : IDynamicApiController +{ + private readonly ISystemService _systemService; + private ISqlSugarClient _sqlSugarClient; + public SystemAppService(ISystemService systemService,ISqlSugarClient sqlSugarClient) + { + _systemService = systemService; + _sqlSugarClient = sqlSugarClient; + } + + + /// <summary> + /// 鍒涘缓绯荤粺 + /// </summary> + /// <returns></returns> + public string codefirst() + { + + + try + { + //_ez.GetDb().AsTenant().ChangeDatabase(ConfigId); + _sqlSugarClient.DbMaintenance.CreateDatabase(); + Type[]? types = DbCoreUntil.DbCodeFirstModes("cylsg.Model", thisAttribute: typeof(CoderFirstAttribute)); + + + _sqlSugarClient.CodeFirst.SetStringDefaultLength(512).InitTables(types ?? new Type[] { }); + + return "鍒涘缓鎴愬姛"; + } + catch (Exception e) + { + + return $"鍒涘缓澶辫触锛屾姤閿欙細 {e.Message}锛�-----璇︽儏:{e.StackTrace}"; + + } + + } +} diff --git a/cylsg/cylsg.Application/applicationsettings.json b/cylsg/cylsg.Application/applicationsettings.json new file mode 100644 index 0000000..b01b457 --- /dev/null +++ b/cylsg/cylsg.Application/applicationsettings.json @@ -0,0 +1,31 @@ +锘縶 + "$schema": "https://gitee.com/dotnetchina/Furion/raw/v4/schemas/v4/furion-schema.json", + "SpecificationDocumentSettings": { + "DocumentTitle": "Furion | 瑙勮寖鍖栨帴鍙�", + "GroupOpenApiInfos": [ + { + "Group": "Default", + "Title": "瑙勮寖鍖栨紨绀�", + "Description": "宸濆嵃鐏垫椂宸�", + "Version": "1.0.0", + + "Contact": { + "Name": "", + + "Email": "monksoul@outlook.com" + }, + "License": { + "Name": "Apache-2.0" + + } + } + ] + }, + "CorsAccessorSettings": { + "WithExposedHeaders": [ + "access-token", + "x-access-token", + "environment" + ] + } +} \ No newline at end of file diff --git a/cylsg/cylsg.Application/cylsg.Application.csproj b/cylsg/cylsg.Application/cylsg.Application.csproj new file mode 100644 index 0000000..71a7b0e --- /dev/null +++ b/cylsg/cylsg.Application/cylsg.Application.csproj @@ -0,0 +1,33 @@ +锘�<Project Sdk="Microsoft.NET.Sdk"> + + + + <PropertyGroup> + <TargetFramework>net8.0</TargetFramework> + <NoWarn>1701;1702;1591</NoWarn> + <DocumentationFile>cylsg.Application.xml</DocumentationFile> + <ImplicitUsings>enable</ImplicitUsings> + </PropertyGroup> + + + <ItemGroup> + <None Remove="applicationsettings.json" /> + <None Remove="cylsg.Application.xml" /> + </ItemGroup> + + <ItemGroup> + <Content Include="applicationsettings.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </Content> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="..\cylsg.Core\cylsg.Core.csproj" /> + <ProjectReference Include="..\cylsg.Model\cylsg.Model.csproj" /> + </ItemGroup> + + <ItemGroup> + <Folder Include="System\Services\" /> + </ItemGroup> + +</Project> diff --git a/cylsg/cylsg.Application/cylsg.Application.xml b/cylsg/cylsg.Application/cylsg.Application.xml new file mode 100644 index 0000000..bc89ada --- /dev/null +++ b/cylsg/cylsg.Application/cylsg.Application.xml @@ -0,0 +1,19 @@ +<?xml version="1.0"?> +<doc> + <assembly> + <name>cylsg.Application</name> + </assembly> + <members> + <member name="T:cylsg.Application.SystemAppService"> + <summary> + 绯荤粺鏈嶅姟鎺ュ彛 + </summary> + </member> + <member name="M:cylsg.Application.SystemAppService.codefirst"> + <summary> + 鍒涘缓绯荤粺 + </summary> + <returns></returns> + </member> + </members> +</doc> diff --git a/cylsg/cylsg.Core/Attributes/CoderFirstAttribute.cs b/cylsg/cylsg.Core/Attributes/CoderFirstAttribute.cs new file mode 100644 index 0000000..e7facf9 --- /dev/null +++ b/cylsg/cylsg.Core/Attributes/CoderFirstAttribute.cs @@ -0,0 +1,16 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace cylsg.Core.Attributes +{ + /// <summary> + /// /鏍囪鏄惁鏄痗odefirst + /// </summary> + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + public class CoderFirstAttribute : Attribute + { + } +} diff --git a/cylsg/cylsg.Core/BaseModelBase.cs b/cylsg/cylsg.Core/BaseModelBase.cs new file mode 100644 index 0000000..e722934 --- /dev/null +++ b/cylsg/cylsg.Core/BaseModelBase.cs @@ -0,0 +1,86 @@ +锘縰sing SqlSugar; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace cylsg.Core +{ + /// <summary> + /// 鏈�鍩虹鐨勬ā鍨嬶紝鍒涘缓鏃堕棿鍒涘缓浜鸿褰� + /// </summary> + public class BaseModelBase + { + /// <summary> + /// 鍒涘缓鏃堕棿 + /// </summary> + [Display(Name = "鍒涘缓鏃堕棿 ")] + [SugarColumn(ColumnDescription = "鍒涘缓鏃堕棿 ")] + public DateTime? CreateTime { get; set; } + /// <summary> + /// 鍒涘缓浜� + /// </summary> + [Display(Name = "鍒涘缓浜� ")] + [SugarColumn(ColumnDescription = "鍒涘缓浜� ", Length = 100)] + public string CreateBy { get; set; } + /// <summary> + /// 淇敼鏃堕棿 + /// </summary> + [Display(Name = "淇敼鏃堕棿 ")] + [SugarColumn(ColumnDescription = "淇敼鏃堕棿 ")] + public DateTime? UpDataTime { get; set; } + /// <summary> + /// 淇敼浜� + /// </summary> + [Display(Name = "淇敼浜� ")] + [SugarColumn(ColumnDescription = "淇敼浜� ", Length = 100)] + public string UpDataBy { get; set; } + + + + } + /// <summary> + /// 淇鍩虹妯″瀷锛屽寘鎷簡鍒犻櫎鏍囧織锛岀敓鏁堟爣蹇楋紝鎺掑簭锛屽拰浣胯兘 + /// </summary> + public class BaseModel : BaseModelBase + { + + + /// <summary> + /// 鏄惁鍒犻櫎 + /// </summary> + [Display(Name = "鏄惁鍒犻櫎 ")] + [SugarColumn(ColumnDescription = "鏄惁鍒犻櫎 ", DefaultValue = "0")] + public bool IsDeleted { get; set; } = false; + + /// <summary> + /// 鏄惁鏈夋晥 + /// </summary> + [Display(Name = "鏄惁鏈夋晥 ")] + [SugarColumn(ColumnDescription = "鏄惁鏈夋晥 ", DefaultValue = "1")] + public bool IsEn { get; set; } = true; + + /// <summary> + /// 鎺掑簭 + /// </summary> + [Display(Name = "鎺掑簭 ")] + [SugarColumn(ColumnDescription = "鎺掑簭 ", IsNullable = true)] + public int? Sort { get; set; } + + /// <summary> + /// 鏍囨敞 + /// </summary> + [Display(Name = "鏍囨敞 ")] + [SugarColumn(ColumnDescription = "鏍囨敞 ", IsNullable = true)] + public string Remake { get; set; } + + /// <summary> + /// 绉熸埛 + /// </summary> + [Display(Name = "绉熸埛 ")] + [SugarColumn(ColumnDescription = "绉熸埛 鎵╁睍 ", IsNullable = true)] + public int? TenantID { get; set; } + } +} diff --git a/cylsg/cylsg.Core/BaseRepository.cs b/cylsg/cylsg.Core/BaseRepository.cs new file mode 100644 index 0000000..3998dae --- /dev/null +++ b/cylsg/cylsg.Core/BaseRepository.cs @@ -0,0 +1,98 @@ +锘縰sing Furion; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; + +namespace cylsg.Core +{ + /// <summary> + /// 浠撳偍绫伙紝浣跨敤鏂瑰紡鍙渶瑕佺户鎵垮氨琛� + /// </summary> + /// <typeparam name="T"></typeparam> + public class BaseRepository<T> : SimpleClient<T> where T : class, new() + { + + + public BaseRepository(ISqlSugarClient context = null) : base(context)//榛樿鍊肩瓑浜巒ull涓嶈兘灏� + { + base.Context = App.GetService<ISqlSugarClient>();//鐢ㄦ墜鍔ㄨ幏鍙栨柟寮忔敮鎸佸垏鎹粨鍌� + + } + /// <summary> + /// 閲嶅啓鏇存柊鏂规硶 + /// </summary> + /// <param name="updateObj"></param> + /// <returns></returns> + public Task<bool> EzUpdateAsync(T updateObj) + { + + var intbs = updateObj as BaseModelBase; + if (intbs != null) + { + intbs.UpDataBy = GetJwtBy(); + intbs.UpDataTime = DateTime.Now; + } + return base.UpdateAsync(updateObj); + } + /// <summary> + /// 寮傛鎻掑叆 + /// </summary> + /// <param name="insertObj"></param> + /// <returns></returns> + public Task<bool> EzInsertAsync(T insertObj) + { + var intbs = insertObj as BaseModelBase; + if (intbs != null) + { + intbs.CreateBy = GetJwtBy(); + intbs.CreateTime = DateTime.Now; + } + + return base.InsertAsync(insertObj); + } + /// <summary> + /// 閲嶅啓鎻掑叆 + /// </summary> + /// <param name="insertObj"></param> + /// <returns></returns> + public T EzInsertReturnEntity(T insertObj) + { + var intbs = insertObj as BaseModelBase; + if (intbs != null) + { + intbs.CreateBy = GetJwtBy(); + intbs.CreateTime = DateTime.Now; + } + return base.InsertReturnEntity(insertObj); + } + + /// <summary> + /// 寮傛鎻掑叆 + /// </summary> + /// <param name="insertObj"></param> + /// <returns></returns> + public Task<int> EzInsertReturnIdentityAsync(T insertObj) + { + + var intbs = insertObj as BaseModelBase; + if (intbs != null) + { + intbs.CreateBy = GetJwtBy(); + intbs.CreateTime = DateTime.Now; + } + return base.InsertReturnIdentityAsync(insertObj); + } + /// <summary> + /// 鑾峰彇鐢ㄦ埛濮撳悕鍜孖D + /// </summary> + /// <returns></returns> + private string GetJwtBy() + { + return (App.User?.FindFirstValue("UserID") ?? "") + "|" + (App.User?.FindFirstValue("NickName") ?? "绯荤粺鑷富澶勭悊"); + } + } + } diff --git a/cylsg/cylsg.Core/DbContext.cs b/cylsg/cylsg.Core/DbContext.cs new file mode 100644 index 0000000..324ec72 --- /dev/null +++ b/cylsg/cylsg.Core/DbContext.cs @@ -0,0 +1,22 @@ +锘縰sing Furion; +using SqlSugar; +using System.Collections.Generic; + +namespace cylsg.Core; + +/// <summary> +/// 鏁版嵁搴撲笂涓嬫枃瀵硅薄 +/// </summary> +public static class DbContext +{ + /// <summary> + /// SqlSugar 鏁版嵁搴撳疄渚� + /// </summary> + public static readonly SqlSugarScope Instance = new( + // 璇诲彇 appsettings.json 涓殑 ConnectionConfigs 閰嶇疆鑺傜偣 + App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs") + , db => + { + // 杩欓噷閰嶇疆鍏ㄥ眬浜嬩欢锛屾瘮濡傛嫤鎴墽琛� SQL + }); +} diff --git a/cylsg/cylsg.Core/DbCoreUntil.cs b/cylsg/cylsg.Core/DbCoreUntil.cs new file mode 100644 index 0000000..3bf6326 --- /dev/null +++ b/cylsg/cylsg.Core/DbCoreUntil.cs @@ -0,0 +1,34 @@ +锘縰sing cylsg.utility; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace cylsg.Core +{ + public class DbCoreUntil + { + /// 鑾峰彇闇�瑕佹洿鏂版垨鑰呮槸鍒涘缓鐨� 鏁版嵁搴撹〃妯″瀷List + /// </summary> + /// <typeparam name="T">缁ф壙琛ㄦ煇涓〃鐨勬墍鏈�</typeparam> + /// <param name="ModeProjectName"></param> + /// <param name="ModeNamespace"></param> + /// <param name="ConfigId"></param> + /// <returns></returns> + public static Type[] DbCodeFirstModes(string ModeProjectName, string ModeNamespace = null, string ConfigId = null, Type subClass = null, Type thisAttribute = null) + { + + +#nullable enable + Type[]? types = CommonHelper.GetAllAssembly().Where(x => x.FullName.Contains(ModeProjectName + ",")).FirstOrDefault()?.GetTypes().WhereIF(!string.IsNullOrEmpty(ModeNamespace), name => name.FullName.Contains(ModeNamespace + ".")).ToArray() + .WhereIF(subClass != null, x => x.IsSubclassOf(subClass)).ToArray() + .WhereIF(thisAttribute != null, x => x.GetCustomAttributes(thisAttribute, true).Length > 0).ToArray(); + + + return types; + + } + } +} diff --git a/cylsg/cylsg.Core/cylsg.Core.csproj b/cylsg/cylsg.Core/cylsg.Core.csproj new file mode 100644 index 0000000..8968473 --- /dev/null +++ b/cylsg/cylsg.Core/cylsg.Core.csproj @@ -0,0 +1,27 @@ +锘�<Project Sdk="Microsoft.NET.Sdk"> + + + + <PropertyGroup> + <TargetFramework>net8.0</TargetFramework> + <NoWarn>1701;1702;1591</NoWarn> + <DocumentationFile>cylsg.Core.xml</DocumentationFile> + </PropertyGroup> + + + <ItemGroup> + <None Remove="cylsg.Core.xml" /> + </ItemGroup> + + <ItemGroup> + <PackageReference Include="Furion.Extras.Authentication.JwtBearer" Version="4.9.5.3" /> + <PackageReference Include="Furion.Extras.ObjectMapper.Mapster" Version="4.9.5.3" /> + <PackageReference Include="Furion.Pure" Version="4.9.5.3" /> + <PackageReference Include="SqlSugarCore" Version="5.1.4.166" /> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="..\cylsg.utility\cylsg.utility.csproj" /> + </ItemGroup> + +</Project> diff --git a/cylsg/cylsg.Core/cylsg.Core.xml b/cylsg/cylsg.Core/cylsg.Core.xml new file mode 100644 index 0000000..0fe01a6 --- /dev/null +++ b/cylsg/cylsg.Core/cylsg.Core.xml @@ -0,0 +1,119 @@ +<?xml version="1.0"?> +<doc> + <assembly> + <name>cylsg.Core</name> + </assembly> + <members> + <member name="T:cylsg.Core.Attributes.CoderFirstAttribute"> + <summary> + /鏍囪鏄惁鏄痗odefirst + </summary> + </member> + <member name="T:cylsg.Core.BaseModelBase"> + <summary> + 鏈�鍩虹鐨勬ā鍨嬶紝鍒涘缓鏃堕棿鍒涘缓浜鸿褰� + </summary> + </member> + <member name="P:cylsg.Core.BaseModelBase.CreateTime"> + <summary> + 鍒涘缓鏃堕棿 + </summary> + </member> + <member name="P:cylsg.Core.BaseModelBase.CreateBy"> + <summary> + 鍒涘缓浜� + </summary> + </member> + <member name="P:cylsg.Core.BaseModelBase.UpDataTime"> + <summary> + 淇敼鏃堕棿 + </summary> + </member> + <member name="P:cylsg.Core.BaseModelBase.UpDataBy"> + <summary> + 淇敼浜� + </summary> + </member> + <member name="T:cylsg.Core.BaseModel"> + <summary> + 淇鍩虹妯″瀷锛屽寘鎷簡鍒犻櫎鏍囧織锛岀敓鏁堟爣蹇楋紝鎺掑簭锛屽拰浣胯兘 + </summary> + </member> + <member name="P:cylsg.Core.BaseModel.IsDeleted"> + <summary> + 鏄惁鍒犻櫎 + </summary> + </member> + <member name="P:cylsg.Core.BaseModel.IsEn"> + <summary> + 鏄惁鏈夋晥 + </summary> + </member> + <member name="P:cylsg.Core.BaseModel.Sort"> + <summary> + 鎺掑簭 + </summary> + </member> + <member name="P:cylsg.Core.BaseModel.Remake"> + <summary> + 鏍囨敞 + </summary> + </member> + <member name="P:cylsg.Core.BaseModel.TenantID"> + <summary> + 绉熸埛 + </summary> + </member> + <member name="T:cylsg.Core.BaseRepository`1"> + <summary> + 浠撳偍绫伙紝浣跨敤鏂瑰紡鍙渶瑕佺户鎵垮氨琛� + </summary> + <typeparam name="T"></typeparam> + </member> + <member name="M:cylsg.Core.BaseRepository`1.EzUpdateAsync(`0)"> + <summary> + 閲嶅啓鏇存柊鏂规硶 + </summary> + <param name="updateObj"></param> + <returns></returns> + </member> + <member name="M:cylsg.Core.BaseRepository`1.EzInsertAsync(`0)"> + <summary> + 寮傛鎻掑叆 + </summary> + <param name="insertObj"></param> + <returns></returns> + </member> + <member name="M:cylsg.Core.BaseRepository`1.EzInsertReturnEntity(`0)"> + <summary> + 閲嶅啓鎻掑叆 + </summary> + <param name="insertObj"></param> + <returns></returns> + </member> + <member name="M:cylsg.Core.BaseRepository`1.EzInsertReturnIdentityAsync(`0)"> + <summary> + 寮傛鎻掑叆 + </summary> + <param name="insertObj"></param> + <returns></returns> + </member> + <member name="M:cylsg.Core.BaseRepository`1.GetJwtBy"> + <summary> + 鑾峰彇鐢ㄦ埛濮撳悕鍜孖D + </summary> + <returns></returns> + </member> + <member name="T:cylsg.Core.DbContext"> + <summary> + 鏁版嵁搴撲笂涓嬫枃瀵硅薄 + </summary> + </member> + <member name="F:cylsg.Core.DbContext.Instance"> + <summary> + SqlSugar 鏁版嵁搴撳疄渚� + </summary> + </member> + <!-- Badly formed XML comment ignored for member "M:cylsg.Core.DbCoreUntil.DbCodeFirstModes(System.String,System.String,System.String,System.Type,System.Type)" --> + </members> +</doc> diff --git a/cylsg/cylsg.Model/UserModel/User.cs b/cylsg/cylsg.Model/UserModel/User.cs new file mode 100644 index 0000000..e6215eb --- /dev/null +++ b/cylsg/cylsg.Model/UserModel/User.cs @@ -0,0 +1,62 @@ +锘縰sing cylsg.Core; +using cylsg.Core.Attributes; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace cylsg.Model.UserModel +{ + /// <summary> + /// 鐢ㄦ埛妯″瀷 + /// </summary> + [Description("鐢ㄦ埛妯″瀷")] + [CoderFirst] + public class User:BaseModelBase + { + /// <summary> + /// 鐢ㄦ埛Id + /// </summary> + [SugarColumn(ColumnDescription = "鐢ㄦ埛ID", IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + + /// <summary> + /// 鐢佃瘽 + /// </summary> + [SugarColumn(ColumnDescription = "鐢佃瘽")] + public string Phone { get; set; } + + /// <summary> + /// 鍚嶇О + /// </summary> + [SugarColumn(ColumnDescription = "鍚嶇О",Length =100)] + public string name { get; set; } + /// <summary> + /// 鐢佃瘽鍙风爜 + /// </summary> + [SugarColumn(ColumnDescription = "鐢佃瘽鍙风爜", Length = 30)] + public string ItCode { get; set; } + + /// <summary> + /// 鏄电О + /// </summary> + [SugarColumn(ColumnDescription = "鐢ㄦ埛ID", Length = 100)] + public int Nickname { get; set; } + + + /// <summary> + /// 瀵嗙爜 + /// </summary> + [SugarColumn(ColumnDescription = "瀵嗙爜", Length = 100)] + public int PassWord { get; set; } + + /// <summary> + /// 澶村儚鍦板潃 + /// </summary> + [SugarColumn(ColumnDescription = "澶村儚鍦板潃")] + public int Avatar { get; set; } + } +} diff --git a/cylsg/cylsg.Model/cylsg.Model.csproj b/cylsg/cylsg.Model/cylsg.Model.csproj new file mode 100644 index 0000000..517ca3b --- /dev/null +++ b/cylsg/cylsg.Model/cylsg.Model.csproj @@ -0,0 +1,14 @@ +锘�<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>net8.0</TargetFramework> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + <GenerateDocumentationFile>True</GenerateDocumentationFile> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\cylsg.Core\cylsg.Core.csproj" /> + </ItemGroup> + +</Project> diff --git a/cylsg/cylsg.Web.Core/Handlers/JwtHandler.cs b/cylsg/cylsg.Web.Core/Handlers/JwtHandler.cs new file mode 100644 index 0000000..62ea9a7 --- /dev/null +++ b/cylsg/cylsg.Web.Core/Handlers/JwtHandler.cs @@ -0,0 +1,16 @@ +锘縰sing Furion.Authorization; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using System.Threading.Tasks; + +namespace cylsg.Web.Core; + +public class JwtHandler : AppAuthorizeHandler +{ + public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext) + { + // 杩欓噷鍐欐偍鐨勬巿鏉冨垽鏂�昏緫锛屾巿鏉冮�氳繃杩斿洖 true锛屽惁鍒欒繑鍥� false + + return Task.FromResult(true); + } +} diff --git a/cylsg/cylsg.Web.Core/Startup.cs b/cylsg/cylsg.Web.Core/Startup.cs new file mode 100644 index 0000000..d0e2936 --- /dev/null +++ b/cylsg/cylsg.Web.Core/Startup.cs @@ -0,0 +1,62 @@ +锘縰sing cylsg.Core; +using Furion; +using Furion.VirtualFileServer; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using SqlSugar; + +namespace cylsg.Web.Core; + +public class Startup : AppStartup +{ + public void ConfigureServices(IServiceCollection services) + { + services.AddConsoleFormatter(); + + services.AddJwt<JwtHandler>(); + + services.AddCorsAccessor(); + services.AddSingleton<ISqlSugarClient>(s => + + { + return DbContext.Instance; + } + ); + + services.AddControllersWithViews() + .AddInjectWithUnifyResult(); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseExceptionHandler("/Home/Error"); + app.UseHsts(); + } + app.UseHttpsRedirection(); + app.UseStaticFiles(); + + app.UseRouting(); + + app.UseCorsAccessor(); + + app.UseAuthentication(); + app.UseAuthorization(); + + app.UseInject(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + }); + } +} diff --git a/cylsg/cylsg.Web.Core/cylsg.Web.Core.csproj b/cylsg/cylsg.Web.Core/cylsg.Web.Core.csproj new file mode 100644 index 0000000..e2fcc82 --- /dev/null +++ b/cylsg/cylsg.Web.Core/cylsg.Web.Core.csproj @@ -0,0 +1,20 @@ +锘�<Project Sdk="Microsoft.NET.Sdk"> + + + + <PropertyGroup> + <TargetFramework>net8.0</TargetFramework> + <NoWarn>1701;1702;1591</NoWarn> + <DocumentationFile>cylsg.Web.Core.xml</DocumentationFile> + </PropertyGroup> + + + <ItemGroup> + <None Remove="cylsg.Web.Core.xml" /> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="..\cylsg.Application\cylsg.Application.csproj" /> + </ItemGroup> + +</Project> diff --git a/cylsg/cylsg.Web.Core/cylsg.Web.Core.xml b/cylsg/cylsg.Web.Core/cylsg.Web.Core.xml new file mode 100644 index 0000000..b670981 --- /dev/null +++ b/cylsg/cylsg.Web.Core/cylsg.Web.Core.xml @@ -0,0 +1,8 @@ +<?xml version="1.0"?> +<doc> + <assembly> + <name>cylsg.Web.Core</name> + </assembly> + <members> + </members> +</doc> diff --git a/cylsg/cylsg.Web.Entry/Controllers/HomeController.cs b/cylsg/cylsg.Web.Entry/Controllers/HomeController.cs new file mode 100644 index 0000000..afa4191 --- /dev/null +++ b/cylsg/cylsg.Web.Entry/Controllers/HomeController.cs @@ -0,0 +1,23 @@ +锘縰sing cylsg.Application; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace cylsg.Web.Entry.Controllers; + +[AllowAnonymous] +public class HomeController : Controller +{ + private readonly ISystemService _systemService; + + public HomeController(ISystemService systemService) + { + _systemService = systemService; + } + + public IActionResult Index() + { + ViewBag.Description = _systemService.GetDescription(); + + return View(); + } +} diff --git a/cylsg/cylsg.Web.Entry/Program.cs b/cylsg/cylsg.Web.Entry/Program.cs new file mode 100644 index 0000000..611ed5a --- /dev/null +++ b/cylsg/cylsg.Web.Entry/Program.cs @@ -0,0 +1 @@ +Serve.Run(RunOptions.Default.WithArgs(args)); \ No newline at end of file diff --git a/cylsg/cylsg.Web.Entry/Properties/launchSettings.json b/cylsg/cylsg.Web.Entry/Properties/launchSettings.json new file mode 100644 index 0000000..025cb44 --- /dev/null +++ b/cylsg/cylsg.Web.Entry/Properties/launchSettings.json @@ -0,0 +1,28 @@ +锘縶 + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:58595", + "sslPort": 44326 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "cylsg.Web.Entry": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cylsg/cylsg.Web.Entry/SingleFilePublish.cs b/cylsg/cylsg.Web.Entry/SingleFilePublish.cs new file mode 100644 index 0000000..4e0f945 --- /dev/null +++ b/cylsg/cylsg.Web.Entry/SingleFilePublish.cs @@ -0,0 +1,22 @@ +锘縰sing Furion; +using System.Reflection; + +namespace cylsg.Web.Entry; + +public class SingleFilePublish : ISingleFilePublish +{ + public Assembly[] IncludeAssemblies() + { + return Array.Empty<Assembly>(); + } + + public string[] IncludeAssemblyNames() + { + return new[] + { + "cylsg.Application", + "cylsg.Core", + "cylsg.Web.Core" + }; + } +} \ No newline at end of file diff --git a/cylsg/cylsg.Web.Entry/Views/Home/Index.cshtml b/cylsg/cylsg.Web.Entry/Views/Home/Index.cshtml new file mode 100644 index 0000000..7f7019d --- /dev/null +++ b/cylsg/cylsg.Web.Entry/Views/Home/Index.cshtml @@ -0,0 +1,9 @@ +锘緻{ + ViewData["Title"] = ViewBag.Description; +} + +<div style="text-align:center;margin-top:50px;"> + + <p>@ViewBag.Description</p> + <p><a href="/api">API 鎺ュ彛</a> +</div> \ No newline at end of file diff --git a/cylsg/cylsg.Web.Entry/Views/Shared/_Layout.cshtml b/cylsg/cylsg.Web.Entry/Views/Shared/_Layout.cshtml new file mode 100644 index 0000000..f5f94a0 --- /dev/null +++ b/cylsg/cylsg.Web.Entry/Views/Shared/_Layout.cshtml @@ -0,0 +1,11 @@ +锘�<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>@ViewData["Title"] - Furion</title> +</head> +<body> + @RenderBody() +</body> +</html> \ No newline at end of file diff --git a/cylsg/cylsg.Web.Entry/Views/_ViewImports.cshtml b/cylsg/cylsg.Web.Entry/Views/_ViewImports.cshtml new file mode 100644 index 0000000..d1799e5 --- /dev/null +++ b/cylsg/cylsg.Web.Entry/Views/_ViewImports.cshtml @@ -0,0 +1,2 @@ +锘緻using cylsg.Web.Entry +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers \ No newline at end of file diff --git a/cylsg/cylsg.Web.Entry/Views/_ViewStart.cshtml b/cylsg/cylsg.Web.Entry/Views/_ViewStart.cshtml new file mode 100644 index 0000000..1af6e49 --- /dev/null +++ b/cylsg/cylsg.Web.Entry/Views/_ViewStart.cshtml @@ -0,0 +1,3 @@ +锘緻{ + Layout = "_Layout"; +} \ No newline at end of file diff --git a/cylsg/cylsg.Web.Entry/appsettings.Development.json b/cylsg/cylsg.Web.Entry/appsettings.Development.json new file mode 100644 index 0000000..5f187ae --- /dev/null +++ b/cylsg/cylsg.Web.Entry/appsettings.Development.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://gitee.com/dotnetchina/Furion/raw/v4/schemas/v4/furion-schema.json", + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Microsoft.EntityFrameworkCore": "Information" + } + } +} \ No newline at end of file diff --git a/cylsg/cylsg.Web.Entry/appsettings.json b/cylsg/cylsg.Web.Entry/appsettings.json new file mode 100644 index 0000000..282b349 --- /dev/null +++ b/cylsg/cylsg.Web.Entry/appsettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://gitee.com/dotnetchina/Furion/raw/v4/schemas/v4/furion-schema.json", + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Microsoft.EntityFrameworkCore": "Information" + } + }, + "AllowedHosts": "*", + "ConnectionConfigs": [ + { + //"ConnectionString": "Data Source=./Furion.db", + //"DbType": "Sqlite", + //"IsAutoCloseConnection": true + + + "ConnectionString": "Server=MS-FSEUTNLCXFDB\\SQLEXPRESS;Database=CyLsgDb; MultipleActiveResultSets=true;pooling=true;min pool size=5;max pool size=32767;connect timeout=20;Encrypt=True;TrustServerCertificate=True;integrated security=True;", + "DbType": "SqlServer", // "SqlServer" ,mysql, + "IsAutoCloseConnection": true + } + ] +} \ No newline at end of file diff --git a/cylsg/cylsg.Web.Entry/cylsg.Web.Entry.csproj b/cylsg/cylsg.Web.Entry/cylsg.Web.Entry.csproj new file mode 100644 index 0000000..f8a41c3 --- /dev/null +++ b/cylsg/cylsg.Web.Entry/cylsg.Web.Entry.csproj @@ -0,0 +1,17 @@ +锘�<Project Sdk="Microsoft.NET.Sdk.Web"> + + + + <PropertyGroup> + <TargetFramework>net8.0</TargetFramework> + <ImplicitUsings>enable</ImplicitUsings> + <SatelliteResourceLanguages>en-US</SatelliteResourceLanguages> + <PublishReadyToRunComposite>true</PublishReadyToRunComposite> + </PropertyGroup> + + + <ItemGroup> + <ProjectReference Include="..\cylsg.Web.Core\cylsg.Web.Core.csproj" /> + </ItemGroup> + +</Project> diff --git a/cylsg/cylsg.Web.Entry/cylsg.Web.Entry.csproj.user b/cylsg/cylsg.Web.Entry/cylsg.Web.Entry.csproj.user new file mode 100644 index 0000000..cb66639 --- /dev/null +++ b/cylsg/cylsg.Web.Entry/cylsg.Web.Entry.csproj.user @@ -0,0 +1,9 @@ +锘�<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <DebuggerFlavor>ProjectDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup> + <ActiveDebugProfile>cylsg.Web.Entry</ActiveDebugProfile> + </PropertyGroup> +</Project> \ No newline at end of file diff --git a/cylsg/cylsg.Web.Entry/wwwroot/images/logo.png b/cylsg/cylsg.Web.Entry/wwwroot/images/logo.png new file mode 100644 index 0000000..166b801 --- /dev/null +++ b/cylsg/cylsg.Web.Entry/wwwroot/images/logo.png Binary files differ diff --git a/cylsg/cylsg.sln b/cylsg/cylsg.sln new file mode 100644 index 0000000..71542db --- /dev/null +++ b/cylsg/cylsg.sln @@ -0,0 +1,55 @@ +锘� +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32519.111 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "cylsg.Application", "cylsg.Application\cylsg.Application.csproj", "{AB699EE9-43A8-46F2-A855-04A26DE63372}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "cylsg.Web.Core", "cylsg.Web.Core\cylsg.Web.Core.csproj", "{9D14BB78-DA2A-4040-B9DB-5A515B599181}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "cylsg.Core", "cylsg.Core\cylsg.Core.csproj", "{4FB30091-15C7-4FD9-AB7D-266814F360F5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "cylsg.Web.Entry", "cylsg.Web.Entry\cylsg.Web.Entry.csproj", "{9826E365-EEE9-4721-A738-B02AB64D47E5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "cylsg.Model", "cylsg.Model\cylsg.Model.csproj", "{09E3AFC0-0975-4842-891F-9B5C78E12458}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "cylsg.utility", "cylsg.utility\cylsg.utility.csproj", "{5ED2C481-2D74-43BC-ABAF-1455A052FAA4}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AB699EE9-43A8-46F2-A855-04A26DE63372}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB699EE9-43A8-46F2-A855-04A26DE63372}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB699EE9-43A8-46F2-A855-04A26DE63372}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB699EE9-43A8-46F2-A855-04A26DE63372}.Release|Any CPU.Build.0 = Release|Any CPU + {9D14BB78-DA2A-4040-B9DB-5A515B599181}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9D14BB78-DA2A-4040-B9DB-5A515B599181}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9D14BB78-DA2A-4040-B9DB-5A515B599181}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9D14BB78-DA2A-4040-B9DB-5A515B599181}.Release|Any CPU.Build.0 = Release|Any CPU + {4FB30091-15C7-4FD9-AB7D-266814F360F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4FB30091-15C7-4FD9-AB7D-266814F360F5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4FB30091-15C7-4FD9-AB7D-266814F360F5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4FB30091-15C7-4FD9-AB7D-266814F360F5}.Release|Any CPU.Build.0 = Release|Any CPU + {9826E365-EEE9-4721-A738-B02AB64D47E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9826E365-EEE9-4721-A738-B02AB64D47E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9826E365-EEE9-4721-A738-B02AB64D47E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9826E365-EEE9-4721-A738-B02AB64D47E5}.Release|Any CPU.Build.0 = Release|Any CPU + {09E3AFC0-0975-4842-891F-9B5C78E12458}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {09E3AFC0-0975-4842-891F-9B5C78E12458}.Debug|Any CPU.Build.0 = Debug|Any CPU + {09E3AFC0-0975-4842-891F-9B5C78E12458}.Release|Any CPU.ActiveCfg = Release|Any CPU + {09E3AFC0-0975-4842-891F-9B5C78E12458}.Release|Any CPU.Build.0 = Release|Any CPU + {5ED2C481-2D74-43BC-ABAF-1455A052FAA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5ED2C481-2D74-43BC-ABAF-1455A052FAA4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5ED2C481-2D74-43BC-ABAF-1455A052FAA4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5ED2C481-2D74-43BC-ABAF-1455A052FAA4}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B2073C2C-0FD3-452B-8047-8134D68E12CE} + EndGlobalSection +EndGlobal diff --git a/cylsg/cylsg.utility/CommonHelper.cs b/cylsg/cylsg.utility/CommonHelper.cs new file mode 100644 index 0000000..978d033 --- /dev/null +++ b/cylsg/cylsg.utility/CommonHelper.cs @@ -0,0 +1,850 @@ +锘縰sing System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Runtime.Loader; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace cylsg.utility +{ + /// <summary> + /// 閫氱敤甯姪绫� + /// </summary> + public static class CommonHelper + { + + #region 鍒ゆ柇瀛楃涓叉槸鍚︿负鎵嬫満鍙风爜 + /// <summary> + /// 鍒ゆ柇瀛楃涓叉槸鍚︿负鎵嬫満鍙风爜 + /// </summary> + /// <param name="mobilePhoneNumber"></param> + /// <returns></returns> + public static bool IsMobile(string mobilePhoneNumber) + { + if (mobilePhoneNumber.Length < 11) + { + return false; + } + + //鐢典俊鎵嬫満鍙风爜姝e垯 + string dianxin = @"^1[345789][01379]\d{8}$"; + Regex regexDx = new Regex(dianxin); + //鑱旈�氭墜鏈哄彿鐮佹鍒� + string liantong = @"^1[345678][01256]\d{8}$"; + Regex regexLt = new Regex(liantong); + //绉诲姩鎵嬫満鍙风爜姝e垯 + string yidong = @"^1[345789][0123456789]\d{8}$"; + Regex regexYd = new Regex(yidong); + if (regexDx.IsMatch(mobilePhoneNumber) || regexLt.IsMatch(mobilePhoneNumber) || regexYd.IsMatch(mobilePhoneNumber)) + { + return true; + } + else + { + return false; + } + } + #endregion + + #region 妫�娴嬫槸鍚︾鍚坋mail鏍煎紡 + + /// <summary> + /// 妫�娴嬫槸鍚︾鍚坋mail鏍煎紡 + /// </summary> + /// <param name="strEmail">瑕佸垽鏂殑email瀛楃涓�</param> + /// <returns>鍒ゆ柇缁撴灉</returns> + public static bool IsValidEmail(string strEmail) + { + return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]"); + } + + public static bool IsValidDoEmail(string strEmail) + { + return Regex.IsMatch(strEmail, + @"^@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); + } + #endregion + + #region 妫�娴嬫槸鍚︽槸姝g‘鐨刄rl + /// <summary> + /// 妫�娴嬫槸鍚︽槸姝g‘鐨刄rl + /// </summary> + /// <param name="strUrl">瑕侀獙璇佺殑Url</param> + /// <returns>鍒ゆ柇缁撴灉</returns> + public static bool IsUrl(string strUrl) + { + return Regex.IsMatch(strUrl, + @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$"); + } + + + #endregion + + #region string 杞琲nt鏁扮粍 + + public static int[] StringToIntArray(string str) + { + try + { + if (string.IsNullOrEmpty(str)) return new int[0]; + if (str.EndsWith(",")) + { + str = str.Remove(str.Length - 1, 1); + } + var idstrarr = str.Split(','); + var idintarr = new int[idstrarr.Length]; + + for (int i = 0; i < idstrarr.Length; i++) + { + idintarr[i] = Convert.ToInt32(idstrarr[i]); + } + return idintarr; + } + catch + { + return new int[0]; + } + } + #endregion + + #region String杞暟缁� + public static string[] StringToStringArray(string str) + { + try + { + if (string.IsNullOrEmpty(str)) return new string[0]; + if (str.EndsWith(",")) str = str.Remove(str.Length - 1, 1); + return str.Split(','); + } + catch + { + return new string[0]; + } + } + #endregion + + #region String鏁扮粍杞琁nt鏁扮粍 + public static int[] StringArrAyToIntArray(string[] str) + { + try + { + int[] iNums = Array.ConvertAll(str, s => int.Parse(s)); + return iNums; + } + catch + { + return new int[0]; + } + } + #endregion + + #region string杞珿uid鏁扮粍 + + public static Guid[] StringToGuidArray(string str) + { + try + { + if (string.IsNullOrEmpty(str)) return new Guid[0]; + if (str.EndsWith(",")) str = str.Remove(str.Length - 1, 1); + var strarr = str.Split(','); + Guid[] guids = new Guid[strarr.Length]; + for (int index = 0; index < strarr.Length; index++) + { + guids[index] = Guid.Parse(strarr[index]); + } + return guids; + } + catch + { + return new Guid[0]; + } + } + #endregion + + #region 杞琈D5 + /// <summary> + /// 杞琈D5 + /// </summary> + /// <param name="str"></param> + /// <returns></returns> + public static string ToMd5(string str) + { + MD5 md5 = MD5.Create(); + // 灏嗗瓧绗︿覆杞崲鎴愬瓧鑺傛暟缁� + byte[] byteOld = Encoding.UTF8.GetBytes(str); + // 璋冪敤鍔犲瘑鏂规硶 + byte[] byteNew = md5.ComputeHash(byteOld); + // 灏嗗姞瀵嗙粨鏋滆浆鎹负瀛楃涓� + StringBuilder sb = new StringBuilder(); + foreach (byte b in byteNew) + { + // 灏嗗瓧鑺傝浆鎹㈡垚16杩涘埗琛ㄧず鐨勫瓧绗︿覆锛� + sb.Append(b.ToString("x2")); + } + // 杩斿洖鍔犲瘑鐨勫瓧绗︿覆 + return sb.ToString(); + } + #endregion + + #region 鑾峰彇32浣峬d5鍔犲瘑 + /// <summary> + /// 閫氳繃鍒涘缓鍝堝笇瀛楃涓查�傜敤浜庝换浣� MD5 鍝堝笇鍑芥暟 锛堝湪浠讳綍骞冲彴锛� 涓婂垱寤� 32 涓瓧绗︾殑鍗佸叚杩涘埗鏍煎紡鍝堝笇瀛楃涓� + /// </summary> + /// <param name="source"></param> + /// <returns>32浣峬d5鍔犲瘑瀛楃涓�</returns> + public static string Md5For32(string source) + { + using (MD5 md5Hash = MD5.Create()) + { + byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source)); + StringBuilder sBuilder = new StringBuilder(); + for (int i = 0; i < data.Length; i++) + { + sBuilder.Append(data[i].ToString("x2")); + } + + string hash = sBuilder.ToString(); + return hash.ToUpper(); + } + } + #endregion + + #region 鑾峰彇16浣峬d5鍔犲瘑 + /// <summary> + /// 鑾峰彇16浣峬d5鍔犲瘑 + /// </summary> + /// <param name="source"></param> + /// <returns>16浣峬d5鍔犲瘑瀛楃涓�</returns> + public static string Md5For16(string source) + { + using (MD5 md5Hash = MD5.Create()) + { + byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source)); + //杞崲鎴愬瓧绗︿覆锛屽苟鍙�9鍒�25浣� + string sBuilder = BitConverter.ToString(data, 4, 8); + //BitConverter杞崲鍑烘潵鐨勫瓧绗︿覆浼氬湪姣忎釜瀛楃涓棿浜х敓涓�涓垎闅旂锛岄渶瑕佸幓闄ゆ帀 + sBuilder = sBuilder.Replace("-", ""); + return sBuilder.ToUpper(); + } + } + + #endregion + + #region 杩斿洖褰撳墠鐨勬绉掓椂闂存埑 + + /// <summary> + /// 杩斿洖褰撳墠鐨勬绉掓椂闂存埑 + /// </summary> + public static string Msectime() + { + long timeTicks = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000; + return timeTicks.ToString(); + } + + + #endregion + + + + #region 鍓╀綑澶氫箙鏃堕棿鏂囧瓧鎻忚堪 + /// <summary> + /// 鍓╀綑澶氫箙鏃堕棿 + /// </summary> + /// <param name="remainingTime"></param> + /// <returns>鏂囧瓧鎻忚堪</returns> + public static string GetRemainingTime(DateTime remainingTime) + { + TimeSpan timeSpan = remainingTime - DateTime.Now; + var day = timeSpan.Days; + var hours = timeSpan.Hours; + var minute = timeSpan.Minutes; + var seconds = timeSpan.Seconds; + if (day > 0) + { + return day + "澶�" + hours + "灏忔椂" + minute + "鍒�" + seconds + "绉�"; + } + else + { + if (hours > 0) + { + return hours + "灏忔椂" + minute + "鍒�" + seconds + "绉�"; + } + else + { + return minute + "鍒�" + seconds + "绉�"; + } + } + } + + #endregion + + #region 鍓╀綑澶氫箙鏃堕棿杩斿洖鏃堕棿绫诲瀷 + /// <summary> + /// 鍓╀綑澶氫箙鏃堕棿 + /// </summary> + /// <param name="remainingTime"></param> + /// <returns>杩斿洖鏃堕棿绫诲瀷</returns> + public static void GetBackTime(DateTime remainingTime, out int day, out int hours, out int minute, out int seconds) + { + TimeSpan timeSpan = remainingTime - DateTime.Now; + day = timeSpan.Days; + hours = timeSpan.Hours; + minute = timeSpan.Minutes; + seconds = timeSpan.Seconds; + } + + #endregion + + #region 璁$畻鏃堕棿鎴冲墿浣欏涔呮椂闂� + + /// <summary> + /// 璁$畻鏃堕棿鎴冲墿浣欏涔呮椂闂� + /// </summary> + /// <param name="postTime">鎻愪氦鏃堕棿(瑕佹槸浠ュ墠鐨勬椂闂�)</param> + /// <returns></returns> + public static string TimeAgo(DateTime postTime) + { + //褰撳墠鏃堕棿鐨勬椂闂存埑 + var nowtimes = ConvertTicks(DateTime.Now); + //鎻愪氦鐨勬椂闂存埑 + var posttimes = ConvertTicks(postTime); + //鐩稿樊鏃堕棿鎴� + var counttime = nowtimes - posttimes; + + //杩涜鏃堕棿杞崲 + if (counttime <= 60) + { + return "鍒氬垰"; + } + else if (counttime > 60 && counttime <= 120) + { + return "1鍒嗛挓鍓�"; + } + else if (counttime > 120 && counttime <= 180) + { + return "2鍒嗛挓鍓�"; + } + else if (counttime > 180 && counttime < 3600) + { + return Convert.ToInt32(counttime / 60) + "鍒嗛挓鍓�"; + } + else if (counttime >= 3600 && counttime < 3600 * 24) + { + return Convert.ToInt32(counttime / 3600) + "灏忔椂鍓�"; + } + else if (counttime >= 3600 * 24 && counttime < 3600 * 24 * 2) + { + return "鏄ㄥぉ"; + } + else if (counttime >= 3600 * 24 * 2 && counttime < 3600 * 24 * 3) + { + return "鍓嶅ぉ"; + } + else if (counttime >= 3600 * 24 * 3 && counttime <= 3600 * 24 * 7) + { + return Convert.ToInt32(counttime / (3600 * 24)) + "澶╁墠"; + } + else if (counttime >= 3600 * 24 * 7 && counttime <= 3600 * 24 * 30) + { + return Convert.ToInt32(counttime / (3600 * 24 * 7)) + "鍛ㄥ墠"; + } + else if (counttime >= 3600 * 24 * 30 && counttime <= 3600 * 24 * 365) + { + return Convert.ToInt32(counttime / (3600 * 24 * 30)) + "涓湀鍓�"; + } + else if (counttime >= 3600 * 24 * 365) + { + return Convert.ToInt32(counttime / (3600 * 24 * 365)) + "骞村墠"; + } + else + { + return ""; + } + } + + /// <summary> + /// 鏃堕棿杞崲涓虹鐨勬椂闂存埑 + /// </summary> + /// <param name="time"></param> + /// <returns></returns> + private static long ConvertTicks(DateTime time) + { + long currentTicks = time.Ticks; + DateTime dtFrom = new DateTime(1970, 1, 1, 0, 0, 0, 0); + long currentMillis = (currentTicks - dtFrom.Ticks) / 10000000; //杞崲涓虹涓篢icks/10000000锛岃浆鎹负姣Ticks/10000 + return currentMillis; + } + + #endregion + + #region 娓呴櫎HTML涓寚瀹氭牱寮� + /// <summary> + /// 娓呴櫎HTML涓寚瀹氭牱寮� + /// </summary> + /// <param name="content"></param> + /// <param name="rule"></param> + /// <returns></returns> + public static string ClearHtml(string content, string[] rule) + { + if (!rule.Any()) + { + return content; + } + + foreach (var item in rule) + { + content = Regex.Replace(content, "/" + item + @"\s*=\s*\d+\s*/i", ""); + content = Regex.Replace(content, "/" + item + @"\s*=\s*.+?[""]/i", ""); + content = Regex.Replace(content, "/" + item + @"\s*:\s*\d+\s*px\s*;?/i", ""); + } + return content; + } + #endregion + + #region list闅忔満鎺掑簭鏂规硶 + /// <summary> + /// list闅忔満鎺掑簭鏂规硶 + /// </summary> + /// <typeparam name="T"></typeparam> + /// <param name="ListT"></param> + /// <returns></returns> + public static List<T> RandomSortList<T>(List<T> ListT) + { + Random random = new Random(); + List<T> newList = new List<T>(); + foreach (T item in ListT) + { + newList.Insert(random.Next(newList.Count + 1), item); + } + return newList; + } + #endregion + + + + #region 鎴墠鍚庡瓧绗�(涓�) + ///<summary> + /// 鎴墠鍚庡瓧绗�(涓�) + ///</summary> + ///<param name="val">鍘熷瓧绗︿覆</param> + ///<param name="str">瑕佹埅鎺夌殑瀛楃涓�</param> + ///<param name="all">鏄惁璐┆</param> + ///<returns></returns> + public static string GetCaptureInterceptedText(string val, string str, bool all = false) + { + return Regex.Replace(val, @"(^(" + str + ")" + (all ? "*" : "") + "|(" + str + ")" + (all ? "*" : "") + "$)", ""); + } + #endregion + + #region 瀵嗙爜鍔犲瘑鏂规硶 + /// <summary> + /// 瀵嗙爜鍔犲瘑鏂规硶 + /// </summary> + /// <param name="password">瑕佸姞瀵嗙殑瀛楃涓�</param> + /// <param name="createTime">鏃堕棿缁勫悎</param> + /// <returns></returns> + public static string EnPassword(string password, DateTime createTime) + { + var dtStr = createTime.ToString("yyyyMMddHHmmss"); + var md5 = Md5For32(password); + var enPwd = Md5For32(md5 + dtStr); + return enPwd; + } + #endregion + + #region 鑾峰彇鐜板湪鏄槦鏈熷嚑 + /// <summary> + /// 鑾峰彇鐜板湪鏄槦鏈熷嚑 + /// </summary> + /// <returns></returns> + public static string GetWeek() + { + string week = string.Empty; + switch (DateTime.Now.DayOfWeek) + { + case DayOfWeek.Monday: + week = "鍛ㄤ竴"; + break; + case DayOfWeek.Tuesday: + week = "鍛ㄤ簩"; + break; + case DayOfWeek.Wednesday: + week = "鍛ㄤ笁"; + break; + case DayOfWeek.Thursday: + week = "鍛ㄥ洓"; + break; + case DayOfWeek.Friday: + week = "鍛ㄤ簲"; + break; + case DayOfWeek.Saturday: + week = "鍛ㄥ叚"; + break; + case DayOfWeek.Sunday: + week = "鍛ㄦ棩"; + break; + default: + week = "N/A"; + break; + } + return week; + } + + #endregion + + #region UrlEncode (URL缂栫爜) + /// <summary> + /// UrlEncode (URL缂栫爜) + /// </summary> + /// <param name="str"></param> + /// <returns></returns> + public static string UrlEncode(string str) + { + StringBuilder sb = new StringBuilder(); + byte[] byStr = Encoding.UTF8.GetBytes(str); //榛樿鏄疭ystem.Text.Encoding.Default.GetBytes(str) + for (int i = 0; i < byStr.Length; i++) + { + sb.Append(@"%" + Convert.ToString(byStr[i], 16)); + } + + return sb.ToString(); + } + + #endregion + + #region 鑾峰彇10浣嶆椂闂存埑 + /// <summary> + /// 鑾峰彇10浣嶆椂闂存埑 + /// </summary> + /// <returns></returns> + public static long GetTimeStampByTotalSeconds() + { + TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0); + return Convert.ToInt64(ts.TotalSeconds); + } + #endregion + + #region 鑾峰彇13浣嶆椂闂存埑 + /// <summary> + /// 鑾峰彇13浣嶆椂闂存埑 + /// </summary> + /// <returns></returns> + public static long GetTimeStampByTotalMilliseconds() + { + TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); + return Convert.ToInt64(ts.TotalMilliseconds); + } + + /// <summary> + /// 鑾峰彇鏃堕棿鎴� + /// </summary> + /// <param name="dt"></param> + /// <returns></returns> + public static int GetDateTimeStamp(DateTime dt) + { + DateTime dateStart = new DateTime(1970, 1, 1, 0, 0, 0); + int timeStamp = Convert.ToInt32((dt.ToUniversalTime() - dateStart).TotalSeconds); + return timeStamp; + } + + #endregion + + #region 鑾峰彇闅忔満瀛楃涓� + /// <summary> + /// 鑾峰彇闅忔満瀛楃涓� + /// </summary> + /// <returns></returns> + public static string GetSerialNumber() + { + var str = string.Empty; + Random rand = new Random(); + var charsStr2 = new[] { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' }; + var charsLen2 = charsStr2.Length - 1; + // shuffle($chars); + str = ""; + for (int i = 0; i < 16; i++) + { + str += charsStr2[rand.Next(0, charsLen2)]; + } + return str; + } + + #endregion + + #region Sha1绛惧悕 + /// <summary> + /// Sha1绛惧悕 + /// </summary> + /// <param name="str">鍐呭</param> + /// <param name="encoding">缂栫爜</param> + /// <returns></returns> + public static string Sha1Signature(string str, Encoding encoding = null) + { + if (encoding == null) encoding = Encoding.UTF8; + var buffer = encoding.GetBytes(str); + var data = SHA1.Create().ComputeHash(buffer); + StringBuilder sub = new StringBuilder(); + foreach (var t in data) + { + sub.Append(t.ToString("x2")); + } + + return sub.ToString(); + } + #endregion + + /// <summary> + /// 绮剧‘璁$畻base64瀛楃涓叉枃浠跺ぇ灏忥紙鍗曚綅锛欱锛� + /// param base64String + /// return double 瀛楄妭澶у皬 + /// </summary> + /// <param name="base64String"></param> + /// <returns></returns> + public static double Base64FileSize(string base64String) + { + //妫�娴嬫槸鍚﹀惈鏈塨ase64,鏂囦欢澶�) + if (base64String.LastIndexOf(",", StringComparison.Ordinal) > -1) + { + base64String = base64String[(base64String.LastIndexOf(",", StringComparison.Ordinal) + 1)..]; + } + //鑾峰彇base64瀛楃涓查暱搴�(涓嶅惈data:audio/wav;base64,鏂囦欢澶�) + var size0 = base64String.Length; + if (size0 <= 10) return size0 - (double)size0 / 8 * 2; + //鑾峰彇瀛楃涓茬殑灏惧反鐨勬渶鍚�10涓瓧绗︼紝鐢ㄤ簬鍒ゆ柇灏惧反鏄惁鏈夌瓑鍙凤紝姝e父鐢熸垚鐨刡ase64鏂囦欢'绛夊彿'涓嶄細瓒呰繃4涓� + var tail = base64String[(size0 - 10)..]; + //鎵惧埌绛夊彿锛屾妸绛夊彿涔熷幓鎺�,(绛夊彿鍏跺疄鏄┖鐨勬剰鎬�,涓嶈兘绠楀湪鏂囦欢澶у皬閲岄潰) + int equalIndex = tail.IndexOf("=", StringComparison.Ordinal); + if (equalIndex > 0) + { + size0 = size0 - (10 - equalIndex); + } + //璁$畻鍚庡緱鍒扮殑鏂囦欢娴佸ぇ灏忥紝鍗曚綅涓哄瓧鑺� + return size0 - (double)size0 / 8 * 2; + } + + /// <summary> + /// 鍒ゆ柇鏂囦欢澶у皬 + /// </summary> + /// <param name="base64"></param> + /// <param name="size"></param> + /// <param name="unit"></param> + /// <returns></returns> + public static bool CheckBase64Size(string base64, int size, string unit = "M") + { + // 涓婁紶鏂囦欢鐨勫ぇ灏�, 鍗曚綅涓哄瓧鑺�. + var len = Base64FileSize(base64); + // 鍑嗗鎺ユ敹鎹㈢畻鍚庢枃浠跺ぇ灏忕殑瀹瑰櫒 + double fileSize = unit.ToUpperInvariant() switch + { + "B" => len, + "K" => (double)len / 1024, + "M" => (double)len / 1048576, + "G" => (double)len / 1073741824, + _ => 0 + }; + // 濡傛灉涓婁紶鏂囦欢澶т簬闄愬畾鐨勫閲� + return !(fileSize > size); + } + + /// <summary> + /// 10浣嶆椂闂存埑 杞寲 + /// </summary> + /// <param name="time"></param> + /// <returns></returns> + public static long ConvertDateTimeToInt(DateTime time) + { + DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0)); + long t = (time.Ticks - startTime.Ticks) / 10000000; //闄�10000000璋冩暣涓�10浣� + return t; + } + + #region 鍙嶅皠鐩稿叧 + private static List<Assembly>? _allAssemblies = null; + /// <summary> + /// 鑾峰彇鎵�鏈夌▼搴忕洰褰曚笅鍜屽父鐢ㄧ殑绋嬪簭闆� 鍖呮嫭涓�浜涚郴缁熷紩鐢ㄧ▼搴忛泦 + /// </summary> + /// <returns> 褰撳墠宸ョ▼涓嬬殑绋嬪簭闆�</returns> + public static List<Assembly> GetAllAssembly() + { + + + if (_allAssemblies == null) + { + _allAssemblies = new List<Assembly>(); + string? path = null; + string singlefile = null; + try + { + path = Assembly.GetEntryAssembly()?.Location; + } + catch { } + if (string.IsNullOrEmpty(path)) + { + singlefile = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; + path = Path.GetDirectoryName(singlefile); + } + if (string.IsNullOrEmpty(path)) + + throw new Exception("鑾峰彇绋嬪簭鐩綍鍑洪敊"); + var dir = new DirectoryInfo(Path.GetDirectoryName(path) ?? ""); + + var dlls = dir.GetFiles("*.dll", SearchOption.TopDirectoryOnly); + string[] systemdll = new string[] + { + "Microsoft.", + "System.", + "Swashbuckle.", + "ICSharpCode", + "Newtonsoft.", + "Oracle.", + "Pomelo.", + "SQLitePCLRaw.", + "Aliyun.OSS", + "BouncyCastle.", + "FreeSql.", + "Google.Protobuf.dll", + "Humanizer.dll", + "IdleBus.dll", + "K4os.", + "MySql.Data.", + "Npgsql.", + "NPOI.", + "netstandard", + "MySqlConnector", + "VueCliMiddleware" + }; + + var filtered = dlls.Where(x => systemdll.Any(y => x.Name.StartsWith(y)) == false); + foreach (var dll in filtered) + { + try + { + AssemblyLoadContext.Default.LoadFromAssemblyPath(dll.FullName); + } + catch + { + } + } + var dlllist = AssemblyLoadContext.Default.Assemblies.Where(x => systemdll.Any(y => x.FullName.StartsWith(y)) == false).ToList(); + _allAssemblies.AddRange(dlllist); + } + return _allAssemblies; + } + #endregion + + #region 鏋氫妇鑾峰彇鎵�鏈夐」 + /// <summary> + /// 鑾峰彇鏋氫妇鐨勬墍鏈夐」 + /// </summary> + /// <typeparam name="T"></typeparam> + /// <returns></returns> + public static List<MenmItem> GetEnumItemsWithAttributes<T>() where T : Enum + { + var result = new List<MenmItem>(); + + foreach (var value in Enum.GetValues(typeof(T))) + { + var member = typeof(T).GetMember(value.ToString())[0]; + var descriptionAttribute = member.GetCustomAttribute<DescriptionAttribute>(); + + var item = new MenmItem + { + Key = value.ToString(), + Value = (int)value, // 鎴栬�呯洿鎺ヤ娇鐢� value.ToString() 濡傛灉涓嶉渶瑕佽浆鎹负鏁存暟瀛楃涓� + Description = descriptionAttribute?.Description ?? string.Empty + }; + + result.Add(item); + } + + return result; + } + + /// <summary> + /// 鑾峰彇鏋氫妇鎵�鏈夌殑椤癸紝杩斿洖鍚嶇О 鍊� 鍜孌escription 鎻忚堪 + /// </summary> + /// <param name="enumType"></param> + /// <returns></returns> + /// <exception cref="ArgumentException"></exception> + public static List<MenmItem> EnumerateWithDescriptions(Type enumType) + { + if (!enumType.IsEnum) + { + throw new ArgumentException(" 杩欎笉鏄灇涓�"); + } + + var result = new List<MenmItem>(); + + foreach (var value in Enum.GetValues(enumType)) + { + var member = enumType.GetMember(value.ToString())[0]; + var descriptionAttribute = member.GetCustomAttribute<DescriptionAttribute>(); + + var item = new MenmItem + { + Key = value.ToString(), + Value = (int)value, // 鎴栬�呯洿鎺ヤ娇鐢� value.ToString() 濡傛灉涓嶉渶瑕佽浆鎹负鏁存暟瀛楃涓� + Description = descriptionAttribute?.Description ?? string.Empty + }; + + result.Add(item); + } + + return result; + } + /// <summary> + /// 鏄惁鏄郴缁熺被鍨� + /// </summary> + /// <param name="type"></param> + /// <returns></returns> + public static bool IsCustomType(Type type) + { + // 瀹氫箟涓�涓垨澶氫釜鍩虹鍛藉悕绌洪棿鍒楄〃锛岃繖浜涘懡鍚嶇┖闂翠笅鐨勭被鍨嬮�氬父璁や负鏄郴缁熺被鍨� + string[] frameworkNamespaces = { "System", "Microsoft", "mscorlib", "netstandard", "System.Private.CoreLib" }; + + // 鑾峰彇绫诲瀷鎵�鍦ㄧ殑鍛藉悕绌洪棿 + string typeNameSpace = type.Namespace; + + // 妫�鏌ヨ鍛藉悕绌洪棿鏄惁鍦ㄥ熀纭�鍛藉悕绌洪棿鍒楄〃涓紝濡傛灉涓嶅湪锛屽垯璁や负鏄嚜瀹氫箟绫诲瀷 + return frameworkNamespaces.Any(n => typeNameSpace.StartsWith(n, StringComparison.OrdinalIgnoreCase)); + } + + + #endregion + + + + + + + } + + /// <summary> + /// 鏋氫妇椤瑰睘鎬� + /// </summary> + [Description("鏋氫妇椤瑰睘鎬�")] + public class MenmItem + { + /// <summary> + /// 鏋氫妇key + /// </summary> + [Description("鏋氫妇key")] + public string? Key { get; set; } + /// <summary> + /// 鏋氫妇鍊� + /// </summary> + [Description("鏋氫妇鍊�")] + public int Value { get; set; } + /// <summary> + /// 鏋氫妇鎻忚堪 + /// </summary> + [Description("鏋氫妇椤瑰睘鎬�")] + public string? Description { get; set; } + } +} diff --git a/cylsg/cylsg.utility/Extend/EmunEx.cs b/cylsg/cylsg.utility/Extend/EmunEx.cs new file mode 100644 index 0000000..6f2d96c --- /dev/null +++ b/cylsg/cylsg.utility/Extend/EmunEx.cs @@ -0,0 +1,15 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace cylsg.utility.Extend +{ + /// <summary> + /// 鏋氫妇鎵╁睍 + /// </summary> + public static class EmunEx + { + } +} diff --git a/cylsg/cylsg.utility/Extend/StringEx.cs b/cylsg/cylsg.utility/Extend/StringEx.cs new file mode 100644 index 0000000..d6e261a --- /dev/null +++ b/cylsg/cylsg.utility/Extend/StringEx.cs @@ -0,0 +1,236 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace cylsg.utility.Extend +{ + /// <summary> + /// 瀛楃涓叉墿灞� + /// </summary> + public static class StringEx + { + /// <summary> + /// 棣栧瓧姣嶅皬鍐� + /// </summary> + /// <param name="self"></param> + /// <returns></returns> + public static string FirstToLower(this string self) + { + string str1 = self?.Substring(0, 1).ToLower() ?? ""; + string str2 = self?.Substring(1) ?? ""; + + //棣栧瓧姣嶈浆灏忓啓 + return str1 + str2; + } + /// <summary> + /// 甯︽湁xxx.xxx缁撴潫鐨勭殑鎵�鏈夊瓧绗︿覆 鐨勫悗闈xx.xxx + /// </summary> + /// <param name="strtypr"></param> + /// <returns></returns> + public static string GetFileName(this string strtypr) + { + return Path.GetFileName(strtypr); + } + /// <summary> + /// 鏄惁鏄暟瀛楀簭鍒� + /// </summary> + /// <param name="str"></param> + /// <returns></returns> + public static bool isPureNum(this string strtypr) + { + if (strtypr.Length == 0 || strtypr == null)//楠岃瘉杩欎釜瀛楃涓叉槸鍚︿负绌� + { + return false; + } + byte[] strBytes = Encoding.ASCII.GetBytes(strtypr);//鑾峰彇瀛楃涓茬殑byte绫诲瀷鐨勫瓧绗︽暟缁勶紝缂栫爜鏂瑰紡ASCII + foreach (byte strByte in strBytes) + { + if (strByte < 48 || strByte > 57) //鍒ゆ柇姣忎釜瀛楃鏄惁涓烘暟瀛楋紝鏍规嵁姣忎釜瀛楃鐨凙SCII鍊兼墍鍦ㄨ寖鍥村垽鏂� + { + return false; //涓嶆槸锛屽氨杩斿洖false + } + } + return true; //鏄紝灏辫繑鍥瀟rue + } + + /// <summary> + /// 鏄惁鏄暟瀛楀簭鍒� + /// </summary> + /// <param name="str"></param> + /// <returns></returns> + public static bool isGuid(this string strtypr) + { + if (strtypr.Length < 20 || strtypr == null)//楠岃瘉杩欎釜瀛楃涓叉槸鍚︿负绌� + { + return false; + } + try + { + new Guid(strtypr); + return true; + + } + catch (Exception) + { + + return false; + } + } + + /// <summary> + /// 瀛楃涓� + /// </summary> + /// <param name="strtypr"></param> + /// <returns></returns> + /// <exception cref="Exception"></exception> + public static int toInt(this string strtypr) + { + if (!strtypr.isPureNum()) + throw new Exception("骞堕潪瀹屾暣鐨勬暟瀛楀簭鍒�"); + return int.Parse(strtypr); + } + + /// <summary> + /// 绉婚櫎绗竴涓瓧绗︿覆涓烘寚瀹氬瓧绗︿覆鐨� 濡� 鈥渁xtXXXXX" 濡傛灉浠�"axt"寮�澶寸殑瀛楃涓诧紝灏辩Щ闄�"axt" 娌℃湁鍒欎笉鍙� + /// </summary> + /// <param name="strtypr"></param> + /// <param name="str">寮�濮嬪瓧绗�</param> + /// <returns></returns> + public static string RemoveStartWithStr(this string strtypr, string str) + { + string strret = strtypr; + if (strtypr.StartsWith(str)) + { + strret = strtypr.Remove(0, str.Length); + } + return strret; + + } + + /// <summary> + /// 瀵瑰瓧绗︿覆杩涜闅愮澶勭悊锛屾瘮濡備腑闂寸殑鐢�*鏄剧ず + /// </summary> + /// <param name="strtypr"></param> + /// <returns></returns> + public static string PrivacyStr(this string strtypr) + { + // 濡傛灉鏄墜鏈哄彿鐮侊紝浠呬繚鐣欏墠3浣嶅拰鍚�4浣嶏紝涓棿鐢ㄦ槦鍙锋浛鎹� + if (Regex.IsMatch(strtypr, @"^1[3-9]\d{9}$")) + { + return $"{strtypr.Substring(0, 3)}****{strtypr.Substring(7)}"; + } + + // 瀵逛簬涓枃鍚嶅瓧鎴栬�呴潪鎵嬫満鍙锋牸寮忥紝浠呬繚鐣欓灏惧悇1涓瓧绗︼紝涓棿鐢ㄦ槦鍙锋浛鎹� + else + { + if (strtypr.Length <= 2) return $"{strtypr.Substring(0, 1)}*"; // 闀垮害灏忎簬绛変簬2鏃讹紝杩斿洖鍥哄畾鐨勬槦鍙� + + var masked = $"{strtypr.Substring(0, 1)}*{strtypr.Substring(strtypr.Length - 1, 1)}"; + return masked; + } + } + + + #region 鏃堕棿鍖洪棿瀛楃涓茶浆鍏跺疄鍜岀粨鏉熸椂闂� + /// <summary> + /// 瑙f瀽鏃堕棿鍖洪棿瀛楃涓� + /// </summary> + /// <param name="input"></param> + /// <returns></returns> + public static (DateTime? StartDate, DateTime? EndDate) TryParseDateRangString(this string input) + { + DateTime startDate, endDate; + var culture = CultureInfo.InvariantCulture; + + // 灏濊瘯瑙f瀽绗竴绉嶆牸寮� "2023-01-012023-01-31" + if (DateTime.TryParseExact(input.Substring(0, 10), "yyyy-MM-dd", culture, DateTimeStyles.None, out startDate) && + DateTime.TryParseExact(input.Substring(10), "yyyy-MM-dd", culture, DateTimeStyles.None, out endDate)) + { + return (startDate, endDate); + } + + // 灏濊瘯瑙f瀽绗簩绉嶆牸寮� "2023-01-01 08:02:032023-01-31 08:02:03" + if (DateTime.TryParseExact(input.Substring(0, 19), "yyyy-MM-dd HH:mm:ss", culture, DateTimeStyles.None, out startDate) && + DateTime.TryParseExact(input.Substring(19), "yyyy-MM-dd HH:mm:ss", culture, DateTimeStyles.None, out endDate)) + { + return (startDate, endDate); + } + + // 灏濊瘯瑙f瀽绗簩绉嶆牸寮� "2023-01-01T08:02:032023-01-31T08:02:03" + if (DateTime.TryParseExact(input.Substring(0, 19), "yyyy-MM-ddTHH:mm:ss", culture, DateTimeStyles.None, out startDate) && + DateTime.TryParseExact(input.Substring(19), "yyyy-MM-ddTHH:mm:ss", culture, DateTimeStyles.None, out endDate)) + { + return (startDate, endDate); + } + // 濡傛灉閮戒笉鏄紝杩斿洖null + return (null, null); + } + + /// <summary> + /// 绉婚櫎鏈�鍚庝竴涓瓧绗︾殑?鍙� + /// </summary> + /// <param name="input"> </param> + /// /// <param name="inChar">瀛楃</param> + /// <returns></returns> + public static string RemoveCharIfPresent(this string input, char inChar) + { + if (string.IsNullOrEmpty(input)) return input; + + // 妫�鏌ュ瓧绗︿覆鐨勬渶鍚庝竴涓瓧绗︽槸鍚︿负闂彿 + if (input[^1] == '?') + { + // 浣跨敤鍒囩墖鎿嶄綔绗﹀垱寤轰笉鍖呭惈闂彿鐨勬柊瀛楃涓� + return input[..^1]; + } + else + { + // 瀛楃涓蹭笉浠ラ棶鍙风粨灏撅紝杩斿洖鍘熷瓧绗︿覆 + return input; + } + } + + /// <summary> + /// 绉婚櫎鏈�鍚庣殑瀛楃涓� + /// </summary> + /// <param name="input"></param> + /// <param name="endString"></param> + /// <returns></returns> + public static string RemoveEndStringIfExists(this string input, string endString) + { + if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(endString)) + { + return input; // 濡傛灉杈撳叆瀛楃涓叉垨缁撴潫瀛楃涓蹭负绌烘垨null锛岀洿鎺ヨ繑鍥炲師瀛楃涓� + } + + if (input.EndsWith(endString)) + { + return input.Substring(0, input.Length - endString.Length); // 绉婚櫎缁撴潫瀛楃涓� + } + + return input; // 濡傛灉涓嶄互鎸囧畾瀛楃涓茬粨鏉燂紝杩斿洖鍘熷瓧绗︿覆 + } + + + /// <summary> + /// 棣栧瓧姣嶈浆灏忓啓 + /// </summary> + /// <param name="input"></param> + /// <returns></returns> + public static string FirstCharToLower(this string input) + { + if (string.IsNullOrEmpty(input)) + { + return input; + } + + // 浣跨敤姝e垯琛ㄨ揪寮� + return Regex.Replace(input, @"^\p{Lu}", match => match.Value.ToLower()); + } + #endregion + + } +} diff --git a/cylsg/cylsg.utility/Extend/TypeAndExpressionEx.cs b/cylsg/cylsg.utility/Extend/TypeAndExpressionEx.cs new file mode 100644 index 0000000..0fe86f8 --- /dev/null +++ b/cylsg/cylsg.utility/Extend/TypeAndExpressionEx.cs @@ -0,0 +1,1021 @@ +锘縰sing System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using cylsg.utility.Extend; +using Microsoft.Extensions.Primitives; + +namespace cylsg.utility.Extend +{ + /// <summary> + /// 鍙嶅皠鎵╁睍鍑芥暟 + /// </summary> + public static class TypeAndExpressionEx + { + #region 灞炴�ф墿灞� 鍙嶅皠 + public static Func<object, object> GetPropertyExpression(Type objtype, string property) + { + property = Regex.Replace(property, @"\[[^\]]*\]", string.Empty); + List<string> level = new List<string>(); + if (property.Contains('.')) + { + level.AddRange(property.Split('.')); + } + else + { + level.Add(property); + } + + var pe = Expression.Parameter(objtype); +#pragma warning disable 8604 + var member = Expression.Property(pe, objtype.GetSingleProperty(level[0])); + for (int i = 1; i < level.Count; i++) + { + member = Expression.Property(member, member.Type.GetSingleProperty(level[i])); + } + return Expression.Lambda<Func<object, object>>(member, pe).Compile(); + } + + /// <summary> + /// 鑾峰彇灞炴�у悕 + /// </summary> + /// <param name="expression">灞炴�ц〃杈惧紡</param> + /// <param name="getAll">鏄惁鑾峰彇鍏ㄩ儴绾у埆鍚嶇О锛屾瘮濡俛.b.c</param> + /// <returns>灞炴�у悕</returns> + public static string GetPropertyName(this Expression expression, bool getAll = true) + { + if (expression == null) + { + return ""; + } + MemberExpression me = null; + LambdaExpression le = null; + if (expression is MemberExpression) + { + me = expression as MemberExpression; + } + if (expression is LambdaExpression) + { + le = expression as LambdaExpression; + if (le.Body is MemberExpression) + { + me = le.Body as MemberExpression; + } + if (le.Body is UnaryExpression) + { + me = (le.Body as UnaryExpression).Operand as MemberExpression; + } + } + string rv = ""; + if (me != null) + { + rv = me.Member.Name; + } + while (me != null && getAll && me.NodeType == ExpressionType.MemberAccess) + { + Expression exp = me.Expression; + if (exp is MemberExpression) + { + rv = (exp as MemberExpression).Member.Name + "." + rv; + me = exp as MemberExpression; + } + else if (exp is MethodCallExpression) + { + var mexp = exp as MethodCallExpression; + if (mexp.Method.Name == "get_Item") + { + object index = 0; + if (mexp.Arguments[0] is MemberExpression) + { + var obj = ((mexp.Arguments[0] as MemberExpression).Expression as ConstantExpression).Value; + index = obj.GetType().GetField((mexp.Arguments[0] as MemberExpression).Member.Name).GetValue(obj); + } + else + { + index = (mexp.Arguments[0] as ConstantExpression).Value; + } + rv = (mexp.Object as MemberExpression).Member.Name + "[" + index + "]." + rv; + me = mexp.Object as MemberExpression; + } + } + else + { + break; + } + } + return rv; + } + + public static Expression GetMemberExp(this ParameterExpression self, Expression member) + { + return self.GetMemberExp(member.GetPropertyName()); + } + + public static Expression GetMemberExp(this ParameterExpression self, string memberName) + { + var names = memberName.Split(','); + Expression rv = Expression.PropertyOrField(self, names[0]); ; + for (int i = 1; i < names.Length; i++) + { + rv = Expression.PropertyOrField(rv, names[i]); + } + return rv; + } + + + + /// <summary> + /// 鑾峰彇姝e垯琛ㄨ揪寮忛敊璇� + /// </summary> + /// <param name="pi">灞炴�т俊鎭�</param> + /// <returns>閿欒鏂囨湰</returns> + public static string GetRegexErrorMessage(this MemberInfo pi) + { + string rv = ""; + + if (pi.GetCustomAttributes(typeof(RegularExpressionAttribute), false).FirstOrDefault() is RegularExpressionAttribute dis && !string.IsNullOrEmpty(dis.ErrorMessage)) + { + rv = dis.ErrorMessage; + //if (CoreProgram._localizer != null) + //{ + // rv = CoreProgram._localizer[rv]; + //} + } + else + { + rv = ""; + } + return rv; + } + + /// <summary> + /// 鑾峰彇灞炴�ф樉绀哄悕绉� + /// </summary> + /// <param name="pi">灞炴�т俊鎭�</param> + /// <returns>灞炴�у悕绉�</returns> + public static string GetPropertyDisplayName(this MemberInfo pi) + { + string rv = ""; + if (pi.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() is DisplayAttribute dis && !string.IsNullOrEmpty(dis.Name)) + { + rv = dis.Name; + + } + else + { + rv = pi.Name; + } + return rv; + } + + /// <summary> + /// 鑾峰彇灞炴�ф樉绀哄悕绉� + /// </summary> + /// <param name="expression">灞炴�ц〃杈惧紡</param> + /// <returns>灞炴�ф樉绀哄悕绉�</returns> + public static string GetPropertyDisplayName(this Expression expression) + { + return expression.GetPropertyInfo().GetPropertyDisplayName(); + } + /// <summary> + /// 鑾峰彇灞炴�х殑 Description 鏍囨敞鍚嶏紝濡傛灉娌℃湁锛屽垯杩斿洖 灞炴�у悕绉� + /// </summary> + /// <param name="pi"></param> + /// <returns></returns> + public static string GetPropertyDescription(this MemberInfo pi) + { + string rv = ""; + if (pi.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() is DescriptionAttribute dis && !string.IsNullOrEmpty(dis.Description)) + { + rv = dis.Description; + + } + else + { + rv = pi.Name; + } + return rv; + } + + /// <summary> + /// 鑾峰彇灞炴�х殑 Description 鏍囨敞鍚嶏紝濡傛灉娌℃湁锛屽垯杩斿洖 灞炴�у悕绉� + /// </summary> + /// <param name="expression"></param> + /// <returns></returns> + public static string GetPropertyDescription(this Expression expression) + { + return expression.GetPropertyInfo().GetPropertyDisplayName(); + } + /// <summary> + /// 鑾峰彇鏋氫妇鏄剧ず鍚嶇О + /// </summary> + /// <param name="value">鏋氫妇鍊�</param> + /// <returns>鏋氫妇鏄剧ず鍚嶇О</returns> + public static string? GetEnumDisplayName(this Enum value) + { + return GetEnumDisplayName(value.GetType(), value.ToString()); + } + + /// <summary> + /// 鑾峰彇灞炴�т俊鎭� + /// </summary> + /// <param name="expression">灞炴�ц〃杈惧紡</param> + /// <returns>灞炴�т俊鎭�</returns> + public static PropertyInfo? GetPropertyInfo(this Expression expression) + { + MemberExpression me = null; + LambdaExpression le = null; + if (expression is MemberExpression) + { + me = expression as MemberExpression; + } + if (expression is LambdaExpression) + { + le = expression as LambdaExpression; + if (le.Body is MemberExpression) + { + me = le.Body as MemberExpression; + } + if (le.Body is UnaryExpression) + { + me = (le.Body as UnaryExpression).Operand as MemberExpression; + } + } + PropertyInfo rv = null; + if (me != null) + { + rv = me.Member.DeclaringType.GetSingleProperty(me.Member.Name); + } + return rv; + } + + /// <summary> + /// 鑾峰彇灞炴�у�� + /// </summary> + /// <param name="exp">灞炴�ц〃杈惧紡</param> + /// <param name="obj">灞炴�ф墍鍦ㄥ疄渚�</param> + /// <returns>灞炴�у��</returns> + public static object? GetPropertyValue(this object obj, LambdaExpression exp) + { + //鑾峰彇琛ㄨ揪寮忕殑鍊硷紝骞惰繃婊ゅ崟寮曞彿 + try + { + var expValue = exp.Compile().DynamicInvoke(obj); + object val = expValue; + return val; + } + catch + { + return ""; + } + } + /// <summary> + /// 鑾峰彇灞炴�у�� + /// </summary> + /// <param name="obj"></param> + /// <param name="property"></param> + /// <returns></returns> + public static object? GetPropertyValue(this object obj, string property) + { + //鑾峰彇琛ㄨ揪寮忕殑鍊硷紝骞惰繃婊ゅ崟寮曞彿 + try + { + return obj.GetType().GetSingleProperty(property).GetValue(obj); + } + catch + { + return null; + } + } + + + public static List<string>? GetPropertySiblingValues(this object obj, string propertyName) + { + if (obj == null) + { + return new List<string>(); + } + Regex reg = new Regex("(.*?)\\[\\-?\\d?\\]\\.(.*?)$"); + var match = reg.Match(propertyName); + if (match.Success) + { + var name1 = match.Groups[1].Value; + var name2 = match.Groups[2].Value; + + var levels = name1.Split('.'); + var objtype = obj.GetType(); + var pe = Expression.Parameter(objtype); + var member = Expression.Property(pe, objtype.GetSingleProperty(levels[0])); + for (int i = 1; i < levels.Length; i++) + { + member = Expression.Property(member, member.Type.GetSingleProperty(levels[i])); + } + var pe2 = Expression.Parameter(member.Type.GetGenericArguments()[0]); + var cast = Expression.Call(typeof(Enumerable), "Cast", new Type[] { pe2.Type }, member); + + var name2exp = Expression.Property(pe2, pe2.Type.GetSingleProperty(name2)); + var selectexp = Expression.Call(name2exp, "ToString", Type.EmptyTypes); + + Expression select = Expression.Call( + typeof(Enumerable), + "Select", + new Type[] { pe2.Type, typeof(string) }, + cast, + Expression.Lambda(selectexp, pe2)); + + + var lambda = Expression.Lambda(select, pe); + var rv = new List<string>(); + try + { + rv = (lambda.Compile().DynamicInvoke(obj) as IEnumerable<string>)?.ToList(); + } + catch { } + return rv; + } + else + { + return new List<string>(); + } + } + + /// <summary> + /// 鍒ゆ柇灞炴�ф槸鍚﹀繀濉� + /// </summary> + /// <param name="pi">灞炴�т俊鎭�</param> + /// <returns>鏄惁蹇呭~</returns> + public static bool IsPropertyRequired(this MemberInfo pi) + { + bool isRequired = false; + if (pi != null) + { + //濡傛灉闇�瑕佹樉绀烘槦鍙凤紝鍒欏垽鏂槸鍚︽槸蹇呭~椤癸紝濡傛灉鏄繀濉垯鍦ㄥ唴瀹瑰悗闈㈠姞涓婃槦鍙� + //鎵�鏈塱nt锛宖loat銆傘�傘�傝繖绉峆rimitive绫诲瀷鐨勶紝鑲畾閮芥槸蹇呭~ + Type t = pi.GetMemberType(); + if (t != null && (t.IsPrimitive() || t.IsEnum() || t == typeof(decimal) || t == typeof(Guid))) + { + isRequired = true; + } + else + { + //瀵逛簬鍏朵粬绫伙紝妫�鏌ユ槸鍚︽湁RequiredAttribute锛屽鏋滄湁灏辨槸蹇呭~ + if (pi.GetCustomAttributes(typeof(RequiredAttribute), false).FirstOrDefault() is RequiredAttribute required && required.AllowEmptyStrings == false) + { + isRequired = true; + } + else if (pi.GetCustomAttributes(typeof(KeyAttribute), false).FirstOrDefault() != null) + { + isRequired = true; + } + } + } + return isRequired; + } + + /// <summary> + /// 璁剧疆灞炴�у�� + /// </summary> + /// <param name="source">灞炴�ф墍鍦ㄥ疄渚�</param> + /// <param name="property">灞炴�у悕</param> + /// <param name="value">瑕佽祴鐨勫��</param> + /// <param name="prefix">灞炴�у墠缂�</param> + /// <param name="stringBasedValue">鏄惁涓哄瓧绗︿覆鏍煎紡鐨勫��</param> + public static void SetPropertyValue(this object source, string property, object value, string? prefix = null, bool stringBasedValue = false) + { + try + { + property = Regex.Replace(property, @"\[[^\]]*\]", string.Empty); + List<string> level = new List<string>(); + if (property.Contains('.')) + { + level.AddRange(property.Split('.')); + } + else + { + level.Add(property); + } + + if (!string.IsNullOrWhiteSpace(prefix)) + { + level.Insert(0, prefix); + } + object temp = source; + Type tempType = source.GetType(); + for (int i = 0; i < level.Count - 1; i++) + { + var member = tempType.GetMember(level[i])[0]; + if (member != null) + { + var va = member.GetMemberValue(temp); + if (va != null) + { + temp = va; + } + else + { + var newInstance = member.GetMemberType().GetConstructor(Type.EmptyTypes).Invoke(null); + member.SetMemberValue(temp, newInstance, null); + temp = newInstance; + } + tempType = member.GetMemberType(); + + } + } + + var memberInfos = tempType.GetMember(level.Last()); + if (!memberInfos.Any()) + { + return; + } + var fproperty = memberInfos[0]; + if (value == null || value is StringValues s && StringValues.IsNullOrEmpty(s)) + { + fproperty.SetMemberValue(temp, null, null); + return; + } + + bool isArray = false; + if (value != null && value.GetType().IsArray == true) + { + isArray = true; + } + + if (stringBasedValue == true) + { + Type propertyType = fproperty.GetMemberType(); + if (propertyType.IsGeneric(typeof(List<>)) == true) + { + var list = propertyType.GetConstructor(Type.EmptyTypes).Invoke(null) as IList; + + var gs = propertyType.GenericTypeArguments; + try + { + if (value.GetType() == typeof(StringValues)) + { + var strVals = (StringValues)value; + var a = strVals.ToArray(); + for (int i = 0; i < a.Length; i++) + { + list.Add(a[i].ConvertValue(gs[0])); + } + } + else if (isArray) + { + var a = value as object[]; + for (int i = 0; i < a.Length; i++) + { + list.Add(a[i].ConvertValue(gs[0])); + } + } + else + { + list = value.ConvertValue(propertyType) as IList; + } + } + catch { } + fproperty.SetMemberValue(temp, list, null); + } + else if (propertyType.IsArray) + { + try + { + var strVals = (StringValues)value; + var eletype = propertyType.GetElementType(); + if (eletype != null) + { + var arr = Array.CreateInstance(eletype, strVals.Count); + for (int i = 0; i < arr.Length; i++) + { + arr.SetValue(strVals[i].ConvertValue(eletype), i); + } + fproperty.SetMemberValue(temp, arr, null); + } + } + catch { } + } + else + { + if (isArray) + { + var a = value as object[]; + if (a.Length == 1) + { + value = a[0]; + } + } + + if (value is string) + { + value = value.ToString().Replace("\\", "/"); + } + fproperty.SetMemberValue(temp, value, null); + } + } + else + { + if (value is string) + { + value = value.ToString().Replace("\\", "/"); + } + fproperty.SetMemberValue(temp, value, null); + } + } + catch + { + } + } + + /// <summary> + /// 鏍规嵁MemberInfo鑾峰彇鍊� + /// </summary> + /// <param name="mi">MemberInfo</param> + /// <param name="obj">鎵�鍦ㄥ疄渚�</param> + /// <param name="index">濡傛灉鏄暟缁勶紝鎸囧畾鏁扮粍涓嬫爣銆傞粯璁や负null</param> + /// <returns>MemberInfo鐨勫��</returns> + public static object? GetMemberValue(this MemberInfo mi, object obj, object[]? index = null) + { + object rv = null; + if (mi.MemberType == MemberTypes.Property) + { + rv = ((PropertyInfo)mi).GetValue(obj, index); + } + else if (mi.MemberType == MemberTypes.Field) + { + rv = ((FieldInfo)mi).GetValue(obj); + } + return rv; + } + + /// <summary> + /// 璁惧畾MemberInfo鐨勫�� + /// </summary> + /// <param name="mi">MemberInfo</param> + /// <param name="obj">鎵�鍦ㄥ疄渚�</param> + /// <param name="val">瑕佽祴鐨勫��</param> + /// <param name="index">濡傛灉鏄暟缁勶紝鎸囧畾鏁扮粍涓嬫爣銆傞粯璁や负null</param> + public static void SetMemberValue(this MemberInfo mi, object obj, object val, object[]? index = null) + { + object newval = val; + if (val is string s) + { + if (string.IsNullOrEmpty(s)) + { + val = null; + } + } + if (val != null && val.GetType() != mi.GetMemberType()) + { + newval = val.ConvertValue(mi.GetMemberType()); + } + if (mi.MemberType == MemberTypes.Property) + { + ((PropertyInfo)mi).SetValue(obj, newval, index); + } + else if (mi.MemberType == MemberTypes.Field) + { + ((FieldInfo)mi).SetValue(obj, newval); + } + } + + /// <summary> + /// 鑾峰彇鏌愪釜MemberInfo鐨勭被鍨� + /// </summary> + /// <param name="mi">MemberInfo</param> + /// <returns>绫诲瀷</returns> + public static Type? GetMemberType(this MemberInfo mi) + { + Type? rv = null; + if (mi != null) + { + if (mi.MemberType == MemberTypes.Property) + { + rv = ((PropertyInfo)mi).PropertyType; + } + else if (mi.MemberType == MemberTypes.Field) + { + rv = ((FieldInfo)mi).FieldType; + } + } + return rv; + } + + /// <summary> + /// 鑾峰彇鏋氫妇鏄剧ず鍚嶇О + /// </summary> + /// <param name="enumType">鏋氫妇绫诲瀷</param> + /// <param name="value">鏋氫妇鍊�</param> + /// <returns>鏋氫妇鏄剧ず鍚嶇О</returns> + public static string? GetEnumDisplayName(Type enumType, string value) + { + string rv = ""; + FieldInfo field = null; + + if (enumType.IsEnum()) + { + field = enumType.GetField(value); + } + //濡傛灉鏄痭ullable鐨勬灇涓� + if (enumType.IsGeneric(typeof(Nullable<>)) && enumType.GetGenericArguments()[0].IsEnum()) + { + field = enumType.GenericTypeArguments[0].GetField(value); + } + + if (field != null) + { + + var attribs = field.GetCustomAttributes(typeof(DisplayAttribute), true).ToList(); + if (attribs.Count > 0) + { + rv = ((DisplayAttribute)attribs[0]).GetName(); + //if (CoreProgram._localizer != null) + //{ + // rv = CoreProgram._localizer[rv]; + //} + } + else + { + rv = value; + } + } + return rv; + } + + public static string? GetEnumDisplayName(Type enumType, int value) + { + string? rv = ""; + FieldInfo? field = null; + string? ename = ""; + if (enumType.IsEnum()) + { + ename = enumType.GetEnumName(value); + field = enumType.GetField(ename ?? ""); + } + //濡傛灉鏄痭ullable鐨勬灇涓� + if (enumType.IsGeneric(typeof(Nullable<>)) && enumType.GetGenericArguments()[0].IsEnum()) + { + ename = enumType.GenericTypeArguments[0].GetEnumName(value); + field = enumType.GenericTypeArguments[0].GetField(ename ?? ""); + } + + if (field != null) + { + + var attribs = field.GetCustomAttributes(typeof(DisplayAttribute), true).ToList(); + if (attribs.Count > 0) + { + rv = ((DisplayAttribute)attribs[0]).GetName(); + //if (CoreProgram._localizer != null) + //{ + // rv = CoreProgram._localizer[rv]; + //} + } + else + { + rv = ename; + } + } + return rv; + } + + /// <summary> + /// 杞寲鍊� + /// </summary> + /// <param name="value">瑕佽浆鎹㈢殑鍊�</param> + /// <param name="propertyType">杞崲鍚庣殑绫诲瀷</param> + /// <returns>杞崲鍚庣殑鍊�</returns> + public static object? ConvertValue(this object value, Type propertyType) + { + object val = null; + if (propertyType.IsGeneric(typeof(Nullable<>)) == true) + { + var gs = propertyType.GenericTypeArguments; + try + { + val = value.ConvertValue(gs[0]); + } + catch { } + } + else if (propertyType.IsEnum()) + { + val = Enum.Parse(propertyType, value.ToString()); + } + else if (propertyType == typeof(string)) + { + val = value?.ToString().Trim(); + } + else if (propertyType == typeof(Guid)) + { + bool suc = Guid.TryParse(value?.ToString(), out Guid g); + if (suc) + { + val = g; + } + else + { + val = Guid.Empty; + } + } + + else + { + try + { + if (value.ToString().StartsWith("`") && value.ToString().EndsWith("`")) + { + string inner = value.ToString().Trim('`').TrimEnd(','); + if (!string.IsNullOrWhiteSpace(inner)) + { + val = propertyType.GetConstructor(Type.EmptyTypes).Invoke(null); + string[] pair = inner.Split(','); + var gs = propertyType.GetGenericArguments(); + foreach (var p in pair) + { + (val as IList).Add(Convert.ChangeType(p, gs[0])); + } + } + } + else + { + val = Convert.ChangeType(value.ToString(), propertyType); + } + } + catch + { + } + } + return val; + } + + public static object MakeList(Type innerType, string propertyName, object[] values) + { + object rv = typeof(List<>).MakeGenericType(innerType).GetConstructor(Type.EmptyTypes).Invoke(null); + var mi = rv.GetType().GetMethod("Add"); + var con = innerType.GetConstructor(Type.EmptyTypes); + foreach (var item in values) + { + var newobj = con.Invoke(null); + newobj.SetPropertyValue(propertyName, item); + mi.Invoke(rv, new object[] { newobj }); + } + return rv; + } + + /// <summary> + /// 鑾峰彇 鏄惁瀹氫箟璇ユ爣绛惧睘鎬� + /// </summary> + /// <param name="pi"></param> + /// <param name="local"></param> + /// <returns></returns> + public static T? GetAttribute<T>(this MemberInfo pi) where T : Attribute + { + string rv = ""; + if (pi.GetCustomAttributes(typeof(T), false).FirstOrDefault() is T dis) + { + return dis; + } + else + { + return null; + } + + } + + + public static ImmutableDictionary<string, List<PropertyInfo>> _propertyCache { get; set; } = + new Dictionary<string, List<PropertyInfo>>().ToImmutableDictionary(); + /// <summary> + /// 鍒ゆ柇鏄惁鏄硾鍨� + /// </summary> + /// <param name="self">Type绫�</param> + /// <param name="innerType">娉涘瀷绫诲瀷</param> + /// <returns>鍒ゆ柇缁撴灉</returns> + public static bool IsGeneric(this Type self, Type innerType) + { + if (self.GetTypeInfo().IsGenericType && self.GetGenericTypeDefinition() == innerType) + { + return true; + } + else + { + return false; + } + } + + /// <summary> + /// 鍒ゆ柇鏄惁涓篘ullable<>绫诲瀷 + /// </summary> + /// <param name="self">Type绫�</param> + /// <returns>鍒ゆ柇缁撴灉</returns> + public static bool IsNullable(this Type self) + { + return self.IsGeneric(typeof(Nullable<>)); + } + + /// <summary> + /// 鍒ゆ柇鏄惁涓篖ist<>绫诲瀷 + /// </summary> + /// <param name="self">Type绫�</param> + /// <returns>鍒ゆ柇缁撴灉</returns> + public static bool IsList(this Type self) + { + return self.IsGeneric(typeof(List<>)) || self.IsGeneric(typeof(IEnumerable<>)); + } + + /// <summary> + /// 鍒ゆ柇鏄惁涓篖ist<>绫诲瀷 + /// </summary> + /// <param name="self">Type绫�</param> + /// <returns>鍒ゆ柇缁撴灉</returns> + public static bool IsListOf<T>(this Type self) + { + if (self.IsGeneric(typeof(List<>)) && typeof(T).IsAssignableFrom(self.GenericTypeArguments[0])) + { + return true; + } + else + { + return false; + } + } + + + #region 鍒ゆ柇鏄惁涓烘灇涓� + + /// <summary> + /// 鍒ゆ柇鏄惁涓烘灇涓� + /// </summary> + /// <param name="self">Type绫�</param> + /// <returns>鍒ゆ柇缁撴灉</returns> + public static bool IsEnum(this Type self) + { + return self.GetTypeInfo().IsEnum; + } + + /// <summary> + /// 鍒ゆ柇鏄惁涓烘灇涓炬垨鑰呭彲绌烘灇涓� + /// </summary> + /// <param name="self"></param> + /// <returns></returns> + public static bool IsEnumOrNullableEnum(this Type self) + { + if (self == null) + { + return false; + } + if (self.IsEnum) + { + return true; + } + else + { + if (self.IsGenericType && self.GetGenericTypeDefinition() == typeof(Nullable<>) && self.GetGenericArguments()[0].IsEnum) + { + return true; + } + else + { + return false; + } + } + } + + #endregion + + /// <summary> + /// 鍒ゆ柇鏄惁涓哄�肩被鍨� 鍩虹鍊肩被鍨� + /// </summary> + /// <param name="self">Type绫�</param> + /// <returns>鍒ゆ柇缁撴灉</returns> + public static bool IsPrimitive(this Type self) + { + return self.GetTypeInfo().IsPrimitive || self == typeof(decimal); + } + /// <summary> + /// 鍒ゆ柇鍊兼槸鍚︽槸鏁板瓧鍩虹绫诲瀷 + /// </summary> + /// <param name="self"></param> + /// <returns></returns> + public static bool IsNumber(this Type self) + { + Type checktype = self; + if (self.IsNullable()) + { + checktype = self.GetGenericArguments()[0]; + } + if (checktype == typeof(int) || checktype == typeof(short) || checktype == typeof(long) || checktype == typeof(float) || checktype == typeof(decimal) || checktype == typeof(double)) + { + return true; + } + else + { + return false; + } + } + + + #region 鍒ゆ柇鏄惁鏄疊ool + /// <summary> + /// 鏄惁鏄痓ool绫诲瀷 + /// </summary> + /// <param name="self"></param> + /// <returns></returns> + public static bool IsBool(this Type self) + { + return self == typeof(bool); + } + + /// <summary> + /// 鍒ゆ柇鏄惁鏄� bool or bool?绫诲瀷 + /// </summary> + /// <param name="self"></param> + /// <returns></returns> + public static bool IsBoolOrNullableBool(this Type self) + { + if (self == null) + { + return false; + } + if (self == typeof(bool) || self == typeof(bool?)) + { + return true; + } + else + { + return false; + } + } + + #endregion + + /// <summary> + /// 鏍规嵁鍚嶅瓧鑾峰彇 + /// </summary> + /// <param name="self"></param> + /// <param name="name"></param> + /// <returns></returns> + public static PropertyInfo? GetSingleProperty(this Type self, string name) + { + if (self.FullName == null) + throw new Exception("灞炴�у悕涓虹┖"); + if (_propertyCache.ContainsKey(self.FullName) == false) + { + var properties = self.GetProperties().ToList(); + _propertyCache = _propertyCache.Add(self.FullName, properties); + return properties.Where(x => x.Name == name).FirstOrDefault(); + } + else + { + return _propertyCache[self.FullName].Where(x => x.Name == name).FirstOrDefault(); + } + } + /// <summary> + /// 鑾峰彇灞炴�у垪琛� 骞跺皢 鍒楄〃灞炴�ф斁鍏ョ紦瀛� + /// </summary> + /// <param name="self"></param> + /// <returns></returns> + public static PropertyInfo? GetSingleProperty(this Type self, Func<PropertyInfo, bool> where) + { + if (self.FullName == null) + throw new Exception("灞炴�у悕涓虹┖"); + if (_propertyCache.ContainsKey(self.FullName) == false) + { + var properties = self.GetProperties().ToList(); + _propertyCache = _propertyCache.Add(self.FullName, properties); + return properties.Where(where).FirstOrDefault(); + } + else + { + return _propertyCache[self.FullName].Where(where).FirstOrDefault(); + } + } + /// <summary> + /// 鑾峰彇灞炴�у垪琛� 骞跺皢 鍒楄〃灞炴�ф斁鍏ョ紦瀛� + /// </summary> + /// <param name="self"></param> + /// <returns></returns> + public static List<PropertyInfo> GetAllProperties(this Type self) + { + if (self.FullName == null) + throw new Exception("灞炴�у悕涓虹┖"); + if (_propertyCache.ContainsKey(self.FullName) == false) + { + var properties = self.GetProperties().ToList(); + _propertyCache = _propertyCache.Add(self.FullName, properties); + return properties; + } + else + { + return _propertyCache[self.FullName]; + } + } + #endregion + } +} diff --git a/cylsg/cylsg.utility/cylsg.utility.csproj b/cylsg/cylsg.utility/cylsg.utility.csproj new file mode 100644 index 0000000..3cb2bf4 --- /dev/null +++ b/cylsg/cylsg.utility/cylsg.utility.csproj @@ -0,0 +1,13 @@ +锘�<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>net8.0</TargetFramework> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="Microsoft.Extensions.Primitives" Version="8.0.0" /> + </ItemGroup> + +</Project> -- Gitblit v1.9.1