From 68e7f3cb5d45bd2b9bd11c3295c931b4a0a15e87 Mon Sep 17 00:00:00 2001 From: wangzewei <1585955375@qq.com> Date: Thu, 27 May 2021 19:16:42 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90Delete=EF=BC=9A=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E7=B1=BB=E5=BA=93=EF=BC=8C=E5=B0=86=E5=85=AC?= =?UTF-8?q?=E5=85=B1=E7=B1=BB=E5=BA=93=E6=89=93=E5=8C=85=E6=88=90=E5=AF=B9?= =?UTF-8?q?=E5=BA=94=E7=9A=84nuget,=E3=80=91=20=E3=80=90Add=EF=BC=9A?= =?UTF-8?q?=E5=87=86=E5=A4=87=E4=BB=8B=E5=85=A5QQ=E7=99=BB=E5=BD=95?= =?UTF-8?q?=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Destiny.Core.Flow.sln | 107 +-- .../destiny-core-flowadmin-autoscaler.yaml | 13 + .../Controllers/DocumentTypeController.cs | 13 +- .../Controllers/Menu/MenuController.cs | 423 +++++------ .../Destiny.Core.Flow.API.csproj | 13 +- .../Destiny.Core.Flow.API.xml | 6 + .../PublishProfiles/FolderProfile.pubxml.user | 2 +- src/Destiny.Core.Flow.API/Startup.cs | 15 + .../Startups/AppWebModule.cs | 3 +- src/Destiny.Core.Flow.Aop/AopModule .cs | 44 -- .../Destiny.Core.Flow.Aop.csproj | 12 - .../NonGlobalAopTranAttribute.cs | 34 - .../Api/AdminControllerBase.cs | 15 - .../Api/ApiControllerBase.cs | 13 - .../BaseController.cs | 24 - .../Destiny.Core.Flow.AspNetCore.csproj | 17 - .../Extensions/HttpRequestExtensions.cs | 32 - .../Extensions/ModelStateExtensions.cs | 80 -- .../Middleware/ExceptionHandlingMiddleware.cs | 94 --- .../Module/AspNetCoreModule.cs | 10 - .../Module/AspNetCoreModuleBase.cs | 62 -- .../Module/DestinyCoreModule.cs | 36 - .../Module/MvcModuleBase.cs | 60 -- .../Mvc/Filters/AuditLogFilterAttribute.cs | 83 -- .../Mvc/Filters/HandleException.cs | 38 - .../Filters/PermissionAuthorizationFilter.cs | 72 -- .../Mvc/Filters/UnitOfWorkAtrrribute.cs | 67 -- .../Mvc/Filters/ValidationFilterAttribute.cs | 53 -- .../Ui/AjaxResult.cs | 89 --- .../Ui/AjaxResultExtensions.cs | 65 -- .../Ui/JsonResultExtensions.cs | 23 - .../Ui/PageList.cs | 30 - .../Ui/PageListExtensions.cs | 22 - .../Ui/TreeModel.cs | 47 -- .../Ui/TreeModelExtensions.cs | 24 - ...tiny.Core.Flow.AuthenticationCenter.csproj | 7 +- .../Startups/IdentityModule.cs | 5 +- .../Views/Account/Login.cshtml | 2 +- .../AutoMapperModule.cs | 62 -- .../Destiny.Core.Flow.AutoMapper.csproj | 16 - .../CSRedisCache.cs | 57 -- .../CSRedisModule.cs | 31 - .../CacheHelper.cs | 157 ---- .../Destiny.Core.Flow.Caching.CSRedis.csproj | 17 - src/Destiny.Core.Flow.Caching/CacheDefault.cs | 135 ---- .../CacheHandlerBase.cs | 16 - src/Destiny.Core.Flow.Caching/CacheOptions.cs | 6 - .../CachingDefaultModule.cs | 21 - .../Destiny.Core.Flow.Caching.csproj | 16 - src/Destiny.Core.Flow.Caching/ICache.cs | 94 --- .../CodeData.cs | 29 - .../CodeGeneratorModeule.cs | 22 - .../CodeGeneratorService.cs | 29 - .../Destiny.Core.Flow.CodeGenerator.csproj | 41 - .../EntityMetadata.cs | 84 -- .../ICodeGenerator.cs | 60 -- .../ICodeGeneratorService.cs | 21 - .../ProjectMetadata.cs | 47 -- .../PropertyMetadata.cs | 66 -- .../RazorCodeGenerator.cs | 302 -------- .../Templates/Controller.cshtml | 97 --- .../Templates/Entity.cshtml | 130 ---- .../Templates/EntityConfiguration.cshtml | 38 - .../Templates/IService.cshtml | 60 -- .../Templates/InputDto.cshtml | 39 - .../Templates/OutputDto.cshtml | 39 - .../Templates/PageListDto.cshtml | 40 - .../Templates/ServiceImpl.cshtml | 94 --- .../TypeHelper.cs | 97 --- .../Destiny.Core.Flow.Consul.csproj | 16 - .../DestinyConsulModule.cs | 94 --- .../Destiny.Core.Flow.Dtos.csproj | 7 +- .../DatabaseTypeAttribute.cs | 22 - .../DbContextExtensions.cs | 23 - .../DbContextOptionsBuilderExtensions..cs | 22 - .../DbContexts/DbContextBase.cs | 215 ------ .../DbContexts/DefaultDbContext.cs | 32 - .../DbDrivens/MySqlDbContextDrivenProvider.cs | 26 - .../SqlServerDbContextDrivenProvider.cs | 24 - ...stiny.Core.Flow.EntityFrameworkCore.csproj | 20 - .../EntityFrameworkCoreModule.cs | 51 -- .../IDbContextDrivenProvider.cs | 29 - .../Interceptor/AuditInterceptor.cs | 22 - .../EntityMappingConfigurationOfModel.cs | 27 - .../Mapping/IEntityMappingConfiguration.cs | 17 - .../IEntityMappingConfigurationOfModel.cs | 12 - .../Mapping/ModelBuilderExtenions.cs | 25 - .../Repository.cs | 716 ------------------ .../Repositorys/DapperRepository.cs | 27 - .../Repositorys/IDapperRepository.cs | 13 - .../Repositorys/UnitOfWork.cs | 300 -------- .../Repositorys/UnitOfWorkExtensions.cs | 160 ---- .../ServiceExtensions.cs | 92 --- .../Destiny.Core.Flow.FluentValidation.csproj | 16 - .../FluentModelValidator.cs | 9 - .../FluentValidationExtensions.cs | 109 --- .../FluentValidationModelValidator.cs | 32 - .../FluentValidationModuleBase.cs | 24 - .../ServiceProviderValidatorFactory.cs | 23 - .../Destiny.Core.Flow.GateWay.csproj | 19 - src/Destiny.Core.Flow.GateWay/Program.cs | 20 - .../Properties/launchSettings.json | 27 - src/Destiny.Core.Flow.GateWay/Startup.cs | 36 - .../appsettings.Development.json | 9 - .../appsettings.json | 10 - .../ocelotconfigure.json | 1 - .../Destiny.Core.Flow.IServices.csproj | 2 +- .../Destiny.Core.Flow.Identitys.csproj | 6 +- ...y.Core.Flow.IdentityServer.Entities.csproj | 4 +- .../Destiny.Core.Flow.IdentityServer.csproj | 2 +- .../Destiny.Core.Flow.Log4Net.csproj | 16 - .../Log4NetLogger.cs | 128 ---- .../Log4NetModuleBase.cs | 18 - .../Log4NetProvider.cs | 64 -- .../MNZ.CMS.Core.Log4Net.csproj | 16 - src/Destiny.Core.Flow.Log4Net/log4net.config | 84 -- .../Destiny.Core.Flow.MiniProfiler.csproj | 18 - .../MiniProfilerModule.cs | 36 - .../Destiny.Core.Flow.Model.csproj | 3 +- .../DbContexts/DefaultMongoDbContext.cs | 13 - .../DbContexts/MongoDbContextBase.cs | 64 -- .../Destiny.Core.Flow.MongoDB.csproj | 16 - .../FindFluentExtensions.cs | 27 - .../FindFluentSortBy.cs | 66 -- .../Infrastructure/IMongoDbContextOptions.cs | 8 - .../Metadata/Builders/MongoDBFilterBuilder.cs | 163 ---- .../MongoCollectionExtensions.cs | 40 - .../MongoDBModuleBase.cs | 32 - .../MongoDBServiceCollectionExtensions.cs | 20 - .../MongoDbContextOptions.cs | 9 - src/Destiny.Core.Flow.MongoDB/MongoEntity.cs | 11 - .../Repositorys/IMongoDBRepository.cs | 54 -- .../Repositorys/MongoDBRepository.cs | 121 --- .../Destiny.Core.Flow.Repository.csproj | 6 +- .../Destiny.Core.Flow.SeriLog.csproj | 5 +- .../Audit/AuditStore.cs | 1 - .../Destiny.Core.Flow.Services.csproj | 11 +- .../Destiny.Core.Flow.Swagger.csproj | 21 - .../Filter/AutoRestSchemaFilter.cs | 27 - .../Filter/TagDescriptionsDocumentFilter.cs | 13 - .../SwaggerModule.cs | 144 ---- .../Destiny.Core.Flow.TestBase.csproj | 5 +- .../Application/CrudServiceAsync.cs | 38 - .../Application/ICrudServiceAsync.cs | 35 - .../Attributes/Base/AttributeBase.cs | 9 - .../Attributes/MongoDBTableAttribute.cs | 21 - src/Destiny.Core.Flow/Audit/AuditChange.cs | 77 -- src/Destiny.Core.Flow/Audit/AuditEntry.cs | 68 -- src/Destiny.Core.Flow/Audit/AuditLog.cs | 74 -- .../Audit/AuditPropertysEntry.cs | 55 -- .../Audit/DataOperationType.cs | 10 - .../Audit/DisableAuditingAttribute.cs | 15 - .../Audit/Dto/AuditEntryDto.cs | 59 -- .../Audit/Dto/AuditEntryOutputPageDto.cs | 63 -- .../Audit/Dto/AuditLogOutputPageDto.cs | 54 -- .../Audit/Dto/AuditPropertyDto.cs | 45 -- .../Dto/AuditPropertyEntryOutputPageDto.cs | 44 -- .../Audit/EntityHistory/AuditHelper.cs | 157 ---- .../Audit/EntityHistory/IAuditHelper.cs | 22 - src/Destiny.Core.Flow/Audit/IAuditStore.cs | 48 -- .../ConsulEntity/ServiceEntity.cs | 30 - src/Destiny.Core.Flow/Data/ComnGuid.cs | 38 - .../Data/Core/Collections/ITypeList.cs | 6 - .../Data/Core/Collections/ITypeListOfModel.cs | 14 - .../Data/Core/Collections/TypeList.cs | 110 --- .../Data/Core/Function/FunctionAttribute.cs | 9 - .../Data/Core/Function/FunctionInfo.cs | 13 - src/Destiny.Core.Flow/Data/Dto/SelectItem.cs | 21 - .../Data/LazyConcurrentDictionary.cs | 51 -- .../Dependency/DependencyAppModule.cs | 96 --- .../Dependency/DependencyAttribute.cs | 28 - .../Dependency/DictionaryScoped.cs | 49 -- .../Dependency/IScopedDependency.cs | 8 - .../Dependency/IServiceProviderAccessor.cs | 12 - .../Dependency/ISingletonDependency.cs | 10 - .../Dependency/ITransientDependency.cs | 10 - .../Dependency/IgnoreDependencyAttribute.cs | 12 - src/Destiny.Core.Flow/Dependency/IocManage.cs | 67 -- .../Dependency/LazyFactory.cs | 13 - .../Dependency/ObjectAccessor.cs | 23 - .../Destiny.Core.Flow.csproj | 41 - .../Disposables/IDisposable2.cs | 57 -- src/Destiny.Core.Flow/Entity/DatabaseType.cs | 23 - .../Entity/DestinyContextOptionsBuilder.cs | 17 - src/Destiny.Core.Flow/Entity/EntityBase.cs | 72 -- src/Destiny.Core.Flow/Entity/ICreatedTime.cs | 14 - .../Entity/ICreationAudited.cs | 19 - src/Destiny.Core.Flow/Entity/IDto.cs | 15 - src/Destiny.Core.Flow/Entity/IEntity.cs | 10 - .../Entity/IEntityExtensions.cs | 96 --- .../Entity/IEntityOfModel.cs | 17 - .../Entity/IFullAuditedEntityOfModel.cs | 16 - src/Destiny.Core.Flow/Entity/IInputDto.cs | 14 - .../Entity/IModificationAudited.cs | 19 - .../Entity/IModificationTime.cs | 14 - src/Destiny.Core.Flow/Entity/IOutputDto.cs | 31 - src/Destiny.Core.Flow/Entity/IRepository.cs | 196 ----- src/Destiny.Core.Flow/Entity/ISeedData.cs | 18 - src/Destiny.Core.Flow/Entity/ISoftDelete.cs | 12 - src/Destiny.Core.Flow/Entity/IStateDto.cs | 25 - src/Destiny.Core.Flow/Entity/IUnitOfWork.cs | 72 -- .../Entity/IUnitOfWorkAccessor.cs | 6 - .../Entity/IUnitOfWorkManager.cs | 9 - src/Destiny.Core.Flow/Entity/InputDto.cs | 7 - .../Entity/InputWaitStateDto.cs | 6 - .../Entity/Modules/MigrationModuleBase.cs | 60 -- src/Destiny.Core.Flow/Entity/OutputDto.cs | 9 - src/Destiny.Core.Flow/Entity/SeedDataBase.cs | 54 -- src/Destiny.Core.Flow/Enums/Enums.cs | 183 ----- .../Events/Abstractions/IEventBase.cs | 21 - .../Events/Abstractions/IEventHandlerBase.cs | 12 - .../Events/CacheEventDataBase.cs | 21 - src/Destiny.Core.Flow/Events/EventBase.cs | 37 - .../Events/EventBus/IEventBus.cs | 24 - .../Events/EventBus/IMediatorHandler.cs | 21 - .../Events/EventBus/InMemoryBus.cs | 33 - .../Events/EventBusExtensions.cs | 17 - .../Events/EventHandlerBase.cs | 11 - src/Destiny.Core.Flow/Events/EventQueue.cs | 31 - .../Events/MediatorAppModule.cs | 25 - src/Destiny.Core.Flow/Events/Notification.cs | 10 - .../Events/NotificationHandlerBase.cs | 9 - .../Exceptions/AppException.cs | 32 - .../Exceptions/MessageBox.cs | 30 - .../MissingTypeRegistrationException.cs | 20 - .../ExpressionUtil/Expressionable.cs | 328 -------- .../ExpressionUtil/ExtensionMethods.cs | 72 -- .../ExpressionUtil/FilterBuilder.cs | 172 ----- .../Extensions/AutoMapperExtensions.cs | 92 --- .../Extensions/BooleanWitnBoolExtensions.cs | 30 - .../Extensions/CheckExtensions.cs | 164 ---- .../Extensions/ClaimsIdentityExtensions.cs | 230 ------ .../Extensions/CollectionExtensions.cs | 259 ------- .../Extensions/ComparableExtensions.cs | 13 - .../Extensions/ControllerExtensions.cs | 25 - .../Extensions/DateExtensions.cs | 34 - .../Extensions/DbContextExtensions.cs | 35 - .../Extensions/EntityEntryExtensions.cs | 54 -- .../Extensions/EntityExtensions.cs | 23 - .../Extensions/EnumExtensions.cs | 38 - .../Extensions/ExpressionExtensions.cs | 434 ----------- .../Extensions/ExpressionVisitorExtensions.cs | 48 -- .../Extensions/FileExtensions.cs | 26 - .../Extensions/GetIPExtension.cs | 45 -- .../Extensions/GuidExtensions.cs | 62 -- .../Extensions/HashExtensions.cs | 79 -- .../Extensions/IdentityResultExtensions.cs | 39 - .../Extensions/ObjectExtensions.cs | 140 ---- .../Extensions/QueryableExtensions.cs | 272 ------- .../Extensions/SecurityExtension.cs | 279 ------- .../Extensions/ServiceCollectionExtension.cs | 278 ------- .../ServiceCollectionObjectsExtensions.cs | 57 -- .../Extensions/ServiceProviderExtensions.cs | 234 ------ .../Extensions/StringExtensions.cs | 232 ------ .../Extensions/TypeExtensions.cs | 689 ----------------- .../Filter/Abstract/IFilterReauest.cs | 16 - .../Filter/Abstract/IFilteredPagedRequest.cs | 27 - .../Filter/Abstract/IOrderRequest.cs | 17 - .../Filter/Abstract/IPagedRequest.cs | 21 - .../Filter/Abstract/IPagedResult.cs | 12 - .../Filter/CollectionPropertySorter.cs | 77 -- .../Filter/FilterCodeAttribute.cs | 23 - .../Filter/FilterCondition.cs | 38 - src/Destiny.Core.Flow/Filter/IResultData.cs | 7 - .../Filter/OrderCondition.cs | 72 -- .../Filter/PageParameters.cs | 35 - src/Destiny.Core.Flow/Filter/PageRequest.cs | 14 - src/Destiny.Core.Flow/Filter/PageResult.cs | 38 - .../Filter/PagedRequestModel.cs | 19 - src/Destiny.Core.Flow/Filter/QueryFilter.cs | 48 -- .../Filter/QueryParameters.cs | 15 - .../Filter/ResultBaseOfModel.cs | 9 - src/Destiny.Core.Flow/Helpers/ArrayHelper.cs | 23 - .../Helpers/DelegateHelper.cs | 44 -- src/Destiny.Core.Flow/Helpers/JsonHelper.cs | 324 -------- .../Helpers/ReflectHelper.cs | 27 - .../Helpers/TypeNameHelper.cs | 174 ----- .../AllowedSigningAlgorithmsConverter.cs | 38 - .../IdentityServer4/GrantType.cs | 21 - .../IdentityServer4/GrantTypes.cs | 43 -- .../IdentityServer4/JwtClaimTypes.cs | 382 ---------- .../Mapping/AutoMapDirection.cs | 8 - .../Mapping/AutoMapFromAttribute.cs | 18 - .../Mapping/AutoMapToAttribute.cs | 18 - .../Mapping/AutoMappingAttribute.cs | 27 - src/Destiny.Core.Flow/Modules/AppModule.cs | 65 -- .../Modules/AppModuleExtensions.cs | 48 -- .../Modules/ApplicationContext.cs | 26 - .../ApplicationInitializationExtensions.cs | 23 - .../Modules/ConfigureServicesContext.cs | 60 -- .../ConfigureServicesContextExtenstions.cs | 14 - .../Modules/DependsOnAttribute.cs | 30 - src/Destiny.Core.Flow/Modules/IAppModule.cs | 28 - .../Modules/IApplicationInitialization.cs | 10 - .../Modules/IDependedTypesProvider.cs | 16 - .../Modules/IModuleApplication.cs | 18 - .../Modules/IStartupModuleRunner.cs | 15 - .../Modules/ModuleApplicationBase.cs | 105 --- .../Modules/StartupModuleRunner.cs | 58 -- .../Network/NetworkHelper.cs | 40 - .../Options/AppOptionSettings.cs | 46 -- src/Destiny.Core.Flow/Options/AuthOptions.cs | 14 - src/Destiny.Core.Flow/Options/CorsOptions.cs | 19 - .../Options/DestinyContextOptions.cs | 39 - src/Destiny.Core.Flow/Options/JwtOptions.cs | 25 - .../Permission/IAuthorityVerification.cs | 19 - .../NoAuthorityVerificationAttribute.cs | 13 - .../Reflection/AssemblyFinder.cs | 12 - .../Reflection/AssemblyHelper.cs | 85 --- .../Reflection/FinderBase.cs | 26 - .../Reflection/IAssemblyFinder.cs | 9 - src/Destiny.Core.Flow/Reflection/IFinder.cs | 14 - .../Reflection/ITypeFinder.cs | 12 - .../Reflection/TypeFinder.cs | 22 - .../Security/Identity/ClaimTypes.cs | 12 - .../Security/Identity/IdentityProfile.cs | 29 - .../Security/Jwt/IJwtBearerService.cs | 13 - .../Security/Jwt/JwtBearerService.cs | 80 -- .../Security/Jwt/JwtResult.cs | 19 - src/Destiny.Core.Flow/Threading/AsyncEx.cs | 202 ----- .../BackgroundTasks/BackgroundTaskQueue.cs | 36 - .../BackgroundTasks/IBackgroundTaskQueue.cs | 14 - .../Threading/ObjectPoolAsync.cs | 107 --- src/Destiny.Core.Flow/Threading/TaskResult.cs | 207 ----- .../Threading/ThreadSafeRandom.cs | 52 -- .../Ui/Abstracts/IHasResultType.cs | 13 - .../Ui/Abstracts/IListResult.cs | 9 - .../Ui/Abstracts/ITreeResult.cs | 25 - .../Ui/AuthorizationResult.cs | 32 - .../Ui/MessageDefinitionType.cs | 15 - src/Destiny.Core.Flow/Ui/OperationResponse.cs | 98 --- .../Ui/OperationResponseExtensions.cs | 117 --- .../Ui/OperationResponseOfModel.cs | 109 --- src/Destiny.Core.Flow/Ui/ResultBase.cs | 32 - src/Destiny.Core.Flow/Ui/TreeResult.cs | 53 -- .../Validation/Extensions.cs | 16 - .../Validation/IModelValidator.cs | 29 - .../Interceptor/IMethodParameterValidator.cs | 9 - .../Interceptor/MethodInvocationValidator.cs | 140 ---- ...ModelValidationMethodParameterValidator.cs | 34 - .../ValidationInterceptorAttribute.cs | 73 -- .../ModelValidationResultExtensions.cs | 16 - .../Validation/ModelValidator.cs | 30 - .../Validation/ValidationException.cs | 21 - .../Validation/ValidationFailure.cs | 19 - .../Destiny.Core.Tests}/CodeGeneratorTests.cs | 0 .../Destiny.Core.Tests.csproj | 12 +- .../Destiny.Core.Tests}/MemoryTests.cs | 0 .../Destiny.Core.Tests}/MongoDBTests.cs | 37 +- .../Destiny.Core.Tests}/StartupModulesTest.cs | 0 .../Destiny.Core.Tests}/appsettings.json | 0 351 files changed, 300 insertions(+), 18758 deletions(-) create mode 100644 K8sdeploy/destiny-core-flowadmin-autoscaler.yaml delete mode 100644 src/Destiny.Core.Flow.Aop/AopModule .cs delete mode 100644 src/Destiny.Core.Flow.Aop/Destiny.Core.Flow.Aop.csproj delete mode 100644 src/Destiny.Core.Flow.Aop/NonGlobalAopTranAttribute.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Api/AdminControllerBase.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Api/ApiControllerBase.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/BaseController.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Destiny.Core.Flow.AspNetCore.csproj delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Extensions/HttpRequestExtensions.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Extensions/ModelStateExtensions.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Middleware/ExceptionHandlingMiddleware.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Module/AspNetCoreModule.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Module/AspNetCoreModuleBase.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Module/DestinyCoreModule.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Module/MvcModuleBase.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/AuditLogFilterAttribute.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/HandleException.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/PermissionAuthorizationFilter.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/UnitOfWorkAtrrribute.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/ValidationFilterAttribute.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Ui/AjaxResult.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Ui/AjaxResultExtensions.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Ui/JsonResultExtensions.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Ui/PageList.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Ui/PageListExtensions.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Ui/TreeModel.cs delete mode 100644 src/Destiny.Core.Flow.AspNetCore/Ui/TreeModelExtensions.cs delete mode 100644 src/Destiny.Core.Flow.AutoMapper/AutoMapperModule.cs delete mode 100644 src/Destiny.Core.Flow.AutoMapper/Destiny.Core.Flow.AutoMapper.csproj delete mode 100644 src/Destiny.Core.Flow.Caching.CSRedis/CSRedisCache.cs delete mode 100644 src/Destiny.Core.Flow.Caching.CSRedis/CSRedisModule.cs delete mode 100644 src/Destiny.Core.Flow.Caching.CSRedis/CacheHelper.cs delete mode 100644 src/Destiny.Core.Flow.Caching.CSRedis/Destiny.Core.Flow.Caching.CSRedis.csproj delete mode 100644 src/Destiny.Core.Flow.Caching/CacheDefault.cs delete mode 100644 src/Destiny.Core.Flow.Caching/CacheHandlerBase.cs delete mode 100644 src/Destiny.Core.Flow.Caching/CacheOptions.cs delete mode 100644 src/Destiny.Core.Flow.Caching/CachingDefaultModule.cs delete mode 100644 src/Destiny.Core.Flow.Caching/Destiny.Core.Flow.Caching.csproj delete mode 100644 src/Destiny.Core.Flow.Caching/ICache.cs delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/CodeData.cs delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/CodeGeneratorModeule.cs delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/CodeGeneratorService.cs delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/Destiny.Core.Flow.CodeGenerator.csproj delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/EntityMetadata.cs delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/ICodeGenerator.cs delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/ICodeGeneratorService.cs delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/ProjectMetadata.cs delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/PropertyMetadata.cs delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/RazorCodeGenerator.cs delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/Templates/Controller.cshtml delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/Templates/Entity.cshtml delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/Templates/EntityConfiguration.cshtml delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/Templates/IService.cshtml delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/Templates/InputDto.cshtml delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/Templates/OutputDto.cshtml delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/Templates/PageListDto.cshtml delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/Templates/ServiceImpl.cshtml delete mode 100644 src/Destiny.Core.Flow.CodeGenerator/TypeHelper.cs delete mode 100644 src/Destiny.Core.Flow.Consul/Destiny.Core.Flow.Consul.csproj delete mode 100644 src/Destiny.Core.Flow.Consul/DestinyConsulModule.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/DatabaseTypeAttribute.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/DbContextExtensions.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/DbContextOptionsBuilderExtensions..cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/DbContexts/DbContextBase.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/DbContexts/DefaultDbContext.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/DbDrivens/MySqlDbContextDrivenProvider.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/DbDrivens/SqlServerDbContextDrivenProvider.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Destiny.Core.Flow.EntityFrameworkCore.csproj delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/EntityFrameworkCoreModule.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/IDbContextDrivenProvider.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Interceptor/AuditInterceptor.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/EntityMappingConfigurationOfModel.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/IEntityMappingConfiguration.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/IEntityMappingConfigurationOfModel.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/ModelBuilderExtenions.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Repository.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/DapperRepository.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/IDapperRepository.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/UnitOfWork.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/UnitOfWorkExtensions.cs delete mode 100644 src/Destiny.Core.Flow.EntityFrameworkCore/ServiceExtensions.cs delete mode 100644 src/Destiny.Core.Flow.FluentValidation/Destiny.Core.Flow.FluentValidation.csproj delete mode 100644 src/Destiny.Core.Flow.FluentValidation/FluentModelValidator.cs delete mode 100644 src/Destiny.Core.Flow.FluentValidation/FluentValidationExtensions.cs delete mode 100644 src/Destiny.Core.Flow.FluentValidation/FluentValidationModelValidator.cs delete mode 100644 src/Destiny.Core.Flow.FluentValidation/FluentValidationModuleBase.cs delete mode 100644 src/Destiny.Core.Flow.FluentValidation/ServiceProviderValidatorFactory.cs delete mode 100644 src/Destiny.Core.Flow.GateWay/Destiny.Core.Flow.GateWay.csproj delete mode 100644 src/Destiny.Core.Flow.GateWay/Program.cs delete mode 100644 src/Destiny.Core.Flow.GateWay/Properties/launchSettings.json delete mode 100644 src/Destiny.Core.Flow.GateWay/Startup.cs delete mode 100644 src/Destiny.Core.Flow.GateWay/appsettings.Development.json delete mode 100644 src/Destiny.Core.Flow.GateWay/appsettings.json delete mode 100644 src/Destiny.Core.Flow.GateWay/ocelotconfigure.json delete mode 100644 src/Destiny.Core.Flow.Log4Net/Destiny.Core.Flow.Log4Net.csproj delete mode 100644 src/Destiny.Core.Flow.Log4Net/Log4NetLogger.cs delete mode 100644 src/Destiny.Core.Flow.Log4Net/Log4NetModuleBase.cs delete mode 100644 src/Destiny.Core.Flow.Log4Net/Log4NetProvider.cs delete mode 100644 src/Destiny.Core.Flow.Log4Net/MNZ.CMS.Core.Log4Net.csproj delete mode 100644 src/Destiny.Core.Flow.Log4Net/log4net.config delete mode 100644 src/Destiny.Core.Flow.MiniProfiler/Destiny.Core.Flow.MiniProfiler.csproj delete mode 100644 src/Destiny.Core.Flow.MiniProfiler/MiniProfilerModule.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/DbContexts/DefaultMongoDbContext.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/DbContexts/MongoDbContextBase.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/Destiny.Core.Flow.MongoDB.csproj delete mode 100644 src/Destiny.Core.Flow.MongoDB/FindFluentExtensions.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/FindFluentSortBy.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/Infrastructure/IMongoDbContextOptions.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/Metadata/Builders/MongoDBFilterBuilder.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/MongoCollectionExtensions.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/MongoDBModuleBase.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/MongoDBServiceCollectionExtensions.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/MongoDbContextOptions.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/MongoEntity.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/Repositorys/IMongoDBRepository.cs delete mode 100644 src/Destiny.Core.Flow.MongoDB/Repositorys/MongoDBRepository.cs delete mode 100644 src/Destiny.Core.Flow.Swagger/Destiny.Core.Flow.Swagger.csproj delete mode 100644 src/Destiny.Core.Flow.Swagger/Filter/AutoRestSchemaFilter.cs delete mode 100644 src/Destiny.Core.Flow.Swagger/Filter/TagDescriptionsDocumentFilter.cs delete mode 100644 src/Destiny.Core.Flow.Swagger/SwaggerModule.cs delete mode 100644 src/Destiny.Core.Flow/Application/CrudServiceAsync.cs delete mode 100644 src/Destiny.Core.Flow/Application/ICrudServiceAsync.cs delete mode 100644 src/Destiny.Core.Flow/Attributes/Base/AttributeBase.cs delete mode 100644 src/Destiny.Core.Flow/Attributes/MongoDBTableAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Audit/AuditChange.cs delete mode 100644 src/Destiny.Core.Flow/Audit/AuditEntry.cs delete mode 100644 src/Destiny.Core.Flow/Audit/AuditLog.cs delete mode 100644 src/Destiny.Core.Flow/Audit/AuditPropertysEntry.cs delete mode 100644 src/Destiny.Core.Flow/Audit/DataOperationType.cs delete mode 100644 src/Destiny.Core.Flow/Audit/DisableAuditingAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Audit/Dto/AuditEntryDto.cs delete mode 100644 src/Destiny.Core.Flow/Audit/Dto/AuditEntryOutputPageDto.cs delete mode 100644 src/Destiny.Core.Flow/Audit/Dto/AuditLogOutputPageDto.cs delete mode 100644 src/Destiny.Core.Flow/Audit/Dto/AuditPropertyDto.cs delete mode 100644 src/Destiny.Core.Flow/Audit/Dto/AuditPropertyEntryOutputPageDto.cs delete mode 100644 src/Destiny.Core.Flow/Audit/EntityHistory/AuditHelper.cs delete mode 100644 src/Destiny.Core.Flow/Audit/EntityHistory/IAuditHelper.cs delete mode 100644 src/Destiny.Core.Flow/Audit/IAuditStore.cs delete mode 100644 src/Destiny.Core.Flow/ConsulEntity/ServiceEntity.cs delete mode 100644 src/Destiny.Core.Flow/Data/ComnGuid.cs delete mode 100644 src/Destiny.Core.Flow/Data/Core/Collections/ITypeList.cs delete mode 100644 src/Destiny.Core.Flow/Data/Core/Collections/ITypeListOfModel.cs delete mode 100644 src/Destiny.Core.Flow/Data/Core/Collections/TypeList.cs delete mode 100644 src/Destiny.Core.Flow/Data/Core/Function/FunctionAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Data/Core/Function/FunctionInfo.cs delete mode 100644 src/Destiny.Core.Flow/Data/Dto/SelectItem.cs delete mode 100644 src/Destiny.Core.Flow/Data/LazyConcurrentDictionary.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/DependencyAppModule.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/DependencyAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/DictionaryScoped.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/IScopedDependency.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/IServiceProviderAccessor.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/ISingletonDependency.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/ITransientDependency.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/IgnoreDependencyAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/IocManage.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/LazyFactory.cs delete mode 100644 src/Destiny.Core.Flow/Dependency/ObjectAccessor.cs delete mode 100644 src/Destiny.Core.Flow/Destiny.Core.Flow.csproj delete mode 100644 src/Destiny.Core.Flow/Disposables/IDisposable2.cs delete mode 100644 src/Destiny.Core.Flow/Entity/DatabaseType.cs delete mode 100644 src/Destiny.Core.Flow/Entity/DestinyContextOptionsBuilder.cs delete mode 100644 src/Destiny.Core.Flow/Entity/EntityBase.cs delete mode 100644 src/Destiny.Core.Flow/Entity/ICreatedTime.cs delete mode 100644 src/Destiny.Core.Flow/Entity/ICreationAudited.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IDto.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IEntity.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IEntityExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IEntityOfModel.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IFullAuditedEntityOfModel.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IInputDto.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IModificationAudited.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IModificationTime.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IOutputDto.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IRepository.cs delete mode 100644 src/Destiny.Core.Flow/Entity/ISeedData.cs delete mode 100644 src/Destiny.Core.Flow/Entity/ISoftDelete.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IStateDto.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IUnitOfWork.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IUnitOfWorkAccessor.cs delete mode 100644 src/Destiny.Core.Flow/Entity/IUnitOfWorkManager.cs delete mode 100644 src/Destiny.Core.Flow/Entity/InputDto.cs delete mode 100644 src/Destiny.Core.Flow/Entity/InputWaitStateDto.cs delete mode 100644 src/Destiny.Core.Flow/Entity/Modules/MigrationModuleBase.cs delete mode 100644 src/Destiny.Core.Flow/Entity/OutputDto.cs delete mode 100644 src/Destiny.Core.Flow/Entity/SeedDataBase.cs delete mode 100644 src/Destiny.Core.Flow/Enums/Enums.cs delete mode 100644 src/Destiny.Core.Flow/Events/Abstractions/IEventBase.cs delete mode 100644 src/Destiny.Core.Flow/Events/Abstractions/IEventHandlerBase.cs delete mode 100644 src/Destiny.Core.Flow/Events/CacheEventDataBase.cs delete mode 100644 src/Destiny.Core.Flow/Events/EventBase.cs delete mode 100644 src/Destiny.Core.Flow/Events/EventBus/IEventBus.cs delete mode 100644 src/Destiny.Core.Flow/Events/EventBus/IMediatorHandler.cs delete mode 100644 src/Destiny.Core.Flow/Events/EventBus/InMemoryBus.cs delete mode 100644 src/Destiny.Core.Flow/Events/EventBusExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Events/EventHandlerBase.cs delete mode 100644 src/Destiny.Core.Flow/Events/EventQueue.cs delete mode 100644 src/Destiny.Core.Flow/Events/MediatorAppModule.cs delete mode 100644 src/Destiny.Core.Flow/Events/Notification.cs delete mode 100644 src/Destiny.Core.Flow/Events/NotificationHandlerBase.cs delete mode 100644 src/Destiny.Core.Flow/Exceptions/AppException.cs delete mode 100644 src/Destiny.Core.Flow/Exceptions/MessageBox.cs delete mode 100644 src/Destiny.Core.Flow/Exceptions/MissingTypeRegistrationException.cs delete mode 100644 src/Destiny.Core.Flow/ExpressionUtil/Expressionable.cs delete mode 100644 src/Destiny.Core.Flow/ExpressionUtil/ExtensionMethods.cs delete mode 100644 src/Destiny.Core.Flow/ExpressionUtil/FilterBuilder.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/AutoMapperExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/BooleanWitnBoolExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/CheckExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/ClaimsIdentityExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/CollectionExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/ComparableExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/ControllerExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/DateExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/DbContextExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/EntityEntryExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/EntityExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/EnumExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/ExpressionExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/ExpressionVisitorExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/FileExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/GetIPExtension.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/GuidExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/HashExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/IdentityResultExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/ObjectExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/QueryableExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/SecurityExtension.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/ServiceCollectionExtension.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/ServiceCollectionObjectsExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/ServiceProviderExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/StringExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Extensions/TypeExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Filter/Abstract/IFilterReauest.cs delete mode 100644 src/Destiny.Core.Flow/Filter/Abstract/IFilteredPagedRequest.cs delete mode 100644 src/Destiny.Core.Flow/Filter/Abstract/IOrderRequest.cs delete mode 100644 src/Destiny.Core.Flow/Filter/Abstract/IPagedRequest.cs delete mode 100644 src/Destiny.Core.Flow/Filter/Abstract/IPagedResult.cs delete mode 100644 src/Destiny.Core.Flow/Filter/CollectionPropertySorter.cs delete mode 100644 src/Destiny.Core.Flow/Filter/FilterCodeAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Filter/FilterCondition.cs delete mode 100644 src/Destiny.Core.Flow/Filter/IResultData.cs delete mode 100644 src/Destiny.Core.Flow/Filter/OrderCondition.cs delete mode 100644 src/Destiny.Core.Flow/Filter/PageParameters.cs delete mode 100644 src/Destiny.Core.Flow/Filter/PageRequest.cs delete mode 100644 src/Destiny.Core.Flow/Filter/PageResult.cs delete mode 100644 src/Destiny.Core.Flow/Filter/PagedRequestModel.cs delete mode 100644 src/Destiny.Core.Flow/Filter/QueryFilter.cs delete mode 100644 src/Destiny.Core.Flow/Filter/QueryParameters.cs delete mode 100644 src/Destiny.Core.Flow/Filter/ResultBaseOfModel.cs delete mode 100644 src/Destiny.Core.Flow/Helpers/ArrayHelper.cs delete mode 100644 src/Destiny.Core.Flow/Helpers/DelegateHelper.cs delete mode 100644 src/Destiny.Core.Flow/Helpers/JsonHelper.cs delete mode 100644 src/Destiny.Core.Flow/Helpers/ReflectHelper.cs delete mode 100644 src/Destiny.Core.Flow/Helpers/TypeNameHelper.cs delete mode 100644 src/Destiny.Core.Flow/IdentityServer4/AllowedSigningAlgorithmsConverter.cs delete mode 100644 src/Destiny.Core.Flow/IdentityServer4/GrantType.cs delete mode 100644 src/Destiny.Core.Flow/IdentityServer4/GrantTypes.cs delete mode 100644 src/Destiny.Core.Flow/IdentityServer4/JwtClaimTypes.cs delete mode 100644 src/Destiny.Core.Flow/Mapping/AutoMapDirection.cs delete mode 100644 src/Destiny.Core.Flow/Mapping/AutoMapFromAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Mapping/AutoMapToAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Mapping/AutoMappingAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Modules/AppModule.cs delete mode 100644 src/Destiny.Core.Flow/Modules/AppModuleExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Modules/ApplicationContext.cs delete mode 100644 src/Destiny.Core.Flow/Modules/ApplicationInitializationExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Modules/ConfigureServicesContext.cs delete mode 100644 src/Destiny.Core.Flow/Modules/ConfigureServicesContextExtenstions.cs delete mode 100644 src/Destiny.Core.Flow/Modules/DependsOnAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Modules/IAppModule.cs delete mode 100644 src/Destiny.Core.Flow/Modules/IApplicationInitialization.cs delete mode 100644 src/Destiny.Core.Flow/Modules/IDependedTypesProvider.cs delete mode 100644 src/Destiny.Core.Flow/Modules/IModuleApplication.cs delete mode 100644 src/Destiny.Core.Flow/Modules/IStartupModuleRunner.cs delete mode 100644 src/Destiny.Core.Flow/Modules/ModuleApplicationBase.cs delete mode 100644 src/Destiny.Core.Flow/Modules/StartupModuleRunner.cs delete mode 100644 src/Destiny.Core.Flow/Network/NetworkHelper.cs delete mode 100644 src/Destiny.Core.Flow/Options/AppOptionSettings.cs delete mode 100644 src/Destiny.Core.Flow/Options/AuthOptions.cs delete mode 100644 src/Destiny.Core.Flow/Options/CorsOptions.cs delete mode 100644 src/Destiny.Core.Flow/Options/DestinyContextOptions.cs delete mode 100644 src/Destiny.Core.Flow/Options/JwtOptions.cs delete mode 100644 src/Destiny.Core.Flow/Permission/IAuthorityVerification.cs delete mode 100644 src/Destiny.Core.Flow/Permission/NoAuthorityVerificationAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Reflection/AssemblyFinder.cs delete mode 100644 src/Destiny.Core.Flow/Reflection/AssemblyHelper.cs delete mode 100644 src/Destiny.Core.Flow/Reflection/FinderBase.cs delete mode 100644 src/Destiny.Core.Flow/Reflection/IAssemblyFinder.cs delete mode 100644 src/Destiny.Core.Flow/Reflection/IFinder.cs delete mode 100644 src/Destiny.Core.Flow/Reflection/ITypeFinder.cs delete mode 100644 src/Destiny.Core.Flow/Reflection/TypeFinder.cs delete mode 100644 src/Destiny.Core.Flow/Security/Identity/ClaimTypes.cs delete mode 100644 src/Destiny.Core.Flow/Security/Identity/IdentityProfile.cs delete mode 100644 src/Destiny.Core.Flow/Security/Jwt/IJwtBearerService.cs delete mode 100644 src/Destiny.Core.Flow/Security/Jwt/JwtBearerService.cs delete mode 100644 src/Destiny.Core.Flow/Security/Jwt/JwtResult.cs delete mode 100644 src/Destiny.Core.Flow/Threading/AsyncEx.cs delete mode 100644 src/Destiny.Core.Flow/Threading/BackgroundTasks/BackgroundTaskQueue.cs delete mode 100644 src/Destiny.Core.Flow/Threading/BackgroundTasks/IBackgroundTaskQueue.cs delete mode 100644 src/Destiny.Core.Flow/Threading/ObjectPoolAsync.cs delete mode 100644 src/Destiny.Core.Flow/Threading/TaskResult.cs delete mode 100644 src/Destiny.Core.Flow/Threading/ThreadSafeRandom.cs delete mode 100644 src/Destiny.Core.Flow/Ui/Abstracts/IHasResultType.cs delete mode 100644 src/Destiny.Core.Flow/Ui/Abstracts/IListResult.cs delete mode 100644 src/Destiny.Core.Flow/Ui/Abstracts/ITreeResult.cs delete mode 100644 src/Destiny.Core.Flow/Ui/AuthorizationResult.cs delete mode 100644 src/Destiny.Core.Flow/Ui/MessageDefinitionType.cs delete mode 100644 src/Destiny.Core.Flow/Ui/OperationResponse.cs delete mode 100644 src/Destiny.Core.Flow/Ui/OperationResponseExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Ui/OperationResponseOfModel.cs delete mode 100644 src/Destiny.Core.Flow/Ui/ResultBase.cs delete mode 100644 src/Destiny.Core.Flow/Ui/TreeResult.cs delete mode 100644 src/Destiny.Core.Flow/Validation/Extensions.cs delete mode 100644 src/Destiny.Core.Flow/Validation/IModelValidator.cs delete mode 100644 src/Destiny.Core.Flow/Validation/Interceptor/IMethodParameterValidator.cs delete mode 100644 src/Destiny.Core.Flow/Validation/Interceptor/MethodInvocationValidator.cs delete mode 100644 src/Destiny.Core.Flow/Validation/Interceptor/ModelValidationMethodParameterValidator.cs delete mode 100644 src/Destiny.Core.Flow/Validation/Interceptor/ValidationInterceptorAttribute.cs delete mode 100644 src/Destiny.Core.Flow/Validation/ModelValidationResultExtensions.cs delete mode 100644 src/Destiny.Core.Flow/Validation/ModelValidator.cs delete mode 100644 src/Destiny.Core.Flow/Validation/ValidationException.cs delete mode 100644 src/Destiny.Core.Flow/Validation/ValidationFailure.cs rename {Destiny.Core.Tests => test/Destiny.Core.Tests}/CodeGeneratorTests.cs (100%) rename {Destiny.Core.Tests => test/Destiny.Core.Tests}/Destiny.Core.Tests.csproj (76%) rename {Destiny.Core.Tests => test/Destiny.Core.Tests}/MemoryTests.cs (100%) rename {Destiny.Core.Tests => test/Destiny.Core.Tests}/MongoDBTests.cs (95%) rename {Destiny.Core.Tests => test/Destiny.Core.Tests}/StartupModulesTest.cs (100%) rename {Destiny.Core.Tests => test/Destiny.Core.Tests}/appsettings.json (100%) diff --git a/Destiny.Core.Flow.sln b/Destiny.Core.Flow.sln index 27fc2a33..ea7644e9 100644 --- a/Destiny.Core.Flow.sln +++ b/Destiny.Core.Flow.sln @@ -11,22 +11,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Services" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Model", "src\Destiny.Core.Flow.Model\Destiny.Core.Flow.Model.csproj", "{3350DDC6-02D0-4986-9F13-17B8B94B9456}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow", "src\Destiny.Core.Flow\Destiny.Core.Flow.csproj", "{49FF2838-ED54-48FF-A8C4-C0F91F1EB872}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Log4Net", "src\Destiny.Core.Flow.Log4Net\Destiny.Core.Flow.Log4Net.csproj", "{DC68A647-D7C2-4321-BDC7-ED8F65CD6A5C}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.AutoMapper", "src\Destiny.Core.Flow.AutoMapper\Destiny.Core.Flow.AutoMapper.csproj", "{1BEA2CF0-145B-4B0C-ABDC-A429E40E5890}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Tests", "Destiny.Core.Tests\Destiny.Core.Tests.csproj", "{57C6446B-F401-402D-9BAD-4CB9302AA344}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Tests", "test\Destiny.Core.Tests\Destiny.Core.Tests.csproj", "{57C6446B-F401-402D-9BAD-4CB9302AA344}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.SeriLog", "src\Destiny.Core.Flow.SeriLog\Destiny.Core.Flow.SeriLog.csproj", "{41EB9B3E-C420-4EFD-86CB-6D292EDF7AEF}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Swagger", "src\Destiny.Core.Flow.Swagger\Destiny.Core.Flow.Swagger.csproj", "{6F852563-D024-40F5-93E4-4A84EF87EEA1}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Identitys", "src\Destiny.Core.Flow.Identity\Destiny.Core.Flow.Identitys.csproj", "{40DA34CA-8A05-40E9-9542-596D6291D3A8}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.EntityFrameworkCore", "src\Destiny.Core.Flow.EntityFrameworkCore\Destiny.Core.Flow.EntityFrameworkCore.csproj", "{009E18C9-38CE-4CE0-9EA0-D9A1AB38DE86}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{1249687C-582B-4A3E-8090-2AAF36AA3284}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{B74CBBDD-8574-4768-AA9D-2144A77D4875}" @@ -37,40 +27,20 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Dtos", "s EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Repository", "src\Destiny.Core.Flow.Repository\Destiny.Core.Flow.Repository.csproj", "{88F5FAB5-5125-43FE-A889-510B7D085F7D}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.FluentValidation", "src\Destiny.Core.Flow.FluentValidation\Destiny.Core.Flow.FluentValidation.csproj", "{C59766D4-9399-4048-81AD-67626B3CD87B}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Moduls", "Moduls", "{D49782B1-99E0-442F-98DD-6D30CD09F6BA}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Business", "Business", "{5D6E6ADE-8C66-4955-9DC6-C8610EDE9DE6}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastructure", "{968F74F4-4D0A-4832-A7EA-5CB2BA08AF8A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.CodeGenerator", "src\Destiny.Core.Flow.CodeGenerator\Destiny.Core.Flow.CodeGenerator.csproj", "{6DC5B2C0-756B-4BCC-8614-9C21D5671F8E}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Aop", "src\Destiny.Core.Flow.Aop\Destiny.Core.Flow.Aop.csproj", "{41EBC4A1-09C2-4426-937B-441B0EF62767}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.MongoDB", "src\Destiny.Core.Flow.MongoDB\Destiny.Core.Flow.MongoDB.csproj", "{D8E15451-16A4-4769-9BFA-A38C6237715B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.GateWay", "src\Destiny.Core.Flow.GateWay\Destiny.Core.Flow.GateWay.csproj", "{3DD6B93E-872B-4F11-B968-DDC88C0E0C3A}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Caching", "src\Destiny.Core.Flow.Caching\Destiny.Core.Flow.Caching.csproj", "{951EDF2A-119D-407B-A8FB-13D4F757D6F4}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Caching.CSRedis", "src\Destiny.Core.Flow.Caching.CSRedis\Destiny.Core.Flow.Caching.CSRedis.csproj", "{1B1CE807-2090-40B0-A6C5-326A9F6543C1}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.TestBase", "src\Destiny.Core.Flow.TestBase\Destiny.Core.Flow.TestBase.csproj", "{7D118558-7701-4804-A42D-C0C81FC394D6}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.Consul", "src\Destiny.Core.Flow.Consul\Destiny.Core.Flow.Consul.csproj", "{43BB4E0A-BAFF-41D1-85FC-AA894627A9DF}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.IdentityServer", "src\Destiny.Core.Flow.IdentityServer4\Destiny.Core.Flow.IdentityServer.csproj", "{501DC32B-2705-4713-A8C3-9C6842996707}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.IdentityServer.Entities", "src\Destiny.Core.Flow.IdentityServer.Entities\Destiny.Core.Flow.IdentityServer.Entities.csproj", "{F7C19E76-E205-4549-8A15-A95107213C64}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.AuthenticationCenter", "src\Destiny.Core.Flow.AuthenticationCenter\Destiny.Core.Flow.AuthenticationCenter.csproj", "{4D580BFD-1D8A-4A23-B152-5A6739F26C97}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.MiniProfiler", "src\Destiny.Core.Flow.MiniProfiler\Destiny.Core.Flow.MiniProfiler.csproj", "{BF84625C-82CB-4F84-A799-F21F81E563F1}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny.Core.Flow.AspNetCore", "src\Destiny.Core.Flow.AspNetCore\Destiny.Core.Flow.AspNetCore.csproj", "{40BACBCF-713A-4F38-ABE8-57B6BC3EC7A2}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -93,18 +63,6 @@ Global {3350DDC6-02D0-4986-9F13-17B8B94B9456}.Debug|Any CPU.Build.0 = Debug|Any CPU {3350DDC6-02D0-4986-9F13-17B8B94B9456}.Release|Any CPU.ActiveCfg = Release|Any CPU {3350DDC6-02D0-4986-9F13-17B8B94B9456}.Release|Any CPU.Build.0 = Release|Any CPU - {49FF2838-ED54-48FF-A8C4-C0F91F1EB872}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {49FF2838-ED54-48FF-A8C4-C0F91F1EB872}.Debug|Any CPU.Build.0 = Debug|Any CPU - {49FF2838-ED54-48FF-A8C4-C0F91F1EB872}.Release|Any CPU.ActiveCfg = Release|Any CPU - {49FF2838-ED54-48FF-A8C4-C0F91F1EB872}.Release|Any CPU.Build.0 = Release|Any CPU - {DC68A647-D7C2-4321-BDC7-ED8F65CD6A5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DC68A647-D7C2-4321-BDC7-ED8F65CD6A5C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DC68A647-D7C2-4321-BDC7-ED8F65CD6A5C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DC68A647-D7C2-4321-BDC7-ED8F65CD6A5C}.Release|Any CPU.Build.0 = Release|Any CPU - {1BEA2CF0-145B-4B0C-ABDC-A429E40E5890}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1BEA2CF0-145B-4B0C-ABDC-A429E40E5890}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1BEA2CF0-145B-4B0C-ABDC-A429E40E5890}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1BEA2CF0-145B-4B0C-ABDC-A429E40E5890}.Release|Any CPU.Build.0 = Release|Any CPU {57C6446B-F401-402D-9BAD-4CB9302AA344}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {57C6446B-F401-402D-9BAD-4CB9302AA344}.Debug|Any CPU.Build.0 = Debug|Any CPU {57C6446B-F401-402D-9BAD-4CB9302AA344}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -113,18 +71,10 @@ Global {41EB9B3E-C420-4EFD-86CB-6D292EDF7AEF}.Debug|Any CPU.Build.0 = Debug|Any CPU {41EB9B3E-C420-4EFD-86CB-6D292EDF7AEF}.Release|Any CPU.ActiveCfg = Release|Any CPU {41EB9B3E-C420-4EFD-86CB-6D292EDF7AEF}.Release|Any CPU.Build.0 = Release|Any CPU - {6F852563-D024-40F5-93E4-4A84EF87EEA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6F852563-D024-40F5-93E4-4A84EF87EEA1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6F852563-D024-40F5-93E4-4A84EF87EEA1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6F852563-D024-40F5-93E4-4A84EF87EEA1}.Release|Any CPU.Build.0 = Release|Any CPU {40DA34CA-8A05-40E9-9542-596D6291D3A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {40DA34CA-8A05-40E9-9542-596D6291D3A8}.Debug|Any CPU.Build.0 = Debug|Any CPU {40DA34CA-8A05-40E9-9542-596D6291D3A8}.Release|Any CPU.ActiveCfg = Release|Any CPU {40DA34CA-8A05-40E9-9542-596D6291D3A8}.Release|Any CPU.Build.0 = Release|Any CPU - {009E18C9-38CE-4CE0-9EA0-D9A1AB38DE86}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {009E18C9-38CE-4CE0-9EA0-D9A1AB38DE86}.Debug|Any CPU.Build.0 = Debug|Any CPU - {009E18C9-38CE-4CE0-9EA0-D9A1AB38DE86}.Release|Any CPU.ActiveCfg = Release|Any CPU - {009E18C9-38CE-4CE0-9EA0-D9A1AB38DE86}.Release|Any CPU.Build.0 = Release|Any CPU {9DFDA589-61A2-46E6-ACB6-6C8D1B987F0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9DFDA589-61A2-46E6-ACB6-6C8D1B987F0D}.Debug|Any CPU.Build.0 = Debug|Any CPU {9DFDA589-61A2-46E6-ACB6-6C8D1B987F0D}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -133,42 +83,10 @@ Global {88F5FAB5-5125-43FE-A889-510B7D085F7D}.Debug|Any CPU.Build.0 = Debug|Any CPU {88F5FAB5-5125-43FE-A889-510B7D085F7D}.Release|Any CPU.ActiveCfg = Release|Any CPU {88F5FAB5-5125-43FE-A889-510B7D085F7D}.Release|Any CPU.Build.0 = Release|Any CPU - {C59766D4-9399-4048-81AD-67626B3CD87B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C59766D4-9399-4048-81AD-67626B3CD87B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C59766D4-9399-4048-81AD-67626B3CD87B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C59766D4-9399-4048-81AD-67626B3CD87B}.Release|Any CPU.Build.0 = Release|Any CPU - {6DC5B2C0-756B-4BCC-8614-9C21D5671F8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6DC5B2C0-756B-4BCC-8614-9C21D5671F8E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6DC5B2C0-756B-4BCC-8614-9C21D5671F8E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6DC5B2C0-756B-4BCC-8614-9C21D5671F8E}.Release|Any CPU.Build.0 = Release|Any CPU - {41EBC4A1-09C2-4426-937B-441B0EF62767}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {41EBC4A1-09C2-4426-937B-441B0EF62767}.Debug|Any CPU.Build.0 = Debug|Any CPU - {41EBC4A1-09C2-4426-937B-441B0EF62767}.Release|Any CPU.ActiveCfg = Release|Any CPU - {41EBC4A1-09C2-4426-937B-441B0EF62767}.Release|Any CPU.Build.0 = Release|Any CPU - {D8E15451-16A4-4769-9BFA-A38C6237715B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D8E15451-16A4-4769-9BFA-A38C6237715B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D8E15451-16A4-4769-9BFA-A38C6237715B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D8E15451-16A4-4769-9BFA-A38C6237715B}.Release|Any CPU.Build.0 = Release|Any CPU - {3DD6B93E-872B-4F11-B968-DDC88C0E0C3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3DD6B93E-872B-4F11-B968-DDC88C0E0C3A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3DD6B93E-872B-4F11-B968-DDC88C0E0C3A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3DD6B93E-872B-4F11-B968-DDC88C0E0C3A}.Release|Any CPU.Build.0 = Release|Any CPU - {951EDF2A-119D-407B-A8FB-13D4F757D6F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {951EDF2A-119D-407B-A8FB-13D4F757D6F4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {951EDF2A-119D-407B-A8FB-13D4F757D6F4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {951EDF2A-119D-407B-A8FB-13D4F757D6F4}.Release|Any CPU.Build.0 = Release|Any CPU - {1B1CE807-2090-40B0-A6C5-326A9F6543C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1B1CE807-2090-40B0-A6C5-326A9F6543C1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1B1CE807-2090-40B0-A6C5-326A9F6543C1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1B1CE807-2090-40B0-A6C5-326A9F6543C1}.Release|Any CPU.Build.0 = Release|Any CPU {7D118558-7701-4804-A42D-C0C81FC394D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7D118558-7701-4804-A42D-C0C81FC394D6}.Debug|Any CPU.Build.0 = Debug|Any CPU {7D118558-7701-4804-A42D-C0C81FC394D6}.Release|Any CPU.ActiveCfg = Release|Any CPU {7D118558-7701-4804-A42D-C0C81FC394D6}.Release|Any CPU.Build.0 = Release|Any CPU - {43BB4E0A-BAFF-41D1-85FC-AA894627A9DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {43BB4E0A-BAFF-41D1-85FC-AA894627A9DF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {43BB4E0A-BAFF-41D1-85FC-AA894627A9DF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {43BB4E0A-BAFF-41D1-85FC-AA894627A9DF}.Release|Any CPU.Build.0 = Release|Any CPU {501DC32B-2705-4713-A8C3-9C6842996707}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {501DC32B-2705-4713-A8C3-9C6842996707}.Debug|Any CPU.Build.0 = Debug|Any CPU {501DC32B-2705-4713-A8C3-9C6842996707}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -181,14 +99,6 @@ Global {4D580BFD-1D8A-4A23-B152-5A6739F26C97}.Debug|Any CPU.Build.0 = Debug|Any CPU {4D580BFD-1D8A-4A23-B152-5A6739F26C97}.Release|Any CPU.ActiveCfg = Release|Any CPU {4D580BFD-1D8A-4A23-B152-5A6739F26C97}.Release|Any CPU.Build.0 = Release|Any CPU - {BF84625C-82CB-4F84-A799-F21F81E563F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BF84625C-82CB-4F84-A799-F21F81E563F1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BF84625C-82CB-4F84-A799-F21F81E563F1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BF84625C-82CB-4F84-A799-F21F81E563F1}.Release|Any CPU.Build.0 = Release|Any CPU - {40BACBCF-713A-4F38-ABE8-57B6BC3EC7A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {40BACBCF-713A-4F38-ABE8-57B6BC3EC7A2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {40BACBCF-713A-4F38-ABE8-57B6BC3EC7A2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {40BACBCF-713A-4F38-ABE8-57B6BC3EC7A2}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -198,34 +108,19 @@ Global {0FDF7DC0-77FE-4529-8E8C-D17FF03D84A0} = {5D6E6ADE-8C66-4955-9DC6-C8610EDE9DE6} {89D24E5C-7C65-4150-AB7B-656809CC6011} = {5D6E6ADE-8C66-4955-9DC6-C8610EDE9DE6} {3350DDC6-02D0-4986-9F13-17B8B94B9456} = {5D6E6ADE-8C66-4955-9DC6-C8610EDE9DE6} - {49FF2838-ED54-48FF-A8C4-C0F91F1EB872} = {968F74F4-4D0A-4832-A7EA-5CB2BA08AF8A} - {DC68A647-D7C2-4321-BDC7-ED8F65CD6A5C} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} - {1BEA2CF0-145B-4B0C-ABDC-A429E40E5890} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} {57C6446B-F401-402D-9BAD-4CB9302AA344} = {B74CBBDD-8574-4768-AA9D-2144A77D4875} {41EB9B3E-C420-4EFD-86CB-6D292EDF7AEF} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} - {6F852563-D024-40F5-93E4-4A84EF87EEA1} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} {40DA34CA-8A05-40E9-9542-596D6291D3A8} = {968F74F4-4D0A-4832-A7EA-5CB2BA08AF8A} - {009E18C9-38CE-4CE0-9EA0-D9A1AB38DE86} = {968F74F4-4D0A-4832-A7EA-5CB2BA08AF8A} {9A347066-1CEA-4FD6-BD7E-598A7FF21E6C} = {1249687C-582B-4A3E-8090-2AAF36AA3284} {9DFDA589-61A2-46E6-ACB6-6C8D1B987F0D} = {5D6E6ADE-8C66-4955-9DC6-C8610EDE9DE6} {88F5FAB5-5125-43FE-A889-510B7D085F7D} = {5D6E6ADE-8C66-4955-9DC6-C8610EDE9DE6} - {C59766D4-9399-4048-81AD-67626B3CD87B} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} {D49782B1-99E0-442F-98DD-6D30CD09F6BA} = {1249687C-582B-4A3E-8090-2AAF36AA3284} {5D6E6ADE-8C66-4955-9DC6-C8610EDE9DE6} = {1249687C-582B-4A3E-8090-2AAF36AA3284} {968F74F4-4D0A-4832-A7EA-5CB2BA08AF8A} = {1249687C-582B-4A3E-8090-2AAF36AA3284} - {6DC5B2C0-756B-4BCC-8614-9C21D5671F8E} = {968F74F4-4D0A-4832-A7EA-5CB2BA08AF8A} - {41EBC4A1-09C2-4426-937B-441B0EF62767} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} - {D8E15451-16A4-4769-9BFA-A38C6237715B} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} - {3DD6B93E-872B-4F11-B968-DDC88C0E0C3A} = {9A347066-1CEA-4FD6-BD7E-598A7FF21E6C} - {951EDF2A-119D-407B-A8FB-13D4F757D6F4} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} - {1B1CE807-2090-40B0-A6C5-326A9F6543C1} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} {7D118558-7701-4804-A42D-C0C81FC394D6} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} - {43BB4E0A-BAFF-41D1-85FC-AA894627A9DF} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} {501DC32B-2705-4713-A8C3-9C6842996707} = {968F74F4-4D0A-4832-A7EA-5CB2BA08AF8A} {F7C19E76-E205-4549-8A15-A95107213C64} = {968F74F4-4D0A-4832-A7EA-5CB2BA08AF8A} {4D580BFD-1D8A-4A23-B152-5A6739F26C97} = {9A347066-1CEA-4FD6-BD7E-598A7FF21E6C} - {BF84625C-82CB-4F84-A799-F21F81E563F1} = {D49782B1-99E0-442F-98DD-6D30CD09F6BA} - {40BACBCF-713A-4F38-ABE8-57B6BC3EC7A2} = {968F74F4-4D0A-4832-A7EA-5CB2BA08AF8A} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {468F450C-837F-4FCD-8E06-3E12690DDED6} diff --git a/K8sdeploy/destiny-core-flowadmin-autoscaler.yaml b/K8sdeploy/destiny-core-flowadmin-autoscaler.yaml new file mode 100644 index 00000000..b315bcf4 --- /dev/null +++ b/K8sdeploy/destiny-core-flowadmin-autoscaler.yaml @@ -0,0 +1,13 @@ +apiVersion: autoscaling/v1 +kind: HorizontalPodAutoscaler +metadata: + name: destiny-core-flowadmin-autoscaler + namespace: destinycore-flow +spec: + maxReplicas: 10 #最大数量 + minReplicas: 2 #最小数量 + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: destiny-core-flowadmin-pod #需要监控的deployment + targetCPUUtilizationPercentage: 40 #目标CPU占用率达到多少启动扩容 \ No newline at end of file diff --git a/src/Destiny.Core.Flow.API/Controllers/DocumentTypeController.cs b/src/Destiny.Core.Flow.API/Controllers/DocumentTypeController.cs index 7c287f5d..524fe744 100644 --- a/src/Destiny.Core.Flow.API/Controllers/DocumentTypeController.cs +++ b/src/Destiny.Core.Flow.API/Controllers/DocumentTypeController.cs @@ -19,17 +19,15 @@ namespace Destiny.Core.Flow.API.Controllers ///文档类型 /// [Description("文档类型")] + [AllowAnonymous] public class DocumentTypeController : AdminControllerBase { private readonly IDocumentTypeService _documentTypeService; - public DocumentTypeController(IDocumentTypeService documentTypeService) { _documentTypeService=documentTypeService; } - - /// /// 异步创建或更新文档类型 /// @@ -41,10 +39,6 @@ public async Task CreateOrUpdateAsync([FromBody] DocumentTypeInputDt return (await _documentTypeService.CreateOrUpdateAsync(dto)).ToAjaxResult(); } - - - - /// /// 异步加载表单文档类型 /// @@ -55,8 +49,6 @@ public async Task LoadFormAsync(Guid id) { return (await _documentTypeService.LoadFormAsync(id)).ToAjaxResult(); } - - /// /// 异步删除文档类型 /// @@ -67,7 +59,6 @@ public async Task DeleteAsync(Guid id) { return (await _documentTypeService.DeleteAsync(id)).ToAjaxResult(); } - /// /// 异步得到文档类型分页数据 /// @@ -78,7 +69,6 @@ public async Task> GetPageAsync(PageRequest re { return (await _documentTypeService.GetPageAsync(request)).ToPageList(); } - /// /// 异步得到文档类型树数据 /// @@ -90,6 +80,5 @@ public async Task> GetDocumentTreeTreeDataAsync() return (await _documentTypeService.GetTreeDataAsync()).ToTreeModel(); } - } } diff --git a/src/Destiny.Core.Flow.API/Controllers/Menu/MenuController.cs b/src/Destiny.Core.Flow.API/Controllers/Menu/MenuController.cs index 03d54f45..7d17bb38 100644 --- a/src/Destiny.Core.Flow.API/Controllers/Menu/MenuController.cs +++ b/src/Destiny.Core.Flow.API/Controllers/Menu/MenuController.cs @@ -1,221 +1,218 @@ -using Destiny.Core.Flow.AspNetCore.Api; -using Destiny.Core.Flow.AspNetCore.Ui; -using Destiny.Core.Flow.Audit; -using Destiny.Core.Flow.Dtos.Menu; -using Destiny.Core.Flow.Dtos.MenuFunction; -using Destiny.Core.Flow.Filter; -using Destiny.Core.Flow.IServices.IMenu; -using Destiny.Core.Flow.Permission; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System; -using System.ComponentModel; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; - -namespace Destiny.Core.Flow.API.Controllers.Menu -{ - /// - /// 菜单管理 - /// - [Description("菜单管理")] - - public class MenuController : AdminControllerBase - { - private readonly IMenuServices _menuServices; - private readonly IMenuFunctionServices _menuFunctionServices; - private readonly Microsoft.Extensions.Logging.ILogger _logger = null; - public MenuController(IMenuServices menuServices, IMenuFunctionServices menuFunctionServices, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) - { - _menuServices = menuServices; - _menuFunctionServices = menuFunctionServices; - _logger = loggerFactory.CreateLogger(); - } - - - ///// - ///// 根据角色Id获取树形菜单信息 - ///// - ///// 角色Id - ///// - //[HttpGet] - //[Description("获取树形菜单信息")] - //public async Task> GetTreeAsync(Guid roleid) - //{ - // var result = await _menuServices.GetMenuAsync(roleid); - // return result.ToTreeModel(); - //} - /// - /// 获取表格菜单信息 - /// - /// - /// - [HttpGet] - [Description("获取表格菜单信息")] - [AllowAnonymous] - public async Task> GetTableAsync() - { - var result = await _menuServices.GetMenuTableAsync(); - return new TreeModel() - { - ItemList = result.ItemList, - Message = result.Message, - Success = result.Success - }; - } - - /// - /// 添加菜单 - /// - /// - [HttpPost] - [Description("添加菜单")] - - public async Task AddMenuAsync([FromBody] MenuInputDto dto) - { - return (await _menuServices.CreateAsync(dto)).ToAjaxResult(); - } - - /// - /// 修改菜单 - /// - /// - [HttpPut] - [Description("修改菜单")] - public async Task UpdateMenuAsync([FromBody] MenuInputDto dto) - { - return (await _menuServices.UpdateAsync(dto)).ToAjaxResult(); - } - /// - /// 删除 - /// - /// - [HttpDelete] - [Description("删除菜单")] - public async Task DeleteAsync(Guid? id) - { - return (await _menuServices.DeleteAsync(id.Value)).ToAjaxResult(); - } - - - /// - /// 异步加载表单菜单 - /// - /// - /// - [HttpGet] - [Description("获取一个菜单")] - public async Task LoadFormMenuAsync(Guid Id) - { - return (await _menuServices.LoadFormMenuAsync(Id)).ToAjaxResult(); - } - - /// - /// 登录成功之后获取菜单 - /// - /// - [HttpGet] - [Description("根据登录账号获取菜单")] - [NoAuthorityVerification] - public async Task GetMenuAsync() - { - return (await _menuServices.GetMenuAsync()).ToAjaxResult(); - } - - /// - /// 登录成功之后获取Vue动态路由菜单 - /// - /// - [HttpGet] - [Description("获取Vue动态路由菜单")] - [NoAuthorityVerification] - [DisableAuditing] - public async Task GetVueDynamicRouterTreeAsync() - { - _logger.LogInformation("进入动态路由控制器"); - return (await _menuServices.GetVueDynamicRouterTreeAsync()).ToAjaxResult(); - } - - /// - /// 异步得到菜单树数据 - /// - /// - [HttpGet] - [Description("异步得到菜单树数据")] - - public async Task GetMenuTreeAsync(Guid? roleId) - { - return (await _menuServices.GetMenuTreeAsync(roleId)).ToAjaxResult(); - } - - /// - /// 异步得到菜单下的按钮 - /// - /// - [HttpGet] - [Description("异步得到菜单下的按钮")] - [NoAuthorityVerification] - - public async Task GetMenuChildrenButtonAsync(Guid? menuId) - { - return (await _menuServices.GetMenuChildrenButton(menuId.Value)).ToAjaxResult(); - } - - /// - /// 获取登录用户权限菜单 - /// - /// - [HttpGet] - [Description("获取登录用户权限菜单")] - [NoAuthorityVerification] - - public async Task GetMenuListAsync() - { - return (await _menuServices.GetMenuListAsync()).ToAjaxResult(); - } - - - - /// - /// 异步得到菜单分页数据(不是树,只是普通表格) - /// - /// 请求参数 - /// - - [HttpPost] - [Description("异步得到菜单分页数据")] - - public async Task> GetMenuPageAsync([FromBody] PageRequest request) - { - - return (await _menuServices.GetMenuPageAsync(request)).ToPageList(); - - } - - /// - /// 异步得到所有菜单 - /// - /// - [HttpGet] - [Description("异步得到所有菜单")] - - public async Task> GetAllMenuTreeAsync() - { - - return (await _menuServices.GetAllMenuTreeAsync()).ToTreeModel(); +using Destiny.Core.Flow.AspNetCore.Api; +using Destiny.Core.Flow.AspNetCore.Ui; +using Destiny.Core.Flow.Audit; +using Destiny.Core.Flow.Dtos.Menu; +using Destiny.Core.Flow.Dtos.MenuFunction; +using Destiny.Core.Flow.Filter; +using Destiny.Core.Flow.IServices.IMenu; +using Destiny.Core.Flow.Permission; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System; +using System.ComponentModel; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace Destiny.Core.Flow.API.Controllers.Menu +{ + /// + /// 菜单管理 + /// + [Description("菜单管理")] + + public class MenuController : AdminControllerBase + { + private readonly IMenuServices _menuServices; + private readonly IMenuFunctionServices _menuFunctionServices; + private readonly Microsoft.Extensions.Logging.ILogger _logger = null; + public MenuController(IMenuServices menuServices, IMenuFunctionServices menuFunctionServices, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) + { + _menuServices = menuServices; + _menuFunctionServices = menuFunctionServices; + _logger = loggerFactory.CreateLogger(); } - [HttpGet] - [Description("清除VUE动态路由缓存")] + + ///// + ///// 根据角色Id获取树形菜单信息 + ///// + ///// 角色Id + ///// + //[HttpGet] + //[Description("获取树形菜单信息")] + //public async Task> GetTreeAsync(Guid roleid) + //{ + // var result = await _menuServices.GetMenuAsync(roleid); + // return result.ToTreeModel(); + //} /// - /// 清除VUE动态路由缓存 + /// 获取表格菜单信息 /// - /// - public async Task CleanVueDynamicRouterCache() + /// + /// + [HttpGet] + [Description("获取表格菜单信息")] + [AllowAnonymous] + public async Task> GetTableAsync() { + var result = await _menuServices.GetMenuTableAsync(); + return new TreeModel() + { + ItemList = result.ItemList, + Message = result.Message, + Success = result.Success + }; + } + /// + /// 添加菜单 + /// + /// + [HttpPost] + [Description("添加菜单")] - return (await _menuServices.CleanVueDynamicRouterCache()).ToAjaxResult(); - } - } + public async Task AddMenuAsync([FromBody] MenuInputDto dto) + { + return (await _menuServices.CreateAsync(dto)).ToAjaxResult(); + } + + /// + /// 修改菜单 + /// + /// + [HttpPut] + [Description("修改菜单")] + public async Task UpdateMenuAsync([FromBody] MenuInputDto dto) + { + return (await _menuServices.UpdateAsync(dto)).ToAjaxResult(); + } + /// + /// 删除 + /// + /// + [HttpDelete] + [Description("删除菜单")] + public async Task DeleteAsync(Guid? id) + { + return (await _menuServices.DeleteAsync(id.Value)).ToAjaxResult(); + } + + + /// + /// 异步加载表单菜单 + /// + /// + /// + [HttpGet] + [Description("获取一个菜单")] + public async Task LoadFormMenuAsync(Guid Id) + { + return (await _menuServices.LoadFormMenuAsync(Id)).ToAjaxResult(); + } + + /// + /// 登录成功之后获取菜单 + /// + /// + [HttpGet] + [Description("根据登录账号获取菜单")] + [NoAuthorityVerification] + public async Task GetMenuAsync() + { + return (await _menuServices.GetMenuAsync()).ToAjaxResult(); + } + + /// + /// 登录成功之后获取Vue动态路由菜单 + /// + /// + [HttpGet] + [Description("获取Vue动态路由菜单")] + [NoAuthorityVerification] + [DisableAuditing] + public async Task GetVueDynamicRouterTreeAsync() + { + _logger.LogInformation("进入动态路由控制器"); + return (await _menuServices.GetVueDynamicRouterTreeAsync()).ToAjaxResult(); + } + + /// + /// 异步得到菜单树数据 + /// + /// + [HttpGet] + [Description("异步得到菜单树数据")] + + public async Task GetMenuTreeAsync(Guid? roleId) + { + return (await _menuServices.GetMenuTreeAsync(roleId)).ToAjaxResult(); + } + + /// + /// 异步得到菜单下的按钮 + /// + /// + [HttpGet] + [Description("异步得到菜单下的按钮")] + [NoAuthorityVerification] + + public async Task GetMenuChildrenButtonAsync(Guid? menuId) + { + return (await _menuServices.GetMenuChildrenButton(menuId.Value)).ToAjaxResult(); + } + + /// + /// 获取登录用户权限菜单 + /// + /// + [HttpGet] + [Description("获取登录用户权限菜单")] + [NoAuthorityVerification] + + public async Task GetMenuListAsync() + { + return (await _menuServices.GetMenuListAsync()).ToAjaxResult(); + } + + + + /// + /// 异步得到菜单分页数据(不是树,只是普通表格) + /// + /// 请求参数 + /// + + [HttpPost] + [Description("异步得到菜单分页数据")] + + public async Task> GetMenuPageAsync([FromBody] PageRequest request) + { + + return (await _menuServices.GetMenuPageAsync(request)).ToPageList(); + + } + + /// + /// 异步得到所有菜单 + /// + /// + [HttpGet] + [Description("异步得到所有菜单")] + + public async Task> GetAllMenuTreeAsync() + { + + return (await _menuServices.GetAllMenuTreeAsync()).ToTreeModel(); + } + /// + /// 清除VUE动态路由缓存 + /// + /// + [HttpGet] + [Description("清除VUE动态路由缓存")] + public async Task CleanVueDynamicRouterCache() + { + return (await _menuServices.CleanVueDynamicRouterCache()).ToAjaxResult(); + } + } } \ No newline at end of file diff --git a/src/Destiny.Core.Flow.API/Destiny.Core.Flow.API.csproj b/src/Destiny.Core.Flow.API/Destiny.Core.Flow.API.csproj index b07c63ee..ba3f9c51 100644 --- a/src/Destiny.Core.Flow.API/Destiny.Core.Flow.API.csproj +++ b/src/Destiny.Core.Flow.API/Destiny.Core.Flow.API.csproj @@ -32,6 +32,12 @@ + + + + + + @@ -50,19 +56,12 @@ - - - - - - - diff --git a/src/Destiny.Core.Flow.API/Destiny.Core.Flow.API.xml b/src/Destiny.Core.Flow.API/Destiny.Core.Flow.API.xml index ce96552c..15df0e5a 100644 --- a/src/Destiny.Core.Flow.API/Destiny.Core.Flow.API.xml +++ b/src/Destiny.Core.Flow.API/Destiny.Core.Flow.API.xml @@ -486,6 +486,12 @@ + + + 清除VUE动态路由缓存 + + + 组织架构管理 diff --git a/src/Destiny.Core.Flow.API/Properties/PublishProfiles/FolderProfile.pubxml.user b/src/Destiny.Core.Flow.API/Properties/PublishProfiles/FolderProfile.pubxml.user index 9dfc9966..8fe06b29 100644 --- a/src/Destiny.Core.Flow.API/Properties/PublishProfiles/FolderProfile.pubxml.user +++ b/src/Destiny.Core.Flow.API/Properties/PublishProfiles/FolderProfile.pubxml.user @@ -5,6 +5,6 @@ https://go.microsoft.com/fwlink/?LinkID=208121. <_PublishTargetUrl>F:\Github\Destiny.Core.Flow\src\Destiny.Core.Flow.API\bin\Release\net5.0\publish\ - True|2021-05-13T15:22:19.0487184Z;True|2021-04-18T22:35:28.3562042+08:00;True|2021-04-18T22:13:33.7933765+08:00;True|2021-04-18T21:41:02.2325343+08:00;True|2021-04-18T21:40:39.9242295+08:00;False|2021-04-18T21:40:00.6560711+08:00;True|2021-04-18T21:39:44.5612093+08:00;True|2021-04-18T21:37:41.3596322+08:00; + True|2021-05-27T02:30:33.3101285Z;True|2021-05-13T23:22:19.0487184+08:00;True|2021-04-18T22:35:28.3562042+08:00;True|2021-04-18T22:13:33.7933765+08:00;True|2021-04-18T21:41:02.2325343+08:00;True|2021-04-18T21:40:39.9242295+08:00;False|2021-04-18T21:40:00.6560711+08:00;True|2021-04-18T21:39:44.5612093+08:00;True|2021-04-18T21:37:41.3596322+08:00; \ No newline at end of file diff --git a/src/Destiny.Core.Flow.API/Startup.cs b/src/Destiny.Core.Flow.API/Startup.cs index d585e8b0..5bbab769 100644 --- a/src/Destiny.Core.Flow.API/Startup.cs +++ b/src/Destiny.Core.Flow.API/Startup.cs @@ -7,6 +7,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; namespace Destiny.Core.Flow.API { @@ -22,6 +25,18 @@ public Startup(IConfiguration configuration) // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { + //string[] filters = + //{ + // "mscorlib", + // "netstandard", + // "dotnet", + // "api-ms-win-core", + // "runtime.", + // "System", + // "Microsoft", + // "Window", + //}; + //IEnumerable allAssemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies().Where(x => !filters.Any(x.Name.StartsWith)).Select(Assembly.Load).ToArray(); services.AddApplication(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/src/Destiny.Core.Flow.API/Startups/AppWebModule.cs b/src/Destiny.Core.Flow.API/Startups/AppWebModule.cs index 5950d5ba..3225d0e3 100644 --- a/src/Destiny.Core.Flow.API/Startups/AppWebModule.cs +++ b/src/Destiny.Core.Flow.API/Startups/AppWebModule.cs @@ -15,7 +15,8 @@ namespace Destiny.Core.Flow.API.Startups { - [DependsOn(typeof(DestinyCoreModule), + [DependsOn + (typeof(DestinyCoreModule), typeof(MvcModule), typeof(MiniProfilerModule), typeof(AspNetCoreSwaggerModule), diff --git a/src/Destiny.Core.Flow.Aop/AopModule .cs b/src/Destiny.Core.Flow.Aop/AopModule .cs deleted file mode 100644 index 1c0e215f..00000000 --- a/src/Destiny.Core.Flow.Aop/AopModule .cs +++ /dev/null @@ -1,44 +0,0 @@ -using AspectCore.Configuration; -using AspectCore.DynamicProxy; -using AspectCore.Extensions.DependencyInjection; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Destiny.Core.Flow.Reflection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Aop -{ - public class AopModule: AppModule - { - public override void ConfigureServices(ConfigureServicesContext context) - { - var service = context.Services; - var typefinder = service.GetService(); - typefinder.NotNull(nameof(typefinder)); - var typs = typefinder.Find(o => o.IsClass && !o.IsAbstract && !o.IsInterface && o.IsSubclassOf(typeof(AbstractInterceptor))); - var interceptorsModule = service.GetConfiguration()["Destiny:InterceptorsModule"]; - - - if (typs?.Length > 0) - { - List types = new List(); - - foreach (var item in typs) - { - //service.AddTransient(item); - service.ConfigureDynamicProxy(cof => - { - var enabled = service.GetConfiguration()[$"Destiny:AopManager:{item.Name}:Enabled"].ObjToBool(); - if (enabled) - cof.Interceptors.AddTyped(item, Predicates.ForNameSpace(interceptorsModule)/*,Predicates.ForNameSpace(IInterceptorsModule)*/);////这种是配置只需要代理的层, Predicates.ForNameSpace("Sukt.Core.Application.Contracts") - //config.NonAspectPredicates.AddService("IUnitofWork");//需要过滤掉不需要代理的服务层 - }); - } - } - } - - - } -} diff --git a/src/Destiny.Core.Flow.Aop/Destiny.Core.Flow.Aop.csproj b/src/Destiny.Core.Flow.Aop/Destiny.Core.Flow.Aop.csproj deleted file mode 100644 index ed3955ee..00000000 --- a/src/Destiny.Core.Flow.Aop/Destiny.Core.Flow.Aop.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - netstandard2.1 - - - - - - - - diff --git a/src/Destiny.Core.Flow.Aop/NonGlobalAopTranAttribute.cs b/src/Destiny.Core.Flow.Aop/NonGlobalAopTranAttribute.cs deleted file mode 100644 index 0b3b9dc2..00000000 --- a/src/Destiny.Core.Flow.Aop/NonGlobalAopTranAttribute.cs +++ /dev/null @@ -1,34 +0,0 @@ -using AspectCore.DynamicProxy; -using Destiny.Core.Flow.Entity; -using System; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Aop -{ - public class NonGlobalAopTranAttribute : AbstractInterceptorAttribute - { - //[FromServiceContext] - //private IUnitOfWork _unitOfWork { get; set; } - public async override Task Invoke(AspectContext context, AspectDelegate next) - { - var _unitOfWork = context.ServiceProvider.GetService(typeof(IUnitOfWork)) as IUnitOfWork; - try - { - - - - _unitOfWork.BeginTransaction(); - Console.WriteLine("代理方法执行前"); - await next(context); - Console.WriteLine("代理方法执行后"); - _unitOfWork.Commit(); - } - catch (Exception ex) - { - _unitOfWork.Rollback(); - throw ex; - } - - } - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Api/AdminControllerBase.cs b/src/Destiny.Core.Flow.AspNetCore/Api/AdminControllerBase.cs deleted file mode 100644 index 1b2126dd..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Api/AdminControllerBase.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.AspNetCore.Api -{ - /// - /// 要授权的控制器 - /// - [Authorize] - public abstract class AdminControllerBase : ApiControllerBase - { - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Api/ApiControllerBase.cs b/src/Destiny.Core.Flow.AspNetCore/Api/ApiControllerBase.cs deleted file mode 100644 index e7d3e3aa..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Api/ApiControllerBase.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Microsoft.AspNetCore.Mvc; - -namespace Destiny.Core.Flow.AspNetCore.Api -{ - [Route("api/[controller]/[action]")] - [ApiController] - //[EnableCors("Destiny.Core.Flow.API")] - public abstract class ApiControllerBase : ControllerBase - { - protected IocManage IocManage => IocManage.Instance; - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AspNetCore/BaseController.cs b/src/Destiny.Core.Flow.AspNetCore/BaseController.cs deleted file mode 100644 index f65b6bec..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/BaseController.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Destiny.Core.Flow.AspNetCore.Api; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; - -namespace Destiny.Core.Flow.AspNetCore -{ - [ApiController] - public class BaseController : ApiControllerBase - { - /// - /// 公共日志记录 - /// - public ILogger _logger; - - /// - /// 构造注入 - /// - /// - public BaseController(ILogger logger) - { - _logger = logger; - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AspNetCore/Destiny.Core.Flow.AspNetCore.csproj b/src/Destiny.Core.Flow.AspNetCore/Destiny.Core.Flow.AspNetCore.csproj deleted file mode 100644 index b064a974..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Destiny.Core.Flow.AspNetCore.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - net5.0 - - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.AspNetCore/Extensions/HttpRequestExtensions.cs b/src/Destiny.Core.Flow.AspNetCore/Extensions/HttpRequestExtensions.cs deleted file mode 100644 index 89e7cc36..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Extensions/HttpRequestExtensions.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Microsoft.AspNetCore.Http; -using System; - -namespace Destiny.Core.Flow.AspNetCore.Extensions -{ - public static class HttpRequestExtensions - { - /// - /// 判断是否为json格式 - /// - /// - /// - public static bool IsJsonContextType(this HttpRequest request) - { - request.NotNull(nameof(request)); - return request.Headers?["Content-Type"].ToString()?.IndexOf("application/json", StringComparison.OrdinalIgnoreCase) > -1; - } - - /// - /// 判断是否AJAX请求 - /// - /// - /// - public static bool IsAjaxRequest(this HttpRequest request) - { - request.NotNull(nameof(request)); - var flag = request.Headers?["X-Requested-With"].ToString()?.Equals("XMLHttpRequest", StringComparison.OrdinalIgnoreCase); - return flag.HasValue && flag.Value; - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AspNetCore/Extensions/ModelStateExtensions.cs b/src/Destiny.Core.Flow.AspNetCore/Extensions/ModelStateExtensions.cs deleted file mode 100644 index fd9a62ad..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Extensions/ModelStateExtensions.cs +++ /dev/null @@ -1,80 +0,0 @@ -using Destiny.Core.Flow.AspNetCore.Mvc.Filters; -using Destiny.Core.Flow.Helpers; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Destiny.Core.Flow.AspNetCore.Extensions -{ - //public static class MvcOptionsExtensions - //{ - // public static MvcOptions UseExceptionHandling(this MvcOptions options) - // { - // options.Filters.Add(); - // return options; - // } - //} - - //public static class ModelStateExtensions - //{ - // public static IDictionary ToSerializableDictionary(this ModelStateDictionary modelState) - // { - // return modelState.Where(x => x.Value.Errors.Any()).ToDictionary( - // kvp => kvp.Key, - // kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray() - // ); - // } - - // public static string ExportErrors(this ModelStateDictionary modelState, bool useHtmlNewLine = false) - // { - // var builder = new StringBuilder(); - - // foreach (var error in modelState.Values.SelectMany(a => a.Errors)) - // { - // var message = error.ErrorMessage; - // if (string.IsNullOrWhiteSpace(message)) - // { - // continue; - // } - - // builder.AppendLine(!useHtmlNewLine ? message : $"{message}
"); - // } - - // return builder.ToString(); - // } - - // public static void ExportModelStateToTempData(this ModelStateDictionary modelState, Controller controller, - // string key) - // { - // if (controller != null && modelState != null) - // { - // var modelStateJson = SerializeModelState(modelState); - // controller.TempData[key] = modelStateJson; - // } - // } - - // public static string SerializeModelState(this ModelStateDictionary modelState) - // { - // var values = modelState - // .Select(kvp => new ModelStateTransferValue - // { - // Key = kvp.Key, - // AttemptedValue = kvp.Value.AttemptedValue, - // RawValue = kvp.Value.RawValue, - // ErrorMessages = kvp.Value.Errors.Select(err => err.ErrorMessage).ToList(), - // }); - - // return values.ToJson(); - // } - - // public class ModelStateTransferValue - // { - // public string Key { get; set; } - // public string AttemptedValue { get; set; } - // public object RawValue { get; set; } - // public ICollection ErrorMessages { get; set; } = new List(); - // } - //} -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AspNetCore/Middleware/ExceptionHandlingMiddleware.cs b/src/Destiny.Core.Flow.AspNetCore/Middleware/ExceptionHandlingMiddleware.cs deleted file mode 100644 index f4f62754..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Middleware/ExceptionHandlingMiddleware.cs +++ /dev/null @@ -1,94 +0,0 @@ -using Destiny.Core.Flow.AspNetCore; -using Destiny.Core.Flow.AspNetCore.Extensions; -using Destiny.Core.Flow.AspNetCore.Ui; -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Extensions; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Diagnostics; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using Microsoft.IdentityModel.Tokens; -using System; -using System.Net; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.AspNetCore -{ - /// - /// - /// - public class ExceptionHandlingMiddleware - { - private readonly RequestDelegate _next; - private readonly ILogger _logger; - - public ExceptionHandlingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) - { - _next = next; - _logger = loggerFactory.CreateLogger(); - } - - public async Task Invoke(HttpContext context) - { - //todo 实现方式不够好,待重写,2021-1-26 大黄瓜 - try - { - var ex = context.Features.Get()?.Error; - - await _next(context); - } - catch (SecurityTokenExpiredException ex) - { - _logger.LogError(new EventId(), ex, ex.Message); - await catchFunc(context, AjaxResultType.Unauthorized, ex, "未经授权", (int)HttpStatusCode.Unauthorized); - } - catch (AppException ex) - { - _logger.LogError(new EventId(), ex, ex.Message); - await catchFunc(context, AjaxResultType.Error, ex, string.Empty, (int)HttpStatusCode.OK); - } - catch (Exception ex) - { - _logger.LogError(new EventId(), ex, ex.Message); - - await catchFunc(context, AjaxResultType.Error, ex, "服务器出现异常,请联系管理员!!", (int)HttpStatusCode.InternalServerError); - } - } - - //todo 实现方式不够好,待重写,2021-1-26 大黄瓜 - private Func catchFunc = async (context, ajax, ex, msg, code) => - { - - if (context.Request.IsAjaxRequest() || context.Request.IsJsonContextType()) - { - if (context.Response.HasStarted) - { - return; - } - context.Response.StatusCode = code; - - context.Response.ContentType = "application/json; charset=utf-8"; - await context.Response.WriteAsync(new AjaxResult(msg.IsNullOrEmpty() ? ex.Message : msg, ajax).ToJson()); - - } - - }; - } - - -} - -public static class ErrorHandlingExtensions -{ - /// - /// 异常中间件 - /// - /// - /// - - public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder) - { - return builder.UseMiddleware(); - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Module/AspNetCoreModule.cs b/src/Destiny.Core.Flow.AspNetCore/Module/AspNetCoreModule.cs deleted file mode 100644 index d325d130..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Module/AspNetCoreModule.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.AspNetCore.Module -{ - public class AspNetCoreModule : AspNetCoreModuleBase - { - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Module/AspNetCoreModuleBase.cs b/src/Destiny.Core.Flow.AspNetCore/Module/AspNetCoreModuleBase.cs deleted file mode 100644 index 3980ffe8..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Module/AspNetCoreModuleBase.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Destiny.Core.Flow.AspNetCore.Mvc.Filters; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Destiny.Core.Flow.Options; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Security.Principal; -using System.Text; - -namespace Destiny.Core.Flow.AspNetCore.Module -{ - public abstract class AspNetCoreModuleBase : AppModule - { - - - public override void ConfigureServices(ConfigureServicesContext context) - { - var settings = context.Services.GetObject(); - context.Services.AddFileProvider(); - - context.Services.AddHttpContextAccessor(); - - context.Services.AddTransient(provider => - { - IHttpContextAccessor accessor = provider.GetService(); - return accessor?.HttpContext?.User; - }); - - } - - - - - - public override void ApplicationInitialization(ApplicationContext context) - { - var app = context.GetApplicationBuilder(); - - app.UseEndpoints(endpoints => { - endpoints = this.Endpoints(endpoints); - - }); - - } - - - protected virtual IEndpointRouteBuilder Endpoints(IEndpointRouteBuilder endpoint) - { - endpoint.MapControllers(); - return endpoint; - - - } - - - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Module/DestinyCoreModule.cs b/src/Destiny.Core.Flow.AspNetCore/Module/DestinyCoreModule.cs deleted file mode 100644 index 7d76fe81..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Module/DestinyCoreModule.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Events; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Destiny.Core.Flow.Options; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -namespace Destiny.Core.Flow.AspNetCore.Module -{ - [DependsOn( - - typeof(DependencyAppModule), - typeof(MediatorAppModule) - )] - public class DestinyCoreModule : AppModule - { - public override void ConfigureServices(ConfigureServicesContext context) - { - context.Services.AddFileProvider(); - var configuration = context.GetConfiguration(); - context.Services.Configure(configuration.GetSection("Destiny")); - - var settings = context.GetConfiguration("Destiny"); - context.Services.AddObjectAccessor(settings); - } - - - - - - - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Module/MvcModuleBase.cs b/src/Destiny.Core.Flow.AspNetCore/Module/MvcModuleBase.cs deleted file mode 100644 index 8e03f115..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Module/MvcModuleBase.cs +++ /dev/null @@ -1,60 +0,0 @@ -using Destiny.Core.Flow.AspNetCore.Mvc.Filters; -using Destiny.Core.Flow.Modules; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.AspNetCore.Module -{ - - public abstract class MvcModuleBase : AppModule - { - - public override void ConfigureServices(ConfigureServicesContext context) - { - AddCors(context); - context.Services.AddControllers(o => this.AddMvcOptions(o)).AddNewtonsoftJson(options => - { - options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); - - options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; - }); - context.Services.AddScoped(); - context.Services.AddScoped(); - } - - - - protected virtual void AddMvcOptions(MvcOptions options) - { - - } - public override void ApplicationInitialization(ApplicationContext context) - { - var app= context.GetApplicationBuilder(); - app.UseRouting(); - UseCors(context); - - app.UseAuthentication(); //认证 - app.UseAuthorization();//授权 - } - - protected virtual void AddCors(ConfigureServicesContext context) - { - - - } - - - protected virtual void UseCors(ApplicationContext context) - { - - - - } - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/AuditLogFilterAttribute.cs b/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/AuditLogFilterAttribute.cs deleted file mode 100644 index 6c15443c..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/AuditLogFilterAttribute.cs +++ /dev/null @@ -1,83 +0,0 @@ -using Destiny.Core.Flow.AspNetCore.Ui; -using Destiny.Core.Flow.Audit; -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Extensions; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Destiny.Core.Flow.AspNetCore.Mvc.Filters -{ - /// - /// c# 计算程序运行时间三种方法 - /// https://www.cnblogs.com/dearzhoubi/p/9842452.html - /// - public class AuditLogFilterAttribute : ActionFilterAttribute - { - - public override void OnActionExecuted(ActionExecutedContext context) - { - - if (context.Result is ObjectResult result) - { - if (result.Value is AjaxResult ajax) - { - var type = ajax.Type; - IServiceProvider provider = context.HttpContext.RequestServices; - - DictionaryScoped dict = provider.GetService(); - if (!ajax.Success) - { - dict.AuditChange.Message = ajax.Message; - } - - dict.AuditChange.ResultType = type; - } - - - } - - } - - public override void OnActionExecuting(ActionExecutingContext context) - { - IServiceProvider provider = context.HttpContext.RequestServices; - var controllerAction = context.ActionDescriptor as ControllerActionDescriptor; - var isAuditEnabled = provider.GetAppSettings().AuditEnabled; - if (isAuditEnabled) - { - DictionaryScoped dict = provider.GetService(); - AuditChange auditChange = new AuditChange(); - auditChange.FunctionName = $"{context.Controller.GetType().ToDescription()}-{controllerAction.MethodInfo.ToDescription()}"; - auditChange.Action = context.HttpContext.Request.Path; - auditChange.Ip = context.HttpContext.GetClientIP(); - auditChange.BrowserInformation = context.HttpContext.Request.Headers["User-Agent"].ToString(); - auditChange.StartTime = DateTime.Now; - dict.AuditChange = auditChange; - } - - } - public override void OnResultExecuted(ResultExecutedContext context) - { - - IServiceProvider provider = context.HttpContext.RequestServices; - var action = context.ActionDescriptor as ControllerActionDescriptor; - var isAuditEnabled = provider.GetAppSettings().AuditEnabled; - if (isAuditEnabled) - { - - var dic = provider.GetService(); - - dic.AuditChange.ExecutionDuration = DateTime.Now.Subtract(dic.AuditChange.StartTime).TotalMilliseconds; - provider.GetService()?.SaveAsync(dic.AuditChange).GetAwaiter().GetResult(); - - } - } - - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/HandleException.cs b/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/HandleException.cs deleted file mode 100644 index 9776aabb..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/HandleException.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Destiny.Core.Flow.AspNetCore.Extensions; -using Destiny.Core.Flow.AspNetCore.Ui; -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Validation; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.Logging; -using System; -using System.Linq; - -namespace Destiny.Core.Flow.AspNetCore.Mvc.Filters -{ - public class HandleException : IExceptionFilter - { - private readonly ILogger _logger; - - public HandleException(ILogger logger) - { - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } - - public void OnException(ExceptionContext context) - { - if (context.HttpContext.Request.IsAjaxRequest() || context.HttpContext.Request.IsJsonContextType()) - { - context.ExceptionHandled = true; - AjaxResult result = new AjaxResult(); - - if (context.Exception is ValidationException validationException) - { - var message = string.Join(",", validationException.Failures.Select(o => o.Message)); - context.Result = new JsonResult(new AjaxResult(validationException.Message.IsNullOrWhiteSpace() ? message : validationException.Message, AjaxResultType.Error)); - } - } - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/PermissionAuthorizationFilter.cs b/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/PermissionAuthorizationFilter.cs deleted file mode 100644 index 5d13b79f..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/PermissionAuthorizationFilter.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Destiny.Core.Flow.AspNetCore.Ui; -using Destiny.Core.Flow.Permission; -using Destiny.Core.Flow.Ui; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.Logging; -using System.Linq; -using System.Reflection; -using System.Security.Principal; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.AspNetCore.Mvc.Filters -{ - /// - /// - /// - public class PermissionAuthorizationFilter : IAsyncAuthorizationFilter - { - private readonly IAuthorityVerification _authority; - private readonly IPrincipal _principal; - private readonly ILogger _logger = null; - - public PermissionAuthorizationFilter(IAuthorityVerification authority, IPrincipal principal, ILogger logger) - { - _authority = authority; - _principal = principal; - _logger = logger; - } - - public async Task OnAuthorizationAsync(AuthorizationFilterContext context) - { - _logger.LogInformation($"进入权限判断"); - var action = context.ActionDescriptor as ControllerActionDescriptor; - var linkurl = context.HttpContext.Request.Path.Value.Replace("/api/", ""); - var result = new AjaxResult(MessageDefinitionType.Unauthorized, Enums.AjaxResultType.Unauthorized); - if (!action.EndpointMetadata.Any(x => x is AllowAnonymousAttribute)) - { - if (!_principal.Identity.IsAuthenticated) - { - context.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized; - context.Result = new JsonResult(result); - return; - } - else - { - if (!action.EndpointMetadata.Any(x => x is NoAuthorityVerificationAttribute)) - { - var result1 = (await _authority.IsPermission(linkurl.ToLower())); - if (!result1.Success) - { - ////????不包含的时候怎么返回出去?这个请求终止掉 - /// - _logger.LogError($"此{linkurl}地址没有权限"); - //result = result1.ToAjaxResult(); - //context.HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden; - //context.Result.ToJsonResult(result); - result.Message = MessageDefinitionType.Uncertified; - result.Type = Enums.AjaxResultType.Uncertified; - context.HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden; - context.Result = new JsonResult(result); - return; - } - } - } - } - _logger.LogInformation($"权限判断结束"); - } - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/UnitOfWorkAtrrribute.cs b/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/UnitOfWorkAtrrribute.cs deleted file mode 100644 index 77cbc870..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/UnitOfWorkAtrrribute.cs +++ /dev/null @@ -1,67 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Microsoft.AspNetCore.Mvc.Filters; -using System; -using System.Collections.Generic; -using System.Text; -using Microsoft.Extensions.DependencyInjection; -using Destiny.Core.Flow.AspNetCore.Ui; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.AspNetCore.Extensions; -using Destiny.Core.Flow.Exceptions; - -namespace Destiny.Core.Flow.AspNetCore.Mvc.Filters -{ - public class UnitOfWorkAtrrribute : ActionFilterAttribute - { - private readonly IServiceProvider _serviceProvider = null; - private readonly ILogger _logger = null; - public UnitOfWorkAtrrribute(IServiceProvider serviceProvider) - { - - _serviceProvider = serviceProvider; - _logger = serviceProvider.GetLogger(); - _unitOfWork = serviceProvider.GetService(); - } - - private readonly IUnitOfWork _unitOfWork = null; - public override void OnActionExecuting(ActionExecutingContext context) - { - _unitOfWork?.BeginTransaction(); - _unitOfWork?.Push(); - } - - - public override void OnActionExecuted(ActionExecutedContext context) - { - _unitOfWork?.Pop(); - if (context.Exception != null && context.ExceptionHandled) - { - var ex = context.Exception; - _unitOfWork?.Rollback(); - MessageBox.Show(ex.Message,ex); - } - - if (context.Result is ObjectResult result) - { - if (result.Value is AjaxResult ajax) - { - - if (ajax.Success) - { - _unitOfWork?.Commit(); - } - else - { - _unitOfWork?.Rollback(); - } - - context.Result = new JsonResult(new AjaxResult() { Type = ajax.Type, Message = ajax.Message,Data=ajax.Data,Success=ajax.Success }); - } - - - } - } - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/ValidationFilterAttribute.cs b/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/ValidationFilterAttribute.cs deleted file mode 100644 index ba034efa..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Mvc/Filters/ValidationFilterAttribute.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Destiny.Core.Flow.Validation.Interceptor; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Text; -using System.Linq; -using Destiny.Core.Flow.AspNetCore.Ui; -using Destiny.Core.Flow.Extensions; -using Microsoft.AspNetCore.Mvc; - -namespace Destiny.Core.Flow.AspNetCore.Mvc.Filters -{ - [AttributeUsage(AttributeTargets.Method)] - //验证特性 - public class ValidationFilterAttribute : ActionFilterAttribute - { - - private readonly MethodInvocationValidator _validator; - private readonly ILogger _logger; - - public ValidationFilterAttribute(MethodInvocationValidator validator, ILoggerFactory loggerFactory) - { - _validator = validator; - _logger = loggerFactory.CreateLogger("Destiny.Core.Flow.AspNetCore.Mvc.Filters"); - } - - public override void OnActionExecuting(ActionExecutingContext context) - { - - var action = context.ActionDescriptor as ControllerActionDescriptor; - var method = action.MethodInfo; - - - var arguments = context.ActionArguments.Values.ToArray(); - _logger.LogInformation($"开启验证:{method.Name}"); - var failures = _validator.Validate(method, arguments); - - if (failures.Any()) - { - _logger.LogInformation($"验证失败:{method.Name} {failures.Select(o => o.ToString()).ToJoin()}"); - context.Result = new JsonResult( new AjaxResult() { Type = Enums.AjaxResultType.Error, Message = failures.Select(o => o.ToString()).ToJoin() }); - return; - } - - _logger.LogInformation($"验证成功:{method.Name}"); - } - - - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Ui/AjaxResult.cs b/src/Destiny.Core.Flow.AspNetCore/Ui/AjaxResult.cs deleted file mode 100644 index 4f5cb048..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Ui/AjaxResult.cs +++ /dev/null @@ -1,89 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Filter; -using Destiny.Core.Flow.Helpers; -using Destiny.Core.Flow.Ui; - -namespace Destiny.Core.Flow.AspNetCore.Ui -{ - /// - /// Ajax操作结果 - /// - public class AjaxResult: ResultBase, IHasResultType - { - public AjaxResult() : this(null) - { - } - - public AjaxResult(AjaxResultType type = AjaxResultType.Success) : this("", null, type) - { - } - - public AjaxResult(string message, AjaxResultType type = AjaxResultType.Success, object data = null) : this(message, data, type) - { - } - - public AjaxResult(AjaxResultType type = AjaxResultType.Success, object data = null) : this("", data, type) - { - } - - - public AjaxResult(string message, object data, AjaxResultType type) - { - this.Message = message; - this.Data = data; - this.Type = type; - this.Success = Succeeded(); - } - - public AjaxResult(string message, bool success, object data, AjaxResultType type) - { - this.Message = message; - this.Data = data; - this.Type = type; - this.Success = success; - - } - - - - /// - /// 返回类型 - /// - - public AjaxResultType Type { get; set; } - - /// - /// 是否成功 - /// - public bool Succeeded() - { - return Type == AjaxResultType.Success; - } - - /// - /// 是否错误 - /// - public bool Error() - { - return Type == AjaxResultType.Error; - } - - /// - /// 转成对象 - /// - /// - public object ToObject() - { - return new { Data, Message, Success, Type }; - } - - /// - /// 转成JSON - /// - /// - public string ToJson() - { - return this.ToObject().ToJson(); - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AspNetCore/Ui/AjaxResultExtensions.cs b/src/Destiny.Core.Flow.AspNetCore/Ui/AjaxResultExtensions.cs deleted file mode 100644 index 96d59e87..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Ui/AjaxResultExtensions.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Ui; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.AspNetCore.Ui -{ - public static class AjaxResultExtensions - { - public static AjaxResult ToAjaxResult(this OperationResponse operationResponse) - { - var message = operationResponse.Message ?? operationResponse.Type.ToDescription(); - AjaxResultType type = operationResponse.Type.ToAjaxResultType(); - return new AjaxResult(message, type, operationResponse.Data) { Success = operationResponse.Success }; - } - - public static async Task ToAjaxResult(this Task operationResponse) - { - - var result = await operationResponse; - var message = result.Message ?? result.Type.ToDescription(); - AjaxResultType type = result.Type.ToAjaxResultType(); - return new AjaxResult(message, type, result.Data) { Success = result.Success }; - } - - public static AjaxResult ToAjaxResult(this OperationResponse operationResult) - { - var message = operationResult.Message ?? operationResult.Type.ToDescription(); - AjaxResultType type = operationResult.Type.ToAjaxResultType(); - return new AjaxResult(message, type, operationResult.Data) { Success = operationResult.Success }; - } - - public static AjaxResultType ToAjaxResultType(this OperationResponseType responseType) - { - return responseType switch - { - OperationResponseType.Success => AjaxResultType.Success, - OperationResponseType.NoChanged => AjaxResultType.Info, - _ => AjaxResultType.Error, - }; - } - - public static AjaxResultType ToAjaxResultType(this AuthResultType type) - { - return type switch - { - AuthResultType.Success => AjaxResultType.Success, - AuthResultType.Unauthorized => AjaxResultType.Unauthorized, - AuthResultType.NoFound => AjaxResultType.NoFound, - AuthResultType.Uncertified => AjaxResultType.Uncertified, - _ => AjaxResultType.Uncertified, - }; - } - - - public static AjaxResult ToAjaxResult(this AuthorizationResult result) - { - - - var message = result.Message ?? result.Type.ToDescription(); - AjaxResultType type = result.Type.ToAjaxResultType(); - return new AjaxResult(message, type) { Success = result.Success }; - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AspNetCore/Ui/JsonResultExtensions.cs b/src/Destiny.Core.Flow.AspNetCore/Ui/JsonResultExtensions.cs deleted file mode 100644 index 4bbacae6..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Ui/JsonResultExtensions.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.AspNetCore.Ui -{ - public static class JsonResultExtensions - { - - /// - /// 转成JsonResult - /// - /// - /// - /// - public static IActionResult ToJsonResult(this IActionResult action, AjaxResult result) - { - - return new JsonResult(result); - } - } -} diff --git a/src/Destiny.Core.Flow.AspNetCore/Ui/PageList.cs b/src/Destiny.Core.Flow.AspNetCore/Ui/PageList.cs deleted file mode 100644 index 4a3371d8..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Ui/PageList.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Ui; -using System.Collections.Generic; - -namespace Destiny.Core.Flow.AspNetCore.Ui -{ - public class PageList : ResultBase, IHasResultType - { - public PageList() : this(new T[0], 0, "查询成功", true) - { - } - - public PageList(IEnumerable itemList, int total, string message = "查询成功", bool success = true) - { - ItemList = itemList; - Total = total; - Success = success; - this.Message = message; - } - - public IEnumerable ItemList { get; set; } - - public int Total { get; set; } - public AjaxResultType Type { get; set; } - } - - public class PageListDto : PageList - { - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AspNetCore/Ui/PageListExtensions.cs b/src/Destiny.Core.Flow.AspNetCore/Ui/PageListExtensions.cs deleted file mode 100644 index 453d2fe6..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Ui/PageListExtensions.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Destiny.Core.Flow.Filter.Abstract; - -namespace Destiny.Core.Flow.AspNetCore.Ui -{ - /// - /// 分页集合Dto扩展 - /// - public static class PageListExtensions - { - /// - /// 分页集合Dto - /// - /// - /// - /// - public static PageList ToPageList(this IPagedResult pageResult) - { - var result = pageResult; - return new PageList() { ItemList = result.ItemList, Message = result.Message, Total = result.Total, Success = result.Success,Type= result.Type }; - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AspNetCore/Ui/TreeModel.cs b/src/Destiny.Core.Flow.AspNetCore/Ui/TreeModel.cs deleted file mode 100644 index 00eebf96..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Ui/TreeModel.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Ui; -using System.Collections.Generic; - -namespace Destiny.Core.Flow.AspNetCore.Ui -{ - public class TreeModel : ResultBase, IListResult, IHasResultType //这里到时候要统一 - { - public TreeModel() : this(new TData[0], "成功返回数据", true) - { - } - - public TreeModel(IReadOnlyList itemList, string message = "成功返回数据", bool success = true) - { - ItemList = itemList; - Message = message; - Success = success; - } - - public IReadOnlyList ItemList { get; set; } - public AjaxResultType Type { get; set; } - } - - public class TreeModel : ResultBase, IListResult, IHasResultType //这里到时候要统一 - { - public TreeModel() : this(new TData[0], new TSelectedType[0], "成功返回数据", true) - { - } - - public TreeModel(IReadOnlyList itemList, IReadOnlyList selectedList, string message = "成功返回数据", bool success = true) - { - ItemList = itemList; - Message = message; - Success = success; - SelectedList = selectedList; - } - - public IReadOnlyList ItemList { get; set; } - - public IReadOnlyList SelectedList { get; set; } - public AjaxResultType Type { get; set; } - } - - public class TreeModel : TreeModel - { - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AspNetCore/Ui/TreeModelExtensions.cs b/src/Destiny.Core.Flow.AspNetCore/Ui/TreeModelExtensions.cs deleted file mode 100644 index c2faa25f..00000000 --- a/src/Destiny.Core.Flow.AspNetCore/Ui/TreeModelExtensions.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Destiny.Core.Flow.Ui.Abstracts; - -namespace Destiny.Core.Flow.AspNetCore.Ui -{ - public static class TreeModelExtensions - { - public static TreeModel ToTreeModel(this ITreeResult result) - { - return new TreeModel(result.ItemList, result.Message, result.Success); - } - - /// - /// 待优化 - /// - /// - /// - /// - /// - public static TreeModel ToTreeModel(this ITreeResult result) - { - return new TreeModel(result.ItemList, result.SelectedList, result.Message, result.Success); - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.AuthenticationCenter/Destiny.Core.Flow.AuthenticationCenter.csproj b/src/Destiny.Core.Flow.AuthenticationCenter/Destiny.Core.Flow.AuthenticationCenter.csproj index 92946160..721f78da 100644 --- a/src/Destiny.Core.Flow.AuthenticationCenter/Destiny.Core.Flow.AuthenticationCenter.csproj +++ b/src/Destiny.Core.Flow.AuthenticationCenter/Destiny.Core.Flow.AuthenticationCenter.csproj @@ -9,15 +9,16 @@ + + + + - - - diff --git a/src/Destiny.Core.Flow.AuthenticationCenter/Startups/IdentityModule.cs b/src/Destiny.Core.Flow.AuthenticationCenter/Startups/IdentityModule.cs index c7f40342..6de8365c 100644 --- a/src/Destiny.Core.Flow.AuthenticationCenter/Startups/IdentityModule.cs +++ b/src/Destiny.Core.Flow.AuthenticationCenter/Startups/IdentityModule.cs @@ -18,8 +18,9 @@ protected override void AddAuthentication(IServiceCollection services) { services.AddAuthentication().AddQQ(x => { - x.ClientId = "adasdasd"; - x.ClientSecret = "asdasdadas"; + x.ClientId = "adasd"; + x.ClientSecret = "adasdas"; + //x.ReturnUrlParameter = "http://localhost:50001/signin-qq"; }); } diff --git a/src/Destiny.Core.Flow.AuthenticationCenter/Views/Account/Login.cshtml b/src/Destiny.Core.Flow.AuthenticationCenter/Views/Account/Login.cshtml index a6239a27..9a9dee67 100644 --- a/src/Destiny.Core.Flow.AuthenticationCenter/Views/Account/Login.cshtml +++ b/src/Destiny.Core.Flow.AuthenticationCenter/Views/Account/Login.cshtml @@ -55,7 +55,7 @@
  • @provider.DisplayName diff --git a/src/Destiny.Core.Flow.AutoMapper/AutoMapperModule.cs b/src/Destiny.Core.Flow.AutoMapper/AutoMapperModule.cs deleted file mode 100644 index 686ae95a..00000000 --- a/src/Destiny.Core.Flow.AutoMapper/AutoMapperModule.cs +++ /dev/null @@ -1,62 +0,0 @@ -using AutoMapper; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Mapping; -using Destiny.Core.Flow.Modules; -using Destiny.Core.Flow.Reflection; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Linq; -using System.Reflection; - -namespace Destiny.Core.Flow.AutoMapper -{ - public class AutoMapperModule : AppModule - { - - - - public override void ConfigureServices(ConfigureServicesContext context) - { - var assemblyFinder = context.Services.GetOrAddSingletonService(); - var assemblys = assemblyFinder.FindAll(); - var myAutoMapTypes = assemblys.SelectMany(o => o.GetTypes()).Where(t => t.IsClass && !t.IsAbstract && t.HasAttribute(true)).Distinct().ToArray(); - context.Services.AddAutoMapper(mapper => - { - - this.CreateMapping(myAutoMapTypes, mapper); - - }, assemblys, ServiceLifetime.Singleton); - var mapper = context.Services.GetService(); - Destiny.Core.Flow.Extensions.Extensions.SetMapper(mapper); - } - - - private void CreateMapping(Type[] sourceTypes, IMapperConfigurationExpression mapperConfigurationExpression) - where TAttribute : AutoMappingAttribute - { - foreach (var sourceType in sourceTypes) - { - var attribute = sourceType.GetCustomAttribute(); - if (attribute.TargetTypes?.Count() <= 0) - { - return; - } - foreach (var tatgetType in attribute.TargetTypes) - { - - if (attribute.Direciton.HasFlag(AutoMapDirection.To)) - { - mapperConfigurationExpression.CreateMap(sourceType, tatgetType); - } - - if (attribute.Direciton.HasFlag(AutoMapDirection.From)) - { - mapperConfigurationExpression.CreateMap(tatgetType, sourceType); - } - - } - } - - } - } -} diff --git a/src/Destiny.Core.Flow.AutoMapper/Destiny.Core.Flow.AutoMapper.csproj b/src/Destiny.Core.Flow.AutoMapper/Destiny.Core.Flow.AutoMapper.csproj deleted file mode 100644 index 6ed29341..00000000 --- a/src/Destiny.Core.Flow.AutoMapper/Destiny.Core.Flow.AutoMapper.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - netstandard2.1 - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.Caching.CSRedis/CSRedisCache.cs b/src/Destiny.Core.Flow.Caching.CSRedis/CSRedisCache.cs deleted file mode 100644 index 8bf85442..00000000 --- a/src/Destiny.Core.Flow.Caching.CSRedis/CSRedisCache.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Caching.CSRedis -{ - - - - public class CSRedisCache : ICache - { - public TCacheData Get(string key) - { - return CacheHelper.Get(key); - } - - public async Task GetAsync(string key, CancellationToken token = default) - { - - return await CacheHelper.GetAsync(key); - } - - public TCacheData GetOrAdd(string key, Func func, int expireSeconds = -1) - { - return CacheHelper.GetOrAdd(key, func, expireSeconds); - } - - public async Task GetOrAddAsync([NotNull] string key, Func> func, int expireSeconds = -1, CancellationToken token = default) - { - return await CacheHelper.GetOrAddAsync(key, func, expireSeconds); - } - - public void Remove(string key) - { - CacheHelper.Remove(key); - } - - public async Task RemoveAsync(string key, CancellationToken token = default) - { - - await CacheHelper.RemoveAsync(key); - } - - public void Set(string key, TCacheData value, int expireSeconds = -1) - { - - CacheHelper.Set(key, value, expireSeconds); - } - - public async Task SetAsync(string key, TCacheData value, int expireSeconds = -1, CancellationToken token = default) - { - - await CacheHelper.SetAsync(key, value, expireSeconds); - } - } -} diff --git a/src/Destiny.Core.Flow.Caching.CSRedis/CSRedisModule.cs b/src/Destiny.Core.Flow.Caching.CSRedis/CSRedisModule.cs deleted file mode 100644 index 57217c0a..00000000 --- a/src/Destiny.Core.Flow.Caching.CSRedis/CSRedisModule.cs +++ /dev/null @@ -1,31 +0,0 @@ -using CSRedis; -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using System.IO; - -namespace Destiny.Core.Flow.Caching.CSRedis -{ - public class CSRedisModule : AppModule - { - - public override void ConfigureServices(ConfigureServicesContext context) - { - var provider = context.Services.BuildServiceProvider(); - var connection = context.Services.GetConfiguration()["Destiny:Redis:ConnectionString"]; - //var connection = services.GetFileByConfiguration("SuktCore:DbContext:MongoDBConnectionString", "未找到存放MongoDB数据库链接的文件"); - if (Path.GetExtension(connection).ToLower() == ".txt") //txt文件 - { - connection = provider.GetFileText(connection, $"未找到存放Rdis链接的文件"); - } - //var connStr = context.Services.GetFileByConfiguration("Destiny:Redis:ConnectionString", "未找到存放Rdis链接的文件"); - var csredis = new CSRedisClient(connection); - RedisHelper.Initialization(csredis); - context.Services.TryAddSingleton(); - } - - - } -} diff --git a/src/Destiny.Core.Flow.Caching.CSRedis/CacheHelper.cs b/src/Destiny.Core.Flow.Caching.CSRedis/CacheHelper.cs deleted file mode 100644 index 9801abb9..00000000 --- a/src/Destiny.Core.Flow.Caching.CSRedis/CacheHelper.cs +++ /dev/null @@ -1,157 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Caching.CSRedis -{ - internal class CacheHelper - { - private static string GetKey(TKey key) - { - key.NotNull(nameof(key)); - return key.ToString(); - } - - /// - /// 得到 - /// - /// 键 - /// 返回得到 - public static TCacheData Get(TKey key) - { - return RedisHelper.Get(GetKey(key)); - } - - /// - /// 得到或添加 - /// - /// 键 - /// - /// - public static TCacheData GetOrAdd( - TKey key, - Func func, int expireSeconds = -1) - { - key.NotNull(nameof(key)); - - func.NotNull(nameof(func)); - var value = Get(key); - - - if (!Equals(value, default(TCacheData))) - { - return value; - } - - value = func(); - - if (Equals(value, default(TCacheData))) - { - return default; - } - - Set(key, value); - return value; - } - - /// - /// 异步得到缓存 - /// - /// - /// 键 - /// - async public static Task GetAsync(TKey key, CancellationToken token = default) - { - return await RedisHelper.GetAsync(GetKey(key)); - } - - /// - /// 得到或添加 - /// - /// <键/param> - /// - /// - /// 返回得到或添加后的缓存数据 - async public static Task GetOrAddAsync( - [NotNull] TKey key, - Func> func, int expireSeconds = -1, - CancellationToken token = default - ) - { - - func.NotNull(nameof(func)); - var value = await GetAsync(key); - - - if (!Equals(value, default(TCacheData))) - { - return value; - } - - value = await func(); - - if (Equals(value, default(TCacheData))) - { - return default; - } - - await SetAsync(key, value); - return value; - } - - - #region 设置 - - /// - /// 设置缓存 - /// - /// 键 - /// 值 - public static void Set(TKey key, TCacheData value, int expireSeconds = -1) - { - value.NotNull(nameof(value)); - RedisHelper.Set(GetKey(key), value, expireSeconds); - } - - /// - /// 异步设置缓存 - /// - /// 键 - /// 值 - /// - /// - async public static Task SetAsync(TKey key, TCacheData value, int expireSeconds = -1, CancellationToken token = default) - { - value.NotNull(nameof(value)); - await RedisHelper.SetAsync(GetKey(key), value, expireSeconds); - } - #endregion - - - - #region 删除 - - /// - /// 删除缓存 - /// - /// 要删除的键 - public static void Remove(TKey key) - { - RedisHelper.Del(GetKey(key)); - } - - /// - /// 异步删除缓存 - /// - /// - /// - /// - async public static Task RemoveAsync(TKey key, CancellationToken token = default) - { - await RedisHelper.DelAsync(GetKey(key)); - } - #endregion - } -} diff --git a/src/Destiny.Core.Flow.Caching.CSRedis/Destiny.Core.Flow.Caching.CSRedis.csproj b/src/Destiny.Core.Flow.Caching.CSRedis/Destiny.Core.Flow.Caching.CSRedis.csproj deleted file mode 100644 index 08d7237c..00000000 --- a/src/Destiny.Core.Flow.Caching.CSRedis/Destiny.Core.Flow.Caching.CSRedis.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - netstandard2.1 - - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.Caching/CacheDefault.cs b/src/Destiny.Core.Flow.Caching/CacheDefault.cs deleted file mode 100644 index a94824f0..00000000 --- a/src/Destiny.Core.Flow.Caching/CacheDefault.cs +++ /dev/null @@ -1,135 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Microsoft.Extensions.Caching.Distributed; -using Microsoft.Extensions.Caching.Memory; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using Destiny.Core.Flow.Helpers; -using Nito.AsyncEx; - -namespace Destiny.Core.Flow.Caching -{ - /// - /// 缓存 - /// - public class CacheDefault : ICache - { - - private IDistributedCache _cache = null; - private readonly AsyncLock _mutex = new AsyncLock(); - - public CacheDefault(IDistributedCache cache) - { - _cache = cache; - } - - /// - /// 得到缓存 - /// - /// - /// - /// - public TCacheData Get(string key) - { - - return _cache.GetString(key).FromJson(); - } - - public async Task GetAsync(string key, CancellationToken token = default) - { - - return (await _cache.GetStringAsync(key)).FromJson(); - } - - public TCacheData GetOrAdd(string key, Func func, int expireSeconds = -1) - { - key.NotNull(nameof(key)); - - func.NotNull(nameof(func)); - - using (_mutex.Lock()) - { - var value = this.Get(key); - - - if (!Equals(value, default(TCacheData))) - { - return value; - } - - value = func(); - - if (Equals(value, default(TCacheData))) - { - return default; - } - - Set(key, value, expireSeconds); - return value; - } - - } - - public async Task GetOrAddAsync([NotNull] string key, Func> func, int expireSeconds = -1, CancellationToken token = default) - { - key.NotNull(nameof(key)); - - func.NotNull(nameof(func)); - - using (await _mutex.LockAsync()) - { - var value = await this.GetAsync(key); - - - if (!Equals(value, default(TCacheData))) - { - return value; - } - - value = await func(); - - if (Equals(value, default(TCacheData))) - { - return default; - } - - await SetAsync(key, value); - return value; - } - - } - - public void Remove(string key) - { - _cache.Remove(key); - } - - public async Task RemoveAsync(string key, CancellationToken token = default) - { - await _cache.RemoveAsync(key); - } - - public void Set(string key, TCacheData value, int expireSeconds = -1) - { - DistributedCacheEntryOptions options = new DistributedCacheEntryOptions(); - if (expireSeconds > 0) - { - options.SetAbsoluteExpiration(TimeSpan.FromSeconds(expireSeconds)); - } - _cache.SetString(key, value.ToJson(), options); - - } - - - public async Task SetAsync(string key, TCacheData value, int expireSeconds = -1, CancellationToken token = default) - { - DistributedCacheEntryOptions options = new DistributedCacheEntryOptions(); - if (expireSeconds > 0) - { - options.SetAbsoluteExpiration(TimeSpan.FromSeconds(expireSeconds)); - } - await _cache.SetStringAsync(key, value.ToJson(), options); - } - } -} diff --git a/src/Destiny.Core.Flow.Caching/CacheHandlerBase.cs b/src/Destiny.Core.Flow.Caching/CacheHandlerBase.cs deleted file mode 100644 index 287fc1c5..00000000 --- a/src/Destiny.Core.Flow.Caching/CacheHandlerBase.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Destiny.Core.Flow.Events; - -namespace Destiny.Core.Flow.Caching -{ - public abstract class CacheHandlerBase : NotificationHandlerBase where TEvent : EventBase - { - protected readonly ICache _cache = null; - - - public CacheHandlerBase(ICache cache) - { - _cache = cache; - - } - } -} diff --git a/src/Destiny.Core.Flow.Caching/CacheOptions.cs b/src/Destiny.Core.Flow.Caching/CacheOptions.cs deleted file mode 100644 index 5de0b6e1..00000000 --- a/src/Destiny.Core.Flow.Caching/CacheOptions.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Destiny.Core.Flow.Caching -{ - public class CacheOptions - { - } -} diff --git a/src/Destiny.Core.Flow.Caching/CachingDefaultModule.cs b/src/Destiny.Core.Flow.Caching/CachingDefaultModule.cs deleted file mode 100644 index 7fbe577a..00000000 --- a/src/Destiny.Core.Flow.Caching/CachingDefaultModule.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Destiny.Core.Flow.Modules; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Caching -{ - /// - /// 缓存默认模块 - /// - public class CachingDefaultModule : AppModule - { - - public override void ConfigureServices(ConfigureServicesContext context) - { - context.Services.AddDistributedMemoryCache(); - context.Services.AddSingleton(); - } - } -} diff --git a/src/Destiny.Core.Flow.Caching/Destiny.Core.Flow.Caching.csproj b/src/Destiny.Core.Flow.Caching/Destiny.Core.Flow.Caching.csproj deleted file mode 100644 index 6d805fe2..00000000 --- a/src/Destiny.Core.Flow.Caching/Destiny.Core.Flow.Caching.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - netstandard2.1 - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.Caching/ICache.cs b/src/Destiny.Core.Flow.Caching/ICache.cs deleted file mode 100644 index 496475c0..00000000 --- a/src/Destiny.Core.Flow.Caching/ICache.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Caching -{ - - - public interface ICache - { - - /// - /// 得到 - /// - /// 键 - /// 返回得到 - TCacheData Get(string key); - - /// - /// 得到或添加 - /// - /// - /// 过期秒数-1,0不过期。 - /// - TCacheData GetOrAdd( - string key, - Func func, int expireSeconds = -1); - - /// - /// 异步得到缓存 - /// - /// - /// 键 - /// - Task GetAsync(string key, CancellationToken token = default); - - /// - /// 得到或添加 - /// - /// <键/param> - /// - /// - /// 过期秒数-1,0不过期。 - /// 返回得到或添加后的缓存数据 - Task GetOrAddAsync( - [NotNull] string key, - Func> func, - int expireSeconds = -1, - CancellationToken token = default - ); - - - #region 设置 - - /// - /// 设置缓存 - /// - /// 键 - /// 值 - /// 过期秒数-1,0不过期。 - void Set(string key, TCacheData value, int expireSeconds = -1); - - /// - /// 异步设置缓存 - /// - /// 键 - /// 值 - /// - /// 过期秒数-1,0不过期。 - Task SetAsync(string key, TCacheData value, int expireSeconds = -1, CancellationToken token = default); - #endregion - - - - #region 删除 - - /// - /// 删除缓存 - /// - /// 要删除的键 - void Remove(string key); - - /// - /// 异步删除缓存 - /// - /// - /// - /// - Task RemoveAsync(string key, CancellationToken token = default); - #endregion - } - -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/CodeData.cs b/src/Destiny.Core.Flow.CodeGenerator/CodeData.cs deleted file mode 100644 index 6e032635..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/CodeData.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Web; - -namespace Destiny.Core.Flow.CodeGenerator -{ - /// - /// 代码数据 - /// - public class CodeData - { - private string _sourceCode; - - /// - /// 获取或设置 源代码字符串 - /// - public string SourceCode - { - get => _sourceCode; - set => _sourceCode = HttpUtility.HtmlDecode(value); - } - - /// - /// 获取或设置 代码存储路径 - /// - public string FileName { get; set; } - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/CodeGeneratorModeule.cs b/src/Destiny.Core.Flow.CodeGenerator/CodeGeneratorModeule.cs deleted file mode 100644 index 61d9143c..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/CodeGeneratorModeule.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Destiny.Core.Flow.Modules; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.CodeGenerator -{ - /// - /// - /// - public class CodeGeneratorModeule : AppModule - { - - public override void ConfigureServices(ConfigureServicesContext context) - { - - context.Services.AddSingleton(); - context.Services.AddSingleton(); - } - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/CodeGeneratorService.cs b/src/Destiny.Core.Flow.CodeGenerator/CodeGeneratorService.cs deleted file mode 100644 index 82773cb5..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/CodeGeneratorService.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Destiny.Core.Flow.Ui; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Destiny.Core.Flow.CodeGenerator -{ - /// - /// 生成器服务实现 - /// - public class CodeGeneratorService : ICodeGeneratorService - { - - /// - /// 得到C#类型转成下拉项 - /// - /// - public OperationResponse GetCSharpTypeToSelectItem() - { - var item= TypeHelper.GetCSharpType().Select(o =>new - { - Label = o.Key.FullName, - Value=o.Value, - }); - return OperationResponse.Ok(data:item); - } - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/Destiny.Core.Flow.CodeGenerator.csproj b/src/Destiny.Core.Flow.CodeGenerator/Destiny.Core.Flow.CodeGenerator.csproj deleted file mode 100644 index bc8e5b9b..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/Destiny.Core.Flow.CodeGenerator.csproj +++ /dev/null @@ -1,41 +0,0 @@ - - - - netstandard2.1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.CodeGenerator/EntityMetadata.cs b/src/Destiny.Core.Flow.CodeGenerator/EntityMetadata.cs deleted file mode 100644 index c2066973..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/EntityMetadata.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System.Collections.Generic; - -namespace Destiny.Core.Flow.CodeGenerator -{ - /// - /// 实体元数据 - /// - public class EntityMetadata - { - - - - /// - /// 实体名 - /// - public string EntityName { get; set; } - - /// - /// 显示名 - /// - public string DisplayName { get; set; } - - /// - /// 主键类型 - /// - public string PrimaryKeyType { get; set; } - - /// - /// 主键名 - /// - - public string PrimaryKeyName { get; set; } - - - /// - /// 是否生成Dto - /// - public bool IsGeneratorDto { get; set; } - - /// - /// 属性集合 - /// - public List Properties { get; set; } = new List(); - - - /// - /// 就否自动映射(AutoMappper) - /// - public bool IsAutoMap { get; set; } - - - /// - // 是否创建 - /// - public bool IsCreation { get; set; } = true; - - - /// - /// 是否修改 - /// - public bool IsModification { get; set; } = true; - - /// - /// 是否软删除 - /// - public bool IsSoftDelete { get; set; } = true; - - /// - /// 是否全部审核 - /// - /// - public bool IsFullAudited() { - - return IsCreation && IsModification && IsSoftDelete; - } - - - /// - /// 审核用户键类型 - /// - public string AuditedUserKeyType { get; set; } - - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/ICodeGenerator.cs b/src/Destiny.Core.Flow.CodeGenerator/ICodeGenerator.cs deleted file mode 100644 index ee57399d..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/ICodeGenerator.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace Destiny.Core.Flow.CodeGenerator -{ - /// - /// 生成器 - /// - public interface ICodeGenerator - { - /// - /// 创建代码文件 - /// - /// - /// - - void GenerateCode(ProjectMetadata projectMetadata); - - /// - /// 创建实体代码 - /// - /// - /// - CodeData GenerateEntityCode(ProjectMetadata metadata); - - /// - /// 生成实体配置代码 - /// - /// 元数据 - /// - CodeData GenerateEntityConfigurationCode(ProjectMetadata metadata); - - - /// - /// 创建输入Dto码 - /// - /// 元数据 - /// - CodeData GenerateInputDtoCode(ProjectMetadata metadata); - - /// - /// 创建输出代码 - /// - /// - /// - CodeData GenerateOutputDtoCode(ProjectMetadata metadata); - - - /// - /// 创建分页Dto代码 - /// - /// - /// - CodeData GeneratePageDtoCode(ProjectMetadata metadata); - - /// - /// 生成控制器 - /// - /// - /// - CodeData GenerateController(ProjectMetadata metadata); - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/ICodeGeneratorService.cs b/src/Destiny.Core.Flow.CodeGenerator/ICodeGeneratorService.cs deleted file mode 100644 index 08fe3c3b..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/ICodeGeneratorService.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Ui; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.CodeGenerator -{ - /// - /// 生成器服务 - /// - public interface ICodeGeneratorService - { - - /// - /// 得到C#类型转换下拉项 - /// - /// - OperationResponse GetCSharpTypeToSelectItem(); - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/ProjectMetadata.cs b/src/Destiny.Core.Flow.CodeGenerator/ProjectMetadata.cs deleted file mode 100644 index ef252bcb..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/ProjectMetadata.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace Destiny.Core.Flow.CodeGenerator -{ - /// - /// 项目元数据 - /// - public class ProjectMetadata - { - /// - /// 获取或设置 公司 - /// - public string Company { get; set; } - - /// - /// 获取或设置 站点地址 - /// - public string SiteUrl { get; set; } - /// - /// 获取或设置 创建者 - /// - public string Creator { get; set; } - - - /// - /// 获取或设置 版权 - /// - public string Copyright { get; set; } - - - /// - /// 命名空间 - /// - public string Namespace { get; set; } - - /// - /// 实体元数据 - /// - - public EntityMetadata EntityMetadata { get; set; } - - /// - /// 保存文件路径 - /// - public string SaveFilePath { get; set; } - - - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/PropertyMetadata.cs b/src/Destiny.Core.Flow.CodeGenerator/PropertyMetadata.cs deleted file mode 100644 index c4890c8e..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/PropertyMetadata.cs +++ /dev/null @@ -1,66 +0,0 @@ -namespace Destiny.Core.Flow.CodeGenerator -{ - /// - /// 属性元数据 - /// - public class PropertyMetadata - { - /// - /// 是否主键 - /// - - public bool IsPrimaryKey { get; set; } = false; - /// - /// 属性名 - /// - public string PropertyName { get; set; } - - /// - /// 显示名 - /// - public string DisplayName { get; set; } - - /// - /// 是否允许为空 - /// - public bool IsNullable { get; set; } = false; - - /// - /// 默认值 - /// - public string DefaultValue { get; set; } - - - /// - /// C#数据类型 - /// - public string CSharpType { get; set; } - - - /// - /// 该字段是否生成输入DTO - /// - public bool IsInputDto { get; set; } = true; - - /// - /// 该字段是否生成输出DTO - /// - public bool IsOutputDto { get; set; } = true; - - /// - /// 该字段是否生成分页DTO - /// - public bool IsPageDto { get; set; } = true; - - - /// - /// 集合类型 - /// - public string AggregateType { get; set; } - - - - } - - -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/RazorCodeGenerator.cs b/src/Destiny.Core.Flow.CodeGenerator/RazorCodeGenerator.cs deleted file mode 100644 index 0ad4fb2f..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/RazorCodeGenerator.cs +++ /dev/null @@ -1,302 +0,0 @@ -using RazorEngine; -using RazorEngine.Templating; -using Destiny.Core.Flow.Exceptions; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using RazorEngine.Configuration; -using RazorEngine.Text; -using System.CodeDom.Compiler; - -namespace Destiny.Core.Flow.CodeGenerator -{ - /// - /// Razor引擎生成器 - /// - public class RazorCodeGenerator : ICodeGenerator - { - - - - /// - /// 生成代码 - /// - /// - public void GenerateCode(ProjectMetadata projectMetadata) - { - - List codes = new List(); - - codes.Add(GenerateEntityCode(projectMetadata)); - codes.Add(GenerateEntityConfigurationCode(projectMetadata)); - codes.Add(GenerateInputDtoCode(projectMetadata)); - codes.Add(GenerateOutputDtoCode(projectMetadata)); - codes.Add(GeneratePageDtoCode(projectMetadata)); - codes.Add(GenerateIService(projectMetadata)); - codes.Add(GenerateServiceImpl(projectMetadata)); - codes.Add(GenerateController(projectMetadata)); - foreach (var code in codes.OrderBy(o => o.FileName)) - { - var saveFilePath = $"{Path.Combine(@"{0}\{1}", projectMetadata.SaveFilePath, code.FileName)}"; - var path = Path.GetDirectoryName(saveFilePath); - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - using (var fs = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write)) - { - - using (var sw = new StreamWriter(fs)) - { - - sw.Write(code.SourceCode); - sw.Flush(); - sw.Close(); - fs.Close(); - } - } - } - } - - /// - /// 得到模版 - /// - /// - /// - /// - private string GetTemplateCode(ProjectMetadata metadata, CodeType codeType) - { - string template = GetInternalTemplate(codeType); - var key = GetKey(codeType, template); - ITemplateServiceConfiguration configuration = new TemplateServiceConfiguration() - { - Language = Language.CSharp, - //EncodedStringFactory = new RawStringFactory(), - Debug = true - }; - IRazorEngineService service = RazorEngineService.Create(configuration); - - return service.RunCompile(template, key, metadata.GetType(), metadata); - } - - - - /// - /// 创建键 - /// - /// - /// - /// - - private ITemplateKey GetKey(CodeType codeType, string template) - { - string name = $"{codeType.ToString()}-{Guid.NewGuid()}"; - return Engine.Razor.GetKey(name); - } - - /// - /// 生成实体代码 - /// - /// 元数据 - /// - - public CodeData GenerateEntityCode(ProjectMetadata metadata) - { - var template = GetTemplateCode(metadata, CodeType.Entity); - - var code = new CodeData() - { - SourceCode = template, - FileName = $"Entity/{metadata.EntityMetadata.EntityName}.cs" - }; - - return code; - } - - /// - /// 生成实体配置代码 - /// - /// 元数据 - /// - public CodeData GenerateEntityConfigurationCode(ProjectMetadata metadata) - { - var template = GetTemplateCode(metadata, CodeType.EntityConfiguration); - var code = new CodeData() - { - SourceCode = template, - FileName = $"EntityConfigurations/{metadata.EntityMetadata.EntityName}Configuration.cs" - }; - return code; - } - - /// - /// 创建输入代码 - /// - /// - /// - public CodeData GenerateInputDtoCode(ProjectMetadata metadata) - { - var template = GetTemplateCode(metadata, CodeType.InputDto); - var code = new CodeData() - { - SourceCode = template, - FileName = $"Dtos/{metadata.EntityMetadata.EntityName}s/{metadata.EntityMetadata.EntityName}InputDto.cs" - }; - return code; - } - - - /// - /// 创建输出代码 - /// - /// - /// - public CodeData GenerateOutputDtoCode(ProjectMetadata metadata) - { - var template = GetTemplateCode(metadata, CodeType.OutputDto); - var code = new CodeData() - { - SourceCode = template, - FileName = $"Dtos/{metadata.EntityMetadata.EntityName}s/{metadata.EntityMetadata.EntityName}OutputDto.cs" - }; - return code; - } - - - /// - /// 创建分页Dto代码 - /// - /// - /// - public CodeData GeneratePageDtoCode(ProjectMetadata metadata) - { - var template = GetTemplateCode(metadata, CodeType.PageListDto); - var code = new CodeData() - { - SourceCode = template, - FileName = $"Dtos/{metadata.EntityMetadata.EntityName}s/{metadata.EntityMetadata.EntityName}PageListDto.cs" - }; - return code; - } - - /// - /// 创建服务接口 - /// - /// 元数据 - /// - - public CodeData GenerateIService(ProjectMetadata metadata) - { - - var template = GetTemplateCode(metadata, CodeType.IService); - var code = new CodeData() - { - SourceCode = template, - FileName = $"IService/{metadata.EntityMetadata.EntityName}s/I{metadata.EntityMetadata.EntityName}Service.cs" - }; - return code; - } - - public CodeData GenerateServiceImpl(ProjectMetadata metadata) - { - - var template = GetTemplateCode(metadata, CodeType.ServiceImpl); - var code = new CodeData() - { - SourceCode = template, - FileName = $"Service/{metadata.EntityMetadata.EntityName}s/{metadata.EntityMetadata.EntityName}Service.cs" - }; - return code; - } - - /// - /// 生成控制器 - /// - /// - /// - public CodeData GenerateController(ProjectMetadata metadata) - { - - var template = GetTemplateCode(metadata, CodeType.Controller); - var code = new CodeData() - { - SourceCode = template, - FileName = $"{metadata.EntityMetadata.EntityName}Controller.cs" - }; - return code; - } - - /// - /// 读取指定代码类型的内置代码模板 - /// - /// 代码类型 - /// - private string GetInternalTemplate(CodeType type) - { - string projectName = Assembly.GetExecutingAssembly().GetName().Name.ToString(); - string resName = $"{projectName}.Templates.{type.ToString()}.cshtml"; - Stream stream = GetType().Assembly.GetManifestResourceStream(resName); - if (stream == null) - { - throw new AppException("没有找到对应的模板"); - } - using (StreamReader reader = new StreamReader(stream)) - { - return reader.ReadToEnd(); - } - } - - } - - public enum CodeType - { - /// - /// 实体类 - /// - Entity, - - - /// - /// 实体配置 - /// - EntityConfiguration, - - /// - /// 输出Dto - /// - OutputDto, - - - /// - /// 输入Dto - /// - InputDto, - - /// - /// 分页Dto - /// - PageListDto, - - - /// - /// 服务接口 - /// - IService, - - - /// - /// 服务接口实现 - /// - ServiceImpl, - - /// - /// 控制器 - /// 控制器 - /// 控制器 - /// - Controller, - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/Templates/Controller.cshtml b/src/Destiny.Core.Flow.CodeGenerator/Templates/Controller.cshtml deleted file mode 100644 index f88fb06a..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/Templates/Controller.cshtml +++ /dev/null @@ -1,97 +0,0 @@ -@using System; -@using Destiny.Core.Flow.CodeGenerator; -@{ - - ProjectMetadata metadata = Model; - string lowerFirstNmae = Destiny.Core.Flow.Extensions.Extensions.LowerFirstChar(metadata.EntityMetadata.EntityName); - string serive = $"{lowerFirstNmae}Service"; - string _serive = $"_{serive}"; -} -using System; -using Destiny.Core.Flow.AspNetCore.Api; -using Destiny.Core.Flow.AspNetCore.Ui; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using System.ComponentModel; -using System.Threading.Tasks; -using Destiny.Core.Flow.Filter; -using @(metadata.Namespace).Dtos; -using @(metadata.Namespace).IServices.@(metadata.EntityMetadata.EntityName)s; -@using Destiny.Core.Flow.Extensions; -namespace @(metadata.Namespace).API.Controllers -{ - - ///<summary> - ///@(string.IsNullOrEmpty(metadata.EntityMetadata.DisplayName) ? metadata.EntityMetadata.EntityName : metadata.EntityMetadata.DisplayName) - ///</summary> - [Description("@metadata.EntityMetadata.DisplayName")] - public class @(metadata.EntityMetadata.EntityName)Controller : AdminControllerBase - { - - private readonly I@(metadata.EntityMetadata.EntityName)Service @_serive; - - public @(metadata.EntityMetadata.EntityName)Controller(I@(metadata.EntityMetadata.EntityName)Service @serive) - { - @_serive=@serive; - } - - - /// <summary> - /// 异步创建@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="dto">添加的@(metadata.EntityMetadata.DisplayName)DTO</param> - [HttpPost] - [Description("异步创建@(metadata.EntityMetadata.DisplayName)")] - public async Task<AjaxResult> CreateAsync([FromBody] @(metadata.EntityMetadata.EntityName)InputDto dto) - { - return (await @(_serive).CreateAsync(dto)).ToAjaxResult(); - } - - /// <summary> - /// 异步更新@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="dto">更新的@(metadata.EntityMetadata.DisplayName)DTO</param> - [HttpPost] - [Description("异步更新@(metadata.EntityMetadata.DisplayName)")] - public async Task<AjaxResult> UpdateAsync([FromBody] @(metadata.EntityMetadata.EntityName)InputDto dto) - { - return (await @(_serive).UpdateAsync(dto)).ToAjaxResult(); - } - - /// <summary> - /// 异步加载表单@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="id">要加载的@(metadata.EntityMetadata.DisplayName)主键</param> - [HttpGet] - [Description("异步加载表单@(metadata.EntityMetadata.DisplayName)")] - public async Task<AjaxResult> LoadFormAsync(@metadata.EntityMetadata.PrimaryKeyType id) - { - return (await @(_serive).LoadFormAsync(id)).ToAjaxResult(); - } - - - /// <summary> - /// 异步删除@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="id">要删除的@(metadata.EntityMetadata.DisplayName)主键</param> - [HttpDelete] - [Description("异步删除@(metadata.EntityMetadata.DisplayName)")] - public async Task<AjaxResult> DeleteAsync(@metadata.EntityMetadata.PrimaryKeyType id) - { - return (await @(_serive).DeleteAsync(id)).ToAjaxResult(); - } - - /// <summary> - /// 异步得到@(metadata.EntityMetadata.DisplayName)分页数据 - /// </summary> - /// <param name="request">分页请求数据</param> - [HttpPost] - [Description("异步得到@(metadata.EntityMetadata.DisplayName)分页数据")] - public async Task<PageList<@(metadata.EntityMetadata.EntityName)PageListDto>> GetPageAsync(PageRequest request) - { - return (await @(_serive).GetPageAsync(request)).ToPageList(); - } - - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/Templates/Entity.cshtml b/src/Destiny.Core.Flow.CodeGenerator/Templates/Entity.cshtml deleted file mode 100644 index 8d3d6203..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/Templates/Entity.cshtml +++ /dev/null @@ -1,130 +0,0 @@ -@using System; -@using Destiny.Core.Flow.CodeGenerator; -@{ - - ProjectMetadata metadata = Model; - var userKeyType = metadata.EntityMetadata.AuditedUserKeyType; - string auditedOrSoft = string.Empty; - if (metadata.EntityMetadata.IsFullAudited()) - { - auditedOrSoft = $"{auditedOrSoft}, IFullAuditedEntity<{userKeyType}>"; - } - else - { - if (metadata.EntityMetadata.IsCreation) - { - auditedOrSoft = $"{auditedOrSoft}, ICreationAudited<{userKeyType}>"; - } - if (metadata.EntityMetadata.IsModification) - { - - auditedOrSoft = $"{auditedOrSoft}, IModificationAudited<{userKeyType}>"; - } - if (metadata.EntityMetadata.IsSoftDelete) - { - auditedOrSoft = $"{auditedOrSoft}, ISoftDelete"; - } - } - - -} -using System; -using System.Collections.Generic; -using System.ComponentModel; -using Destiny.Core.Flow.Entity; -namespace @(metadata.Namespace).Entities -{ - - /// <summary> - /// @(string.IsNullOrEmpty(metadata.EntityMetadata.DisplayName) ? metadata.EntityMetadata.EntityName : metadata.EntityMetadata.DisplayName) - /// </summary> - [DisplayName("@(metadata.EntityMetadata.DisplayName)")] - public partial class @metadata.EntityMetadata.EntityName : EntityBase<@(metadata.EntityMetadata.PrimaryKeyType)>@auditedOrSoft - { - @foreach (var property in metadata.EntityMetadata.Properties.Where(o => !o.IsPrimaryKey)) - { - - @:/// <summary> - @:/// 获取或设置 @property.DisplayName - @:/// </summary> - @:[DisplayName("@property.DisplayName")] - @:public @(string.IsNullOrEmpty(property.AggregateType)?TypeHelper.ToSingleTypeName(property.CSharpType,property.IsNullable):TypeHelper.GetAggregate(property.AggregateType,property.CSharpType,property.IsNullable)) @property.PropertyName { get; set; } - } - @{ - if (metadata.EntityMetadata.IsFullAudited()) - { - @:/// <summary> - @:/// 获取或设置最后修改用户 - @:/// </summary> - @:[DisplayName("最后修改用户")] - @:public @metadata.EntityMetadata.AuditedUserKeyType? LastModifierUserId { get; set; } - - @:/// <summary> - @:/// 获取或设置最后修改时间 - @:/// </summary> - @:[DisplayName("最后修改时间")] - @:public DateTime? LastModifionTime { get; set; } - - @:/// <summary> - @:/// 获取或设置是否删除 - @:/// </summary> - @:[DisplayName("是否删除")] - @:public bool IsDeleted { get; set; } - - @:/// <summary> - @:/// 获取或设置创建用户ID - @:/// </summary> - @:[DisplayName("创建用户ID")] - @:public @metadata.EntityMetadata.AuditedUserKeyType? CreatorUserId { get; set; } - - @:/// <summary> - @:/// 获取或设置创建时间 - @:/// </summary> - @:[DisplayName("创建时间")] - @:public DateTime CreatedTime { get; set; } - } - else - { - if (metadata.EntityMetadata.IsCreation) - { - @:/// <summary> - @:/// 获取或设置创建用户ID - @:/// </summary> - @:[DisplayName("创建用户ID")] - @:public @metadata.EntityMetadata.AuditedUserKeyType? CreatorUserId { get; set; } - - @:/// <summary> - @:/// 获取或设置创建时间 - @:/// </summary> - @:[DisplayName("创建时间")] - @:public DateTime CreatedTime { get; set; } - } - if (metadata.EntityMetadata.IsModification) - { - @:/// <summary> - @:/// 获取或设置最后修改用户 - @:/// </summary> - @:[DisplayName("最后修改用户")] - @:public @metadata.EntityMetadata.AuditedUserKeyType? LastModifierUserId { get; set; } - - @:/// <summary> - @:/// 获取或设置最后修改时间 - @:/// </summary> - @:[DisplayName("最后修改时间")] - @:public DateTime? LastModifionTime { get; set; } - } - if (metadata.EntityMetadata.IsSoftDelete) - { - @:/// <summary> - @:/// 获取或设置是否删除 - @:/// </summary> - @:[DisplayName("是否删除")] - @:public bool IsDeleted { get; set; } - } - } - - - } - - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/Templates/EntityConfiguration.cshtml b/src/Destiny.Core.Flow.CodeGenerator/Templates/EntityConfiguration.cshtml deleted file mode 100644 index 6f8c9763..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/Templates/EntityConfiguration.cshtml +++ /dev/null @@ -1,38 +0,0 @@ -@using System; -@using Destiny.Core.Flow.CodeGenerator; - -@{ - - ProjectMetadata metadata = Model; -} -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using @(metadata.Namespace).Entities; -namespace @(metadata.Namespace).EntityConfigurations -{ - - /// <summary> - /// @(string.IsNullOrEmpty(metadata.EntityMetadata.DisplayName) ? metadata.EntityMetadata.EntityName : metadata.EntityMetadata.DisplayName) - /// </summary> - public partial class @(metadata.EntityMetadata.EntityName)Configuration : EntityMappingConfiguration<@(metadata.EntityMetadata.EntityName), @(metadata.EntityMetadata.PrimaryKeyType)> - { - /// <summary> - /// 重写以实现实体类型各个属性的数据库配置 - /// </summary> - /// <param name="builder">实体类型创建器</param> - public override void Map(EntityTypeBuilder<@metadata.EntityMetadata.EntityName> builder) - { - builder.HasKey(x => x.Id); - @foreach (var property in metadata.EntityMetadata.Properties) - { - - builder.Property(x => x.@(property.PropertyName)).HasComment("@property.DisplayName").IsRequired(@((property.IsNullable==true?false:true).ToString().ToLower())); - } - - builder.ToTable("@metadata.EntityMetadata.EntityName"); - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.CodeGenerator/Templates/IService.cshtml b/src/Destiny.Core.Flow.CodeGenerator/Templates/IService.cshtml deleted file mode 100644 index e02cb5db..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/Templates/IService.cshtml +++ /dev/null @@ -1,60 +0,0 @@ - -@using Destiny.Core.Flow.CodeGenerator; - -@{ - - ProjectMetadata metadata = Model; -} - - -using System; -using @(metadata.Namespace).Dtos; -using Destiny.Core.Flow.Dependency; -using System.Threading.Tasks; -using Destiny.Core.Flow.Filter; -using Destiny.Core.Flow.Filter.Abstract; -using Destiny.Core.Flow.Ui; - - - -namespace @(metadata.Namespace).IServices.@(metadata.EntityMetadata.EntityName)s -{ - ///<summary> - ///@(string.IsNullOrEmpty(metadata.EntityMetadata.DisplayName) ? metadata.EntityMetadata.EntityName : metadata.EntityMetadata.DisplayName) - ///</summary> - public interface I@(metadata.EntityMetadata.EntityName)Service : IScopedDependency - { - /// <summary> - /// 异步创建@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="dto">添加的@(metadata.EntityMetadata.DisplayName)DTO</param> - Task<OperationResponse> CreateAsync(@(metadata.EntityMetadata.EntityName)InputDto dto); - - - /// <summary> - /// 异步更新@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="dto">更新的@(metadata.EntityMetadata.DisplayName)DTO</param> - Task<OperationResponse> UpdateAsync(@(metadata.EntityMetadata.EntityName)InputDto dto); - - /// <summary> - /// 异步加载表单@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="id">要加载的@(metadata.EntityMetadata.DisplayName)主键</param> - Task<OperationResponse<@(metadata.EntityMetadata.EntityName)OutputDto>> LoadFormAsync(@metadata.EntityMetadata.PrimaryKeyType id); - - /// <summary> - /// 异步删除@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="id">要删除的@(metadata.EntityMetadata.DisplayName)主键</param> - Task<OperationResponse> DeleteAsync(@metadata.EntityMetadata.PrimaryKeyType id); - - /// <summary> - /// 异步得到@(metadata.EntityMetadata.DisplayName)分页数据 - /// </summary> - /// <param name="request">分页请求数据</param> - Task<IPagedResult<@(metadata.EntityMetadata.EntityName)PageListDto>> GetPageAsync(PageRequest request); - - } - -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/Templates/InputDto.cshtml b/src/Destiny.Core.Flow.CodeGenerator/Templates/InputDto.cshtml deleted file mode 100644 index bc9c3a70..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/Templates/InputDto.cshtml +++ /dev/null @@ -1,39 +0,0 @@ -@using System; -@using Destiny.Core.Flow.CodeGenerator; - -@{ - - ProjectMetadata metadata = Model; -} - - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Mapping; -using @(metadata.Namespace).Entities; - -namespace @(metadata.Namespace).Dtos -{ - - /// <summary> - /// @(string.IsNullOrEmpty(metadata.EntityMetadata.DisplayName) ? metadata.EntityMetadata.EntityName : metadata.EntityMetadata.DisplayName) - /// </summary> - [AutoMapping(typeof(@metadata.EntityMetadata.EntityName))] - public partial class @(metadata.EntityMetadata.EntityName)InputDto : InputDto<@(metadata.EntityMetadata.PrimaryKeyType)> - { - @foreach (var property in metadata.EntityMetadata.Properties.Where(o => o.IsInputDto)) - { - - - @:/// <summary> - @:/// 获取或设置 @property.DisplayName - @:/// </summary> - @:public @(string.IsNullOrEmpty(property.AggregateType)?TypeHelper.ToSingleTypeName(property.CSharpType,property.IsNullable):TypeHelper.GetAggregate(property.AggregateType,property.CSharpType,property.IsNullable)) @property.PropertyName { get; set; } - - - } - - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/Templates/OutputDto.cshtml b/src/Destiny.Core.Flow.CodeGenerator/Templates/OutputDto.cshtml deleted file mode 100644 index 9449c4e6..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/Templates/OutputDto.cshtml +++ /dev/null @@ -1,39 +0,0 @@ -@using System; -@using Destiny.Core.Flow.CodeGenerator; -@{ - - ProjectMetadata metadata = Model; -} -using System; -using System.Collections.Generic; -using System.ComponentModel; -using Destiny.Core.Flow.Entity; -using @(metadata.Namespace).Entities; -using Destiny.Core.Flow.Mapping; -namespace @(metadata.Namespace).Dtos -{ - /// <summary> - /// @(string.IsNullOrEmpty(metadata.EntityMetadata.DisplayName) ? metadata.EntityMetadata.EntityName : metadata.EntityMetadata.DisplayName) - /// </summary> -@if (metadata.EntityMetadata.IsAutoMap) -{ - - @:[AutoMapping(typeof(@metadata.EntityMetadata.EntityName))] - -} - public partial class @(metadata.EntityMetadata.EntityName)OutputDto : OutputDto<@(metadata.EntityMetadata.PrimaryKeyType)> - { -@foreach (var property in metadata.EntityMetadata.Properties.Where(o => o.IsOutputDto)) -{ - - @:/// <summary> - @:/// 获取或设置 @property.DisplayName - @:/// </summary> - @:public @(string.IsNullOrEmpty(property.AggregateType)?TypeHelper.ToSingleTypeName(property.CSharpType,property.IsNullable):TypeHelper.GetAggregate(property.AggregateType,property.CSharpType,property.IsNullable)) @property.PropertyName { get; set; } - - -} - - } - -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/Templates/PageListDto.cshtml b/src/Destiny.Core.Flow.CodeGenerator/Templates/PageListDto.cshtml deleted file mode 100644 index 5835337a..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/Templates/PageListDto.cshtml +++ /dev/null @@ -1,40 +0,0 @@ -@using System; -@using Destiny.Core.Flow.CodeGenerator; - -@{ - - ProjectMetadata metadata = Model; -} -using System; -using System.Collections.Generic; -using System.ComponentModel; -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Mapping; -using @(metadata.Namespace).Entities; -namespace @(metadata.Namespace).Dtos -{ - - /// <summary> - /// @(string.IsNullOrEmpty(metadata.EntityMetadata.DisplayName) ? metadata.EntityMetadata.EntityName : metadata.EntityMetadata.DisplayName) - /// </summary> -@if (metadata.EntityMetadata.IsAutoMap) -{ - - @:[AutoMapping(typeof(@metadata.EntityMetadata.EntityName))] -} - public partial class @(metadata.EntityMetadata.EntityName)PageListDto : OutputDto<@(metadata.EntityMetadata.PrimaryKeyType)> - { -@foreach (var property in metadata.EntityMetadata.Properties.Where(o => o.IsPageDto)) -{ - - @:/// <summary> - @:/// 获取或设置 @property.DisplayName - @:/// </summary> - @:public @(string.IsNullOrEmpty(property.AggregateType)?TypeHelper.ToSingleTypeName(property.CSharpType,property.IsNullable):TypeHelper.GetAggregate(property.AggregateType,property.CSharpType,property.IsNullable)) @property.PropertyName { get; set; } - - -} - - } - -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/Templates/ServiceImpl.cshtml b/src/Destiny.Core.Flow.CodeGenerator/Templates/ServiceImpl.cshtml deleted file mode 100644 index 0dce4bf7..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/Templates/ServiceImpl.cshtml +++ /dev/null @@ -1,94 +0,0 @@ -@using System; -@using Destiny.Core.Flow.CodeGenerator; - - -@{ - - ProjectMetadata metadata = Model; - string lowerFirstNmae = Destiny.Core.Flow.Extensions.Extensions.LowerFirstChar(metadata.EntityMetadata.EntityName); - string iRepository = $"_{lowerFirstNmae}Repository"; - string repository = $"{lowerFirstNmae}Repository"; -} - - -using System; -using @(metadata.Namespace).Dtos; -using System.Threading.Tasks; -using Destiny.Core.Flow.Filter; -using Destiny.Core.Flow.Filter.Abstract; -using Destiny.Core.Flow.Ui; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow; -using Destiny.Core.Flow.Enums; -using Microsoft.Extensions.DependencyInjection; -using @(metadata.Namespace).Entities; -using @(metadata.Namespace).IServices.@(metadata.EntityMetadata.EntityName)s; - - -namespace @(metadata.Namespace).Services.@(metadata.EntityMetadata.EntityName)s -{ - /// <summary> - ///@(string.IsNullOrEmpty(metadata.EntityMetadata.DisplayName) ? metadata.EntityMetadata.EntityName : metadata.EntityMetadata.DisplayName) - /// </summary> - public class @(metadata.EntityMetadata.EntityName)Service : I@(metadata.EntityMetadata.EntityName)Service - { - - private readonly IRepository<@(metadata.EntityMetadata.EntityName), @(metadata.EntityMetadata.PrimaryKeyType)> @iRepository; - - /// <summary> - /// 初始化一个<see cref="@(metadata.EntityMetadata.EntityName)Service"/>类型的新实例 - /// </summary> - public @(metadata.EntityMetadata.EntityName)Service(IRepository<@(metadata.EntityMetadata.EntityName), @(metadata.EntityMetadata.PrimaryKeyType)> @repository) - { - @(iRepository) = @(repository); - } - - /// <summary> - /// 异步创建@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="dto">添加的@(metadata.EntityMetadata.DisplayName)DTO</param> - public async Task<OperationResponse> CreateAsync(@(metadata.EntityMetadata.EntityName)InputDto dto) - { - return await @(iRepository).InsertAsync(dto); - } - - - /// <summary> - /// 异步更新@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="dto">更新的@(metadata.EntityMetadata.DisplayName)DTO</param> - public async Task<OperationResponse> UpdateAsync(@(metadata.EntityMetadata.EntityName)InputDto dto) - { - return await @(iRepository).UpdateAsync(dto); - } - - /// <summary> - /// 异步加载表单@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="id">要加载的@(metadata.EntityMetadata.DisplayName)主键</param> - public async Task<OperationResponse<@(metadata.EntityMetadata.EntityName)OutputDto>> LoadFormAsync(@metadata.EntityMetadata.PrimaryKeyType id) - { - var dto = (await @(iRepository).GetByIdAsync(id)).MapTo<@(metadata.EntityMetadata.EntityName)OutputDto>(); - return new OperationResponse<@(metadata.EntityMetadata.EntityName)OutputDto>("加载成功",dto,OperationResponseType.Success); - } - - /// <summary> - /// 异步删除@(metadata.EntityMetadata.DisplayName) - /// </summary> - /// <param name="id">要删除的@(metadata.EntityMetadata.DisplayName)主键</param> - public Task<OperationResponse> DeleteAsync(@metadata.EntityMetadata.PrimaryKeyType id) - { - id.NotEmpty(nameof(id)); - return @(iRepository).DeleteAsync(id); - } - - /// <summary> - /// 异步得到@(metadata.EntityMetadata.DisplayName)分页数据 - /// </summary> - /// <param name="request">分页请求数据</param> - public Task<IPagedResult<@(metadata.EntityMetadata.EntityName)PageListDto>> GetPageAsync(PageRequest request) - { - return @(iRepository).Entities.ToPageAsync<@(metadata.EntityMetadata.EntityName),@(metadata.EntityMetadata.EntityName)PageListDto>(request); - } - } -} diff --git a/src/Destiny.Core.Flow.CodeGenerator/TypeHelper.cs b/src/Destiny.Core.Flow.CodeGenerator/TypeHelper.cs deleted file mode 100644 index 0411a844..00000000 --- a/src/Destiny.Core.Flow.CodeGenerator/TypeHelper.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Destiny.Core.Flow.CodeGenerator -{ - /// - /// 类型帮助 - /// - public static class TypeHelper - { - - /// - /// c#类型 - /// - private static readonly Dictionary _cSharpType = new Dictionary - { - - { typeof(bool), "bool" }, - { typeof(byte), "byte" }, - { typeof(char), "char" }, - { typeof(decimal), "decimal" }, - { typeof(double), "double" }, - { typeof(float), "float" }, - { typeof(int), "int" }, - { typeof(long), "long" }, - { typeof(object), "object" }, - { typeof(sbyte), "sbyte" }, - { typeof(short), "short" }, - { typeof(string), "string" }, - { typeof(uint), "uint" }, - { typeof(ulong), "ulong" }, - { typeof(ushort), "ushort" }, - { typeof(Guid),"Guid"} - }; - - /// - /// 得到c#类型 - /// - /// - public static Dictionary GetCSharpType() - { - - return _cSharpType; - } - - /// - /// 根据类型全称转成类型名 - /// - /// - /// - public static string ToTypeName(string typeFullName) - { - return _cSharpType.Where(o => o.Key.FullName == typeFullName)?.FirstOrDefault().Value; - } - - - public static string ToSingleTypeName(string cSharpType, bool isNullable) - { - - if (cSharpType == typeof(string).Name.ToLower()) - { - return cSharpType; - } - - return $"{cSharpType}{(isNullable ? "?" : "")}"; - } - - /// - /// 得到想要的集合 - /// - /// 集合名 - /// 类型 - /// 是否可空 - /// 返回转后集合 - public static string GetAggregate(string aggregateName, string cSharpType, bool isNullable) - { - //Guid? [] - //List// - //IEnumerable// - //ICollection - //[] - if (aggregateName == "[]") //数组 - { - return $"{TypeHelper.ToSingleTypeName(cSharpType,isNullable)}{aggregateName}"; - } - else { - - return $"{aggregateName}<{TypeHelper.ToSingleTypeName(cSharpType,isNullable)}>"; - } - - - } - - } -} diff --git a/src/Destiny.Core.Flow.Consul/Destiny.Core.Flow.Consul.csproj b/src/Destiny.Core.Flow.Consul/Destiny.Core.Flow.Consul.csproj deleted file mode 100644 index 669bc5c5..00000000 --- a/src/Destiny.Core.Flow.Consul/Destiny.Core.Flow.Consul.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - netstandard2.1 - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.Consul/DestinyConsulModule.cs b/src/Destiny.Core.Flow.Consul/DestinyConsulModule.cs deleted file mode 100644 index 4bf3136e..00000000 --- a/src/Destiny.Core.Flow.Consul/DestinyConsulModule.cs +++ /dev/null @@ -1,94 +0,0 @@ -using Consul; -using Destiny.Core.Flow.ConsulEntity; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Destiny.Core.Flow.Network; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using System; - -namespace Destiny.Core.Flow.Consul -{ - /// - /// Consul服务发现模块 - /// - public abstract class DestinyConsulModule : AppModule - { - /// - /// 服务地址 - /// - /// Consul服务地址 - /// - private string _consulIp = string.Empty; - /// - /// Consul服务端口 - /// - private int _consulPort = 80; - /// - /// docker容器内部端口 - /// - private int _prot = 80; - /// - /// 获取配置文件 - /// - /// - /// - /// - public override void ConfigureServices(ConfigureServicesContext context) - { - IConfiguration configuration = context.Services.GetConfiguration(); - _consulIp = configuration["Consul:IP"]; - _consulPort = /*Convert.ToInt32(configuration["Consul:Port"])*/configuration["Consul:Port"].AsTo(); - _prot = /*Convert.ToInt32(configuration["Service:Port"])*/configuration["Service:Port"].AsTo(); - _serviceName = configuration["Service:Name"]; - } - - - /// - /// 注册Consul - /// - /// - public override void ApplicationInitialization(ApplicationContext context) - { - var app = context.GetApplicationBuilder(); - ServiceEntity serviceEntity = new ServiceEntity - { - IP = NetworkHelper.LocalIPAddress, - Port = _prot,//如果使用的是docker 进行部署这个需要和dockerfile中的端口保证一致 - ServiceName = _serviceName, - ConsulIP = _consulIp, - ConsulPort = _consulPort - }; - var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{serviceEntity.ConsulIP}:{serviceEntity.ConsulPort}"));//请求注册的 Consul 地址 - var httpCheck = new AgentServiceCheck() - { - DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册 - Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔 - HTTP = $"http://{serviceEntity.IP}:{serviceEntity.Port}/api/health",//健康检查地址 - Timeout = TimeSpan.FromSeconds(1) - }; - Console.WriteLine($"我是服务IP和端口:{serviceEntity.IP}:{serviceEntity.Port}"); - // Register service with consul - var registration = new AgentServiceRegistration() - { - Checks = new[] { httpCheck }, - ID = Guid.NewGuid().ToString(), - Name = serviceEntity.ServiceName, - Address = serviceEntity.IP, - Port = serviceEntity.Port, - Tags = new[] { $"urlprefix-/{serviceEntity.ServiceName}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别 - }; - consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起) - var lifetime = context.ServiceProvider.GetRequiredService(); - lifetime.ApplicationStopping.Register(() => - { - consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册 - }); - } - - - } -} diff --git a/src/Destiny.Core.Flow.Dtos/Destiny.Core.Flow.Dtos.csproj b/src/Destiny.Core.Flow.Dtos/Destiny.Core.Flow.Dtos.csproj index 373e18d0..6c296a9f 100644 --- a/src/Destiny.Core.Flow.Dtos/Destiny.Core.Flow.Dtos.csproj +++ b/src/Destiny.Core.Flow.Dtos/Destiny.Core.Flow.Dtos.csproj @@ -5,13 +5,16 @@ - - + + + + + diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/DatabaseTypeAttribute.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/DatabaseTypeAttribute.cs deleted file mode 100644 index 249ff3f9..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/DatabaseTypeAttribute.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Destiny.Core.Flow.Entity; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow -{ - - [AttributeUsage(AttributeTargets.Class)] - public class DatabaseTypeAttribute: Attribute - { - public DatabaseTypeAttribute(DatabaseType databaseType) - { - - DatabaseType = databaseType; - - - } - - public DatabaseType DatabaseType { get; private set; } - } -} diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/DbContextExtensions.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/DbContextExtensions.cs deleted file mode 100644 index 2690d7c6..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/DbContextExtensions.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow -{ - /// - /// 上下文扩展 - /// - public static class DbContextExtensions - { - /// - /// 当前上下文是否是关系型数据库 - /// - public static bool IsRelationalTransaction(this DbContext context) - { - return context.Database.GetService() is IRelationalTransactionManager; - } - } -} diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/DbContextOptionsBuilderExtensions..cs b/src/Destiny.Core.Flow.EntityFrameworkCore/DbContextOptionsBuilderExtensions..cs deleted file mode 100644 index 932448ab..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/DbContextOptionsBuilderExtensions..cs +++ /dev/null @@ -1,22 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow -{ - public static class DbContextOptionsBuilderExtenions - { - - - public static void MigrationsAssembly(this DbContextOptionsBuilder optionsBuilder, string migrationsAssemblyName) - { - if (!migrationsAssemblyName.IsNullOrEmpty()) - { - optionsBuilder.MigrationsAssembly(migrationsAssemblyName); - - } - } - } -} diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/DbContexts/DbContextBase.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/DbContexts/DbContextBase.cs deleted file mode 100644 index 7305f2d3..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/DbContexts/DbContextBase.cs +++ /dev/null @@ -1,215 +0,0 @@ -using Destiny.Core.Flow.Audit.Dto; -using Destiny.Core.Flow.Audit.EntityHistory; -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Options; -using Destiny.Core.Flow.Reflection; -using DnsClient.Internal; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.ChangeTracking; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Principal; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow -{ - - /// - /// 上下文基类 - /// - public abstract class DbContextBase : DbContext - { - protected readonly IServiceProvider _serviceProvider = null; - protected readonly AppOptionSettings _option = null; - protected readonly Microsoft.Extensions.Logging.ILogger _logger = null; - private readonly IPrincipal _principal; - protected DbContextBase(DbContextOptions options, IServiceProvider serviceProvider) - : base(options) - { - _serviceProvider = serviceProvider; - _option = serviceProvider.GetService>()?.Value; - _logger = serviceProvider.GetLogger(GetType()); - _principal = serviceProvider.GetService(); - } - - public IUnitOfWork UnitOfWork { get; set; } - - - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - base.OnModelCreating(modelBuilder); - var typeFinder = _serviceProvider.GetService(); - - IEntityMappingConfiguration[] mappings = typeFinder.Find(o => o.IsDeriveClassFrom()).Select(o => Activator.CreateInstance(o) as IEntityMappingConfiguration).ToArray(); - foreach (var item in mappings) - { - item.Map(modelBuilder); - } - } - - /// - /// 异步保存 - /// - /// - /// - - public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) - { - ApplyConcepts(); - var result = OnBeforeSaveChanges(); - //SavedChanges += DbContextBase_SavedChanges;//EFCore 5.X自带事件触发 - int count = await base.SaveChangesAsync(cancellationToken); - _logger.LogInformation($"成功保存{count}条数据"); - return count; - } - private void CheckAdd(EntityEntry entity) - { - - var creationAudited = entity.GetType().GetInterface(typeof(ICreationAudited<>).Name); - - if (!creationAudited.IsNull()) - { - var typeArguments = creationAudited?.GenericTypeArguments[0]; - } - //if (creationAudited == null) - //{ - // return entity; - //} - - //var typeArguments = creationAudited?.GenericTypeArguments[0]; - //var fullName = typeArguments?.FullName; - //if (fullName == typeof(Guid).FullName) - //{ - // entity = CheckIModificationAudited(entity); - //} - - //return entity; - } - - /// - /// 设置公共属性 - /// - - protected virtual void ApplyConcepts() - { - var entries = this.FindChangedEntries().ToList(); - foreach (var entity in entries) - { - - if (entity.Entity is ICreationAudited createdTime && entity.State == EntityState.Added) - { - createdTime.CreatedTime = DateTime.Now; - createdTime.CreatorUserId = _principal?.Identity?.GetUesrId(); - } - - if (entity.State == EntityState.Modified) - { - if (entity.Entity is IModificationAudited modificationAuditedUserId) - { - modificationAuditedUserId.LastModifionTime = DateTime.Now; - modificationAuditedUserId.LastModifierUserId = _principal?.Identity?.GetUesrId(); - } - - //if (entity.Entity is ISoftDelete softDelete) - //{ - - // softDelete.IsDeleted = true; - //} - } - - } - } - - /// - /// 准备重写 - /// - /// - /// - protected virtual void OnCompleted(int count, object sender) - { - - if (_option.AuditEnabled) - { - if (count > 0 && sender != null && sender is List senders) - { - var scoped = _serviceProvider.GetService(); - var auditChange = scoped.AuditChange; - if (auditChange != null) - { - auditChange.AuditEntitys.AddRange(senders); - } - - - } - } - _logger.LogInformation($"进入保存更新成功方法"); - } - protected virtual object OnBeforeSaveChanges() - { - _logger.LogInformation($"进入开始保存更改方法"); - return GetAuditEntitys(); - } - - - protected virtual IEnumerable GetAuditEntitys() - { - if (!_option.AuditEnabled) - { - return null; - } - IEnumerable entityEntry = FindChangedEntries(); - return _serviceProvider.GetRequiredService()?.GetAuditEntity(entityEntry); - - } - /// - /// 保存更改 - /// - /// - public override int SaveChanges() - { - ApplyConcepts(); - var result = OnBeforeSaveChanges(); - int count = base.SaveChanges(); - _logger.LogInformation($"成功保存{count}条数据"); - OnAfterSaveChanges(); - OnCompleted(count, result); - return count; - } - /// - /// 结束保存 - /// - protected virtual void OnAfterSaveChanges() - { - - _logger.LogInformation($"进入结束保存更改"); - } - - protected virtual IReadOnlyList FindChangedEntries() - { - return this.ChangeTracker.Entries() - .Where(x => - x.State == EntityState.Added || - x.State == EntityState.Modified || - x.State == EntityState.Deleted) - .ToList(); - } - - protected virtual bool HasCreationAuditedIdProperty(EntityEntry entity) - { - return entity.GetType().GetProperty(nameof(ICreationAudited.CreatorUserId)) != null; - } - protected virtual bool HasCreatedTimeProperty(EntityEntry entity) - { - return entity.GetType().GetProperty(nameof(ICreationAudited.CreatedTime)) != null; - } - } - - -} diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/DbContexts/DefaultDbContext.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/DbContexts/DefaultDbContext.cs deleted file mode 100644 index fb2a9dc2..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/DbContexts/DefaultDbContext.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Destiny.Core.Flow.Audit; -using Destiny.Core.Flow.Audit.Dto; -using Destiny.Core.Flow.Audit.EntityHistory; - -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Events.EventBus; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Options; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.ChangeTracking; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow -{ - public class DefaultDbContext : DbContextBase - { - - public DefaultDbContext(DbContextOptions options, IServiceProvider serviceProvider) - : base(options, serviceProvider) - { - - } - - - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/DbDrivens/MySqlDbContextDrivenProvider.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/DbDrivens/MySqlDbContextDrivenProvider.cs deleted file mode 100644 index f51788cb..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/DbDrivens/MySqlDbContextDrivenProvider.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Entity; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.DbDrivens -{ - [DatabaseType(DatabaseType.MySql), Dependency(ServiceLifetime.Singleton, AddSelf = true)] - - /// - /// MYsql驱动提供者 - /// - public class MySqlDbContextDrivenProvider : IDbContextDrivenProvider - { - - public DbContextOptionsBuilder Builder(DbContextOptionsBuilder builder, string connectionString, DestinyContextOptionsBuilder optionsBuilder) - { - //builder.UseMySql(connectionString, options => options.MigrationsAssembly(optionsBuilder.MigrationsAssemblyName)); - builder.UseMySql(connectionString,new MySqlServerVersion(new Version(8,0,21)), options => options.MigrationsAssembly(optionsBuilder.MigrationsAssemblyName)); - return builder; - } - } -} diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/DbDrivens/SqlServerDbContextDrivenProvider.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/DbDrivens/SqlServerDbContextDrivenProvider.cs deleted file mode 100644 index 8fa82f81..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/DbDrivens/SqlServerDbContextDrivenProvider.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Entity; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.DbDrivens -{ - [DatabaseType(DatabaseType.SqlServer), Dependency(ServiceLifetime.Singleton, AddSelf = true)] - /// - /// SqlServer驱动提供者 - /// - public class SqlServerDbContextDrivenProvider : IDbContextDrivenProvider - { - - public DbContextOptionsBuilder Builder(DbContextOptionsBuilder builder, string connectionString, DestinyContextOptionsBuilder optionsBuilder) - { - builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(optionsBuilder.MigrationsAssemblyName)); - return builder; - } - } -} diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Destiny.Core.Flow.EntityFrameworkCore.csproj b/src/Destiny.Core.Flow.EntityFrameworkCore/Destiny.Core.Flow.EntityFrameworkCore.csproj deleted file mode 100644 index 839133d4..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Destiny.Core.Flow.EntityFrameworkCore.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - netstandard2.1 - Destiny.Core.Flow - - - - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/EntityFrameworkCoreModule.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/EntityFrameworkCoreModule.cs deleted file mode 100644 index f7745625..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/EntityFrameworkCoreModule.cs +++ /dev/null @@ -1,51 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Events; -using Destiny.Core.Flow.Modules; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; - -namespace Destiny.Core.Flow -{ - [DependsOn( - typeof(MediatorAppModule) - - )] - public class EntityFrameworkCoreModule : AppModule - { - public override void ConfigureServices(ConfigureServicesContext context) - { - AddDestinyDbContextWnitUnitOfWork(context.Services); - AddRepository(context.Services); - } - - - - /// - /// 添加仓储 - /// - /// - /// - protected virtual IServiceCollection AddRepository(IServiceCollection services) - { - - services.AddScoped(typeof(IRepository<,>), typeof(Repository<,>)); - return services; - } - - - /// - /// 添加上下文与工作单元 - /// - /// - /// - - protected virtual IServiceCollection AddDestinyDbContextWnitUnitOfWork(IServiceCollection services) { - - services.AddDestinyDbContext(); - services.AddUnitOfWork(); - return services; - } - - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/IDbContextDrivenProvider.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/IDbContextDrivenProvider.cs deleted file mode 100644 index 78b0a10a..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/IDbContextDrivenProvider.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Entity; -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow -{ - - /// - /// 上下文驱动提供者 - /// - public interface IDbContextDrivenProvider - { - - - /// - /// 构建数据库驱动 - /// - /// - /// - /// - - DbContextOptionsBuilder Builder(DbContextOptionsBuilder builder,string connectionString, DestinyContextOptionsBuilder optionsBuilder); - - - } -} diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Interceptor/AuditInterceptor.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/Interceptor/AuditInterceptor.cs deleted file mode 100644 index 6e77f592..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Interceptor/AuditInterceptor.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Microsoft.EntityFrameworkCore.Diagnostics; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Interceptor -{ - public class AuditInterceptor: SaveChangesInterceptor - { - protected readonly IServiceProvider _serviceProvider = null; - - public AuditInterceptor(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - - public override int SavedChanges(SaveChangesCompletedEventData eventData, int result) - { - return base.SavedChanges(eventData, result); - } - } -} diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/EntityMappingConfigurationOfModel.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/EntityMappingConfigurationOfModel.cs deleted file mode 100644 index 03510694..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/EntityMappingConfigurationOfModel.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using System; - -namespace Destiny.Core.Flow -{ - public abstract class EntityMappingConfiguration : IEntityMappingConfiguration where TEntity : class, IEntity - where TKey : IEquatable - { - public virtual Type DbContextType => typeof(DefaultDbContext); - - public Type EntityType => typeof(TEntity); - - public void Map(ModelBuilder b) - { - Map(b.Entity()); - - if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity))) - { - b.Entity().HasQueryFilter(m => ((ISoftDelete)m).IsDeleted == false); - } - } - - public abstract void Map(EntityTypeBuilder b); - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/IEntityMappingConfiguration.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/IEntityMappingConfiguration.cs deleted file mode 100644 index ed9a6bfb..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/IEntityMappingConfiguration.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; - -namespace Destiny.Core.Flow -{ - public interface IEntityMappingConfiguration - { - void Map(ModelBuilder b); - - Type DbContextType { get; } - - /// - /// 获取 相应的实体类型 - /// - Type EntityType { get; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/IEntityMappingConfigurationOfModel.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/IEntityMappingConfigurationOfModel.cs deleted file mode 100644 index 37e99a2d..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/IEntityMappingConfigurationOfModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using System; - -namespace Destiny.Core.Flow -{ - public interface IEntityMappingConfiguration : IEntityMappingConfiguration where TEntity : class, IEntity - where TKey : IEquatable - { - void Map(EntityTypeBuilder builder); - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/ModelBuilderExtenions.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/ModelBuilderExtenions.cs deleted file mode 100644 index 2bf467f8..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Mapping/ModelBuilderExtenions.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -namespace Destiny.Core.Flow -{ - public static class ModelBuilderExtenions - { - public static IEnumerable GetMappingTypes(this Assembly assembly, Type mappingInterface) - { - return assembly.GetTypes().Where(x => !x.IsAbstract && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface)); - } - - public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder, Assembly assembly) - { - var mappingTypes = assembly.GetMappingTypes(typeof(IEntityMappingConfiguration<,>)); - foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast()) - { - config.Map(modelBuilder); - } - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Repository.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/Repository.cs deleted file mode 100644 index d1e8f98c..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Repository.cs +++ /dev/null @@ -1,716 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Ui; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Security.Principal; -using System.Threading; -using System.Threading.Tasks; -using Z.EntityFramework.Plus; - -namespace Destiny.Core.Flow -{ - public class Repository : IRepository - where TEntity : class, IEntity - where TPrimaryKey : IEquatable - { - /// - /// - private readonly DbSet _dbSet = null; - - private readonly DbContext _dbContext = null; - - private readonly ILogger _logger = null; - - private readonly IPrincipal _principal; - - public Repository(IServiceProvider serviceProvider) - { - UnitOfWork = (serviceProvider.GetService(typeof(IUnitOfWork)) as IUnitOfWork); - _dbContext = UnitOfWork.GetDbContext(); - _dbSet = _dbContext.Set(); - _logger = serviceProvider.GetLogger>(); - _principal = serviceProvider.GetService(); - } - - #region 查询 - - public virtual IUnitOfWork UnitOfWork { get; } - - /// - /// 获取 不跟踪数据更改(NoTracking)的查询数据源 - /// - public virtual IQueryable Entities => _dbSet.AsNoTracking(); - - /// - /// 获取 跟踪数据更改(Tracking)的查询数据源 - /// - public virtual IQueryable TrackEntities => _dbSet; - - /// - /// 根据ID得到实体 - /// - /// 主键 - /// 返回查询后实体 - public virtual TEntity GetById(TPrimaryKey primaryKey) => _dbSet.Find(primaryKey); - - /// - /// 异步根据ID得到实体 - /// - /// 主键 - /// 返回查询后实体 - public virtual async Task GetByIdAsync(TPrimaryKey primaryKey) => await _dbSet.FindAsync(primaryKey); - - - - /// - ///查询不跟踪数据源 - /// - /// 条件 - /// 返回查询后数据源 - public virtual IQueryable Query(Expression> predicate) - { - predicate.NotNull(nameof(predicate)); - return this.Entities.Where(predicate); - } - - /// - /// 查询不跟踪数据源 - /// - /// - /// 条件 - /// 数据筛选表达式 - /// 返回查询后数据源 - public virtual IQueryable Query(Expression> predicate, Expression> selector) - { - predicate.NotNull(nameof(predicate)); - selector.NotNull(nameof(selector)); - return this.Entities.Where(predicate).Select(selector); - } - - /// - ///查询跟踪数据源 - /// - /// 条件 - /// 返回查询后数据源 - public virtual IQueryable TrackQuery(Expression> predicate) - { - predicate.NotNull(nameof(predicate)); - return this.TrackEntities.Where(predicate); - } - - /// - /// 异步得到实体 - /// - /// 条件 - /// 返回查询后实体 - - public Task GetAsync(Expression> predicate) - { - - predicate.NotNull(nameof(predicate)); - return this._dbSet.FirstOrDefaultAsync(predicate); - } - - - - /// - /// 异步判断是否存 - /// - /// 要判断的条件 - /// 返回true/false,若存在true,则false - public Task ExistAsync(Expression> predicate) - { - predicate.NotNull(nameof(predicate)); - return this.Entities.AnyAsync(predicate); - } - - #endregion 查询 - - #region 添加 - - /// - /// 以异步DTO插入实体 - /// - /// 添加DTO类型 - /// 添加DTO - /// 添加信息合法性检查委托 - /// 由DTO到实体的转换委托 - /// 业务操作结果 - public virtual async Task InsertAsync(TInputDto dto, Func checkFunc = null, Func> insertFunc = null, Func completeFunc = null) where TInputDto : IInputDto - { - dto.NotNull(nameof(dto)); - - try - { - if (checkFunc.IsNotNull()) - { - await checkFunc(dto); - } - - TEntity entity = dto.MapTo(); - - if (!insertFunc.IsNull()) - { - entity = await insertFunc(dto, entity); - } - //entity = CheckInsert(entity); - await _dbSet.AddAsync(entity); - - if (completeFunc.IsNotNull()) - { - dto = completeFunc(entity); - } - - int count = await _dbContext.SaveChangesAsync(); - return new OperationResponse(count > 0 ? "添加成功" : "操作没有引发任何变化", count > 0 ? OperationResponseType.Success : OperationResponseType.NoChanged); - } - catch (AppException e) - { - return new OperationResponse(e.Message, OperationResponseType.Error); - } - catch (Exception ex) - { - return new OperationResponse(ex.Message, OperationResponseType.Error); - } - } - /// - /// 异步添加单条实体 - /// - /// - /// - public virtual async Task InsertAsync(TEntity entity, Func checkFunc = null, Func> insertFunc = null, Func completeFunc = null) - { - entity.NotNull(nameof(entity)); - try - { - if (checkFunc.IsNotNull()) - { - await checkFunc(entity); - } - if (!insertFunc.IsNull()) - { - entity = await insertFunc(entity, entity); - } - //entity = CheckInsert(entity); - await _dbSet.AddAsync(entity); - - if (completeFunc.IsNotNull()) - { - entity = completeFunc(entity); - } - int count = await _dbContext.SaveChangesAsync(); - return new OperationResponse(count > 0 ? "添加成功" : "操作没有引发任何变化", count > 0 ? OperationResponseType.Success : OperationResponseType.NoChanged); - } - catch (AppException e) - { - return new OperationResponse(e.Message, OperationResponseType.Error); - } - catch (Exception ex) - { - return new OperationResponse(ex.Message, OperationResponseType.Error); - } - - } - - /// - /// 以异步插入实体 - /// - /// 要插入实体 - /// - public virtual async Task InsertAsync(TEntity entity) - { - entity.NotNull(nameof(entity)); - //entity = CheckInsert(entity); - - await _dbSet.AddAsync(entity); - return await _dbContext.SaveChangesAsync(); - } - - /// - /// 以异步批量插入实体 - /// - /// 要插入实体集合 - /// - public virtual async Task InsertAsync(TEntity[] entitys) - { - entitys.NotNull(nameof(entitys)); - //entitys = CheckInsert(entitys); - - await _dbSet.AddRangeAsync(entitys); - return await _dbContext.SaveChangesAsync(); - } - - /// - /// 以批量插入实体 - /// - /// 要插入实体集合 - /// - public virtual int Insert(params TEntity[] entitys) - { - entitys.NotNull(nameof(entitys)); - //entitys = CheckInsert(entitys); - _dbSet.AddRange(entitys); - return _dbContext.SaveChanges(); - } - - #endregion 添加 - - #region 更新 - - /// - /// 以异步DTO更新实体 - /// - /// 更新DTO类型 - /// 更新DTO - /// 添加信息合法性检查委托 - /// 由DTO到实体的转换委托 - /// 业务操作结果 - public virtual async Task UpdateAsync(TInputDto dto, Func checkFunc = null, Func> updateFunc = null) where TInputDto : class, IInputDto, new() - { - dto.NotNull(nameof(dto)); - try - { - TEntity entity = await this.GetByIdAsync(dto.Id); - - if (entity.IsNull()) - { - return new OperationResponse($"该{dto.Id}键的数据不存在", OperationResponseType.QueryNull); - } - - if (checkFunc.IsNotNull()) - { - await checkFunc(dto, entity); - } - - entity = dto.MapTo(entity); - if (!updateFunc.IsNull()) - { - entity = await updateFunc(dto, entity); - } - //entity = CheckUpdate(entity); - _dbSet.Update(entity); - int count = await _dbContext.SaveChangesAsync(); - return new OperationResponse(count > 0 ? "更新成功" : "操作没有引发任何变化", count > 0 ? OperationResponseType.Success : OperationResponseType.NoChanged); - } - catch (AppException e) - { - return new OperationResponse(e.Message, OperationResponseType.Error); - } - catch (Exception ex) - { - throw ex; - } - } - - /// - /// 异步更新 - /// - /// 要更新实体 - /// 返回更新受影响条数 - public virtual async Task UpdateAsync(TEntity entity) - { - entity.NotNull(nameof(entity)); - //entity = CheckUpdate(entity); - _dbSet.Update(entity); - int count = await _dbContext.SaveChangesAsync(); - return count; - } - - /// - /// 同步更新 - /// - /// 要更新实体 - /// 返回更新受影响条数 - public int Update(TEntity entity) - { - entity.NotNull(nameof(entity)); - //entity = CheckUpdate(entity); - _dbSet.Update(entity); - int count = _dbContext.SaveChanges(); - return count; - } - - /// - /// 异步批量更新 - /// - /// - /// - /// - /// - public virtual async Task UpdateBatchAsync(Expression> predicate, Expression> updateExpression, CancellationToken cancellationToken = default) - { - predicate.NotNull(nameof(predicate)); - predicate.NotNull(nameof(updateExpression)); - //updateExpression = CheckUpdate(updateExpression); - - return await this.TrackEntities.Where(predicate).UpdateAsync(updateExpression, cancellationToken); - } - - #endregion 更新 - - #region 删除 - - /// - /// 删除 - /// - /// 主键 - /// 删除合法性检查委托 - /// - public virtual async Task DeleteAsync(TPrimaryKey primaryKey,Func checkFunc = null) - { - TEntity entity = await this.GetByIdAsync(primaryKey); - - if (entity.IsNull()) - { - return new OperationResponse($"该{primaryKey}键的数据不存在", OperationResponseType.QueryNull); - } - - try - { - if (checkFunc.IsNotNull()) - { - - await checkFunc(entity); - } - CheckDelete(entity); - - int count = await _dbContext.SaveChangesAsync(); - return new OperationResponse(count > 0 ? "删除成功" : "操作没有引发任何变化", count > 0 ? OperationResponseType.Success : OperationResponseType.NoChanged); - } - catch (AppException app) - { - return OperationResponse.Error(app.Message); - } - - - } - - - /// - /// 删除 - /// - /// 要删除实体 - /// 返回删除受影响条数 - public virtual async Task DeleteAsync(TEntity entity) - { - entity = await this.GetByIdAsync(entity.Id); - - if (entity.IsNull()) - { - throw new AppException($"该{entity.Id}键的数据不存在"); - } - - CheckDelete(entity); - int count = await _dbContext.SaveChangesAsync(); - return count; - } - - - public virtual int Delete(params TEntity[] entitys) - { - foreach (var entity in entitys) - { - CheckDelete(entity); - } - return _dbContext.SaveChanges(); - } - - /// - /// 异步删除所有符合特定条件的实体 - /// - /// 查询条件谓语表达式 - /// 操作影响的行数 - public virtual async Task DeleteBatchAsync(Expression> predicate, CancellationToken cancellationToken = default) - { - - predicate.NotNull(nameof(predicate)); - if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity))) - { - List newMemberBindings = new List(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(TEntity), "o"); //参数 - - ConstantExpression constant = Expression.Constant(true); - var propertyName = nameof(ISoftDelete.IsDeleted); - var propertyInfo = typeof(TEntity).GetProperty(propertyName); - var memberAssignment = Expression.Bind(propertyInfo, constant); //绑定属性 - newMemberBindings.Add(memberAssignment); - - //创建实体 - var newEntity = Expression.New(typeof(TEntity)); - var memberInit = Expression.MemberInit(newEntity, newMemberBindings.ToArray()); //成员初始化 - Expression> updateExpression = Expression.Lambda> //生成要更新的Expression - ( - memberInit, - new ParameterExpression[] { parameterExpression } - ); - - return await TrackEntities.Where(predicate).UpdateAsync(updateExpression, cancellationToken); - } - return await TrackEntities.Where(predicate).DeleteAsync(cancellationToken); - } - - - - - - - #endregion 删除 - - #region 其他 - - - - /// - /// 检查删除 - /// - /// 实体 - /// - private void CheckDelete(TEntity entity) - { - if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity))) - { - ISoftDelete softDeletabl = (ISoftDelete)entity; - softDeletabl.IsDeleted = true; - var entity1 = (TEntity)softDeletabl; - - this._dbContext.Update(entity1); - } - else - { - this._dbContext.Remove(entity); - } - } - - ///// - ///// 检查软删除接口 - ///// - ///// 要检查的实体 - ///// 返回检查好的实体 - //private TEntity CheckISoftDelete(TEntity entity) - //{ - // if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity))) - // { - // ISoftDelete softDeletableEntity = (ISoftDelete)entity; - // softDeletableEntity.IsDeleted = true; - // var entity1 = (TEntity)softDeletableEntity; - // return entity1; - // } - // return entity; - //} - - /// - /// 检查创建 - /// - /// 实体集合 - /// - - private TEntity[] CheckInsert(TEntity[] entitys) - { - for (int i = 0; i < entitys.Length; i++) - { - var entity = entitys[i]; - entitys[i] = CheckInsert(entity); - } - return entitys; - } - - /// - /// 检查创建时间 - /// - /// 实体 - /// - private TEntity CheckInsert(TEntity entity) - { - entity = CheckICreatedTime(entity); - - var creationAudited = entity.GetType().GetInterface(/*$"ICreationAudited`1"*/typeof(ICreationAudited<>).Name); - if (creationAudited == null) - { - return entity; - } - - var typeArguments = creationAudited?.GenericTypeArguments[0]; - var fullName = typeArguments?.FullName; - if (fullName == typeof(Guid).FullName) - { - entity = CheckICreationAudited(entity); - } - - return entity; - } - - private TEntity CheckICreationAudited(TEntity entity) - where TUserKey : struct, IEquatable - { - if (!entity.GetType().IsBaseOn(typeof(ICreationAudited<>))) - { - return entity; - } - - ICreationAudited entity1 = (ICreationAudited)entity; - entity1.CreatorUserId = _principal?.Identity.GetUesrId(); - entity1.CreatedTime = DateTime.Now; - return (TEntity)entity1; - } - - public static TEntity CheckICreatedTime(TEntity entity) - { - if (!(entity is ICreatedTime)) - { - return entity; - } - ICreatedTime entity1 = (ICreatedTime)entity; - - entity1.CreatedTime = DateTime.Now; - return (TEntity)entity1; - } - - /// - /// 检查最后修改时间 - /// - /// - /// - private TEntity[] CheckUpdate(TEntity[] entitys) - { - for (int i = 0; i < entitys.Length; i++) - { - var entity = entitys[i]; - entitys[i] = CheckUpdate(entity); - } - return entitys; - } - - /// - /// 检查最后修改时间 - /// - /// 实体 - /// - private TEntity CheckUpdate(TEntity entity) - { - var creationAudited = entity.GetType().GetInterface(/*$"ICreationAudited`1"*/typeof(IModificationAudited<>).Name); - if (creationAudited == null) - { - return entity; - } - - var typeArguments = creationAudited?.GenericTypeArguments[0]; - var fullName = typeArguments?.FullName; - if (fullName == typeof(Guid).FullName) - { - entity = CheckIModificationAudited(entity); - } - - return entity; - } - - /// - /// 检查最后修改时间 - /// - /// - /// - /// - public TEntity CheckIModificationAudited(TEntity entity) - where TUserKey : struct, IEquatable - { - if (!entity.GetType().IsBaseOn(typeof(IModificationAudited<>))) - { - return entity; - } - - IModificationAudited entity1 = (IModificationAudited)entity; - entity1.LastModifierUserId = _principal?.Identity?.GetUesrId(); - entity1.LastModifionTime = DateTime.Now; - return (TEntity)entity1; - } - - /// - /// 检查最后修改时间 - /// - /// 实体 - /// - private Expression> CheckUpdate(Expression> updateExpression) - { - var creationAudited = typeof(TEntity).GetType().GetInterface(/*$"ICreationAudited`1"*/typeof(IModificationAudited<>).Name); - if (creationAudited == null) - { - return updateExpression; - } - - var typeArguments = creationAudited?.GenericTypeArguments[0]; - var fullName = typeArguments?.FullName; - if (fullName == typeof(Guid).FullName) - { - return CheckIModificationAudited(updateExpression); - } - - return updateExpression; - } - - /// - /// 检查最后修改时间 - /// - /// - /// - /// - public Expression> CheckIModificationAudited(Expression> updateExpression) - where TUserKey : struct, IEquatable - { - if (!typeof(TEntity).IsBaseOn(typeof(IModificationAudited<>))) - { - return updateExpression; - } - List newMemberBindings = new List(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(TEntity), "o"); //参数 - - var memberBindings = ((MemberInitExpression)updateExpression?.Body)?.Bindings; - var propertyInfos = typeof(IModificationAudited).GetProperties(); - if (memberBindings?.Count > 0) - { - var propertyNames = propertyInfos.Select(o => o.Name); - - foreach (var memberBinding in memberBindings.Where(o => !propertyNames.Contains(o.Member.Name))) - { - newMemberBindings.Add(memberBinding); - } - } - foreach (var propertyInfo in propertyInfos) - { - var propertyName = propertyInfo.Name; - ConstantExpression constant = Expression.Constant(DateTime.Now); - if (propertyName == nameof(IModificationAudited.LastModifionTime)) - { - var memberAssignment = Expression.Bind(propertyInfo, constant); //绑定属性 - newMemberBindings.Add(memberAssignment); - } - else if (propertyName == nameof(IModificationAudited.LastModifierUserId)) - { - constant = Expression.Constant(_principal?.Identity?.GetUesrId(), typeof(TUserKey)); - var memberAssignment = Expression.Bind(propertyInfo, constant); //绑定属性 - newMemberBindings.Add(memberAssignment); - } - } - - //创建实体 - var newEntity = Expression.New(typeof(TEntity)); - var memberInit = Expression.MemberInit(newEntity, newMemberBindings.ToArray()); //成员初始化 - Expression> updateExpression1 = Expression.Lambda> //生成要更新的Expression - ( - memberInit, - new ParameterExpression[] { parameterExpression } - ); - - return updateExpression1; - } - - - #endregion 其他 - } -} diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/DapperRepository.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/DapperRepository.cs deleted file mode 100644 index 80a8cab7..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/DapperRepository.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Dapper; -using Destiny.Core.Flow.Entity; -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; -using System.Data; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.EntityFrameworkCore.Repositorys -{ - public class DapperRepository : IDapperRepository - { - private readonly IUnitOfWork _unitOfWork = null; - - public DapperRepository(IUnitOfWork unitOfWork) - { - _unitOfWork = unitOfWork; - DbConnection = _unitOfWork.GetDbContext().Database.GetDbConnection(); - } - - public IDbConnection DbConnection { get; set; } - - public Task> QueryAsync(string sql, object param) - { - return DbConnection.QueryAsync(sql, param); - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/IDapperRepository.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/IDapperRepository.cs deleted file mode 100644 index a78a02cb..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/IDapperRepository.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Collections.Generic; -using System.Data; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.EntityFrameworkCore.Repositorys -{ - public interface IDapperRepository - { - IDbConnection DbConnection { get; } - - Task> QueryAsync(string sql, object param); - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/UnitOfWork.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/UnitOfWork.cs deleted file mode 100644 index 21fbb06e..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/UnitOfWork.cs +++ /dev/null @@ -1,300 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Ui; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.EntityFrameworkCore -{ - ///https://docs.microsoft.com/zh-cn/ef/core/saving/transactions 共享连接和事务 - /// - /// 工作单元 - /// - public class UnitOfWork : IUnitOfWork where TDbContext : DbContextBase - { - /// - /// 释放时触发 - /// - public Action OnDispose { get; set; } - - - private readonly DbContextBase _dbContext = null; - - /// - /// 是否提交 - /// - /// - public bool HasCommit() - { - return HasCommitted; - } - - /// - /// 是否提交 - /// - private bool HasCommitted { get; set; } - - /// - /// 事务 - /// - private DbTransaction _transaction; - - private bool _disposed; - - //private readonly ILogger _logger = null; - - private DbConnection _connection = null; - - public UnitOfWork(TDbContext dbContext) - { - _dbContext = dbContext as DbContextBase; - } - - - private Stack _callStack = new Stack(); - - /// - /// 为了解决多接口使用事务问题 - /// - - public void Push() - { - _callStack.Push(true); - } - - public void Pop() - { - if (_callStack.Any()) - { - _callStack.Pop(); - } - } - - - - - public bool Enabled => _callStack.Count <= 0; - - /// - /// 开启事务 - /// - public virtual void BeginTransaction() - { - - if (!Enabled) - { - return; - } - - if (_transaction?.Connection == null) - { - if (_connection.State != ConnectionState.Open) - { - _connection.Open(); - } - _transaction = _connection.BeginTransaction(); - } - - if (_dbContext.IsRelationalTransaction()) - { - _dbContext.Database.UseTransaction(_transaction); - } - else - { - - _dbContext.Database.BeginTransaction(); - } - - - HasCommitted = false; - } - - - - /// - /// 开启事务异步 - /// - public virtual async Task BeginTransactionAsync(CancellationToken cancellationToken = default) - { - - - if (!Enabled) - { - return; - } - - if (_transaction?.Connection == null) - { - if (_connection.State != ConnectionState.Open) - { - await _connection.OpenAsync(); - } - _transaction = _connection.BeginTransaction(); - } - - - if (_dbContext.IsRelationalTransaction()) - { - - _dbContext.Database.UseTransaction(_transaction); - } - else { - _dbContext.Database.BeginTransaction(); - - - } - - - HasCommitted = false; - } - - /// - /// 提交事务 - /// - public void Commit() - { - if (!Enabled) - { - return; - } - - if (HasCommitted || _transaction == null) - { - return; - } - _transaction.Commit(); - if (_dbContext.IsRelationalTransaction()) - { - _dbContext.Database.CurrentTransaction.Dispose(); - } - else { - _dbContext.Database.CommitTransaction(); - } - - HasCommitted = true; - } - - /// - /// 异步提交事务 - /// - /// - public async Task CommitAsync() - { - if (!Enabled) - { - return; - } - - if (HasCommitted || _transaction == null) - { - return; - } - await _transaction.CommitAsync(); - - if (_dbContext.IsRelationalTransaction()) - { - await _dbContext.Database.CurrentTransaction.DisposeAsync(); - } - else - { - _dbContext.Database.CommitTransaction(); - } - - HasCommitted = true; - } - - /// - /// 得到上下文 - /// - /// - public DbContext GetDbContext() - { - _connection = _dbContext.Database.GetDbConnection(); - _dbContext.UnitOfWork = this; - return _dbContext as DbContext; - } - - /// - /// 释放对象. - /// - public void Dispose() - { - if (_disposed) - { - return; - } - _transaction?.Dispose(); - _dbContext.Dispose(); - OnDispose?.Invoke(); - _callStack?.Clear(); - _disposed = true; - - } - - /// - /// 回滚 - /// - public void Rollback() - { - if (!Enabled) - { - return; - } - - if (_transaction?.Connection != null) - { - _transaction.Rollback(); - } - - if (_dbContext.IsRelationalTransaction()) - { - if (_dbContext.Database.CurrentTransaction != null) - { - _dbContext.Database.CurrentTransaction.Dispose(); - } - } - else { - _dbContext.Database.RollbackTransaction(); - } - HasCommitted = true; - } - - /// - /// 异步回滚 - /// - /// - public async Task RollbackAsync() - { - if (!Enabled) - { - return; - } - - if (_transaction?.Connection != null) - { - await _transaction.RollbackAsync(); - } - - if (_dbContext.IsRelationalTransaction()) - { - if (_dbContext.Database.CurrentTransaction != null) - { - await _dbContext.Database.CurrentTransaction.DisposeAsync(); - } - } - else { - _dbContext.Database.RollbackTransaction(); - } - - HasCommitted = true; - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/UnitOfWorkExtensions.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/UnitOfWorkExtensions.cs deleted file mode 100644 index 0e1eb50d..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/Repositorys/UnitOfWorkExtensions.cs +++ /dev/null @@ -1,160 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.EntityFrameworkCore; -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Ui; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -namespace Destiny.Core.Flow.Entity -{ - /// - /// 工作单元扩展 - /// - public static class UnitOfWorkExtensions - { - /// - /// 添加工作单元 - /// - /// - /// - /// - /// - /// - public static IServiceCollection AddUnitOfWork(this IServiceCollection services, ServiceLifetime lifetime= ServiceLifetime.Scoped) - where TDbContext : DbContextBase - { - - ServiceDescriptor serviceDescriptor = new ServiceDescriptor(typeof(IUnitOfWork), typeof(UnitOfWork),lifetime); - services.Add(serviceDescriptor); - return services; - } - - - - /// - /// 开启事务 如果成功提交事务,失败回滚事务 - /// - /// 要执行的操作 - /// - public static void UseTran(this IUnitOfWork unitOfWork, Action action) - { - action.NotNull(nameof(action)); - if (unitOfWork.HasCommit()) - { - return; - } - - unitOfWork.BeginTransaction(); - try - { - action?.Invoke(); - unitOfWork.Commit(); - } - catch (Exception ex) - { - - unitOfWork.Rollback(); - LogError(ex); - } - } - - public static async Task UseTranAsync(this IUnitOfWork unitOfWork, Func func) - { - func.NotNull(nameof(func)); - if (unitOfWork.HasCommit()) - { - return; - } - - unitOfWork.BeginTransaction(); - await func?.Invoke(); - unitOfWork.Commit(); - } - - /// - /// 开启事务 如果成功提交事务,失败回滚事务 - /// - /// - /// 返回操作结果 - public static async Task UseTranAsync(this IUnitOfWork unitOfWork, Func> func) - { - func.NotNull(nameof(func)); - OperationResponse result = new OperationResponse(); - if (unitOfWork.HasCommit()) - { - result.Type = OperationResponseType.NoChanged; - result.Message = "事务已提交!!"; - return result; - } - - try - { - await unitOfWork.BeginTransactionAsync(); - result = await func.Invoke(); - if (!result.Success) - { - await unitOfWork.RollbackAsync(); - return result; - } - await unitOfWork.CommitAsync(); - } - catch (Exception ex) - { - - await unitOfWork.RollbackAsync(); - LogError(ex); - return new OperationResponse() - { - Type = OperationResponseType.Error, - Message = ex.Message, - }; - } - return result; - } - - private static void LogError(Exception exception) - { - IocManage.Instance.GetLogger()?.LogError(exception.Message, exception); - } - - /// - /// 开启事务 如果成功提交事务,失败回滚事务 - /// - /// - /// 返回操作结果 - public static OperationResponse UseTran(this IUnitOfWork unitOfWork, Func func) - { - func.NotNull(nameof(func)); - OperationResponse result = new OperationResponse(); - if (unitOfWork.HasCommit()) - { - result.Type = OperationResponseType.NoChanged; - result.Message = "事务已提交!!"; - return result; - } - try - { - unitOfWork.BeginTransaction(); - result = func.Invoke(); - unitOfWork.Commit(); - return result; - } - catch (Exception ex) - { - - unitOfWork.Rollback(); - LogError(ex); - return new OperationResponse() - { - Type = OperationResponseType.Error, - Message = ex.Message, - }; - } - } - } -} diff --git a/src/Destiny.Core.Flow.EntityFrameworkCore/ServiceExtensions.cs b/src/Destiny.Core.Flow.EntityFrameworkCore/ServiceExtensions.cs deleted file mode 100644 index 6269d82d..00000000 --- a/src/Destiny.Core.Flow.EntityFrameworkCore/ServiceExtensions.cs +++ /dev/null @@ -1,92 +0,0 @@ -using Destiny.Core.Flow; -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Options; -using Microsoft.EntityFrameworkCore.Diagnostics; -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Text; -using System.Linq; -using Destiny.Core.Flow.Entity; -using System.IO; -using Destiny.Core.Flow.Interceptor; - -namespace Microsoft.Extensions.DependencyInjection -{ - public static class ServiceExtensions - { - /// - /// 添加上下文,自动识别数据库驱动 - /// - /// 上下文 - /// 服务集合 - /// 操作委托 - /// 返回已添加上下文服务集合 - - public static IServiceCollection AddDestinyDbContext(this IServiceCollection services, Action optionsAction = null) where TDbContext : DbContextBase - { - - services.AddDbContext((provider, builder) => - { - - var type = typeof(TDbContext); - var settings = provider.GetAppSettings(); - if (settings == null) - { - MessageBox.Show("配置不存在!!"); - } - - DestinyContextOptions contextOptions = settings.DbContexts?.Values.FirstOrDefault(o => o.DbContextType == type); - - if (contextOptions is null) - { - MessageBox.Show($"无法找到{type.Name}数据库配置信息!!"); - - } - - var databaseType =contextOptions.DatabaseType; - - //if (databaseType == Destiny.Core.Flow.Entity.DatabaseType.SqlServer) - //每个类型都要判断。可以使用一个接口,每种类型实现自己的,根据数据类型得到相关驱动,使用(策略模式?工厂模式??) - //配合注入完美 - //{ - - - //} - var drivenProviderType = services.GetImplementationTypes() - ?.FirstOrDefault(o=>o.GetAttribute()?.DatabaseType == databaseType); - - if (drivenProviderType == null) - { - MessageBox.Show($"没有找到{databaseType}类型的驱动实例"); - - } - - var drivenProvider = (IDbContextDrivenProvider)provider.GetService(drivenProviderType); - if (drivenProvider == null) - { - MessageBox.Show($"没有找到{databaseType}类型的驱动"); - - } - DestinyContextOptionsBuilder optionsBuilder1 = new DestinyContextOptionsBuilder(); - optionsBuilder1.MigrationsAssemblyName = contextOptions.MigrationsAssemblyName; - var connectionString = contextOptions.ConnectionString; - - if (contextOptions.ConnectionString.IsFile(".txt")) //txt文件 - { - - connectionString = provider.GetFileText(contextOptions.ConnectionString, $"未找到存放{databaseType.ToDescription()}数据库链接的文件"); - } - - builder = drivenProvider.Builder(builder, connectionString, optionsBuilder1); - optionsAction?.Invoke(provider,builder); - builder.AddInterceptors(new AuditInterceptor(provider)); - }); - return services; - - } - - - } -} diff --git a/src/Destiny.Core.Flow.FluentValidation/Destiny.Core.Flow.FluentValidation.csproj b/src/Destiny.Core.Flow.FluentValidation/Destiny.Core.Flow.FluentValidation.csproj deleted file mode 100644 index 1c833ef3..00000000 --- a/src/Destiny.Core.Flow.FluentValidation/Destiny.Core.Flow.FluentValidation.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - netstandard2.1 - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.FluentValidation/FluentModelValidator.cs b/src/Destiny.Core.Flow.FluentValidation/FluentModelValidator.cs deleted file mode 100644 index 234d1af8..00000000 --- a/src/Destiny.Core.Flow.FluentValidation/FluentModelValidator.cs +++ /dev/null @@ -1,9 +0,0 @@ -using FluentValidation; - -namespace Destiny.Core.Flow.FluentValidation -{ - public abstract class FluentModelValidator : AbstractValidator - { - - } -} diff --git a/src/Destiny.Core.Flow.FluentValidation/FluentValidationExtensions.cs b/src/Destiny.Core.Flow.FluentValidation/FluentValidationExtensions.cs deleted file mode 100644 index 2d74b03f..00000000 --- a/src/Destiny.Core.Flow.FluentValidation/FluentValidationExtensions.cs +++ /dev/null @@ -1,109 +0,0 @@ -using Destiny.Core.Flow.Validation; -using FluentValidation; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace Destiny.Core.Flow.FluentValidation -{ - public static class FluentValidationExtensions - { - public static IServiceCollection WithFluentValidation(this IServiceCollection services) - { - services.AddTransient(typeof(IModelValidator<>), typeof(FluentValidationModelValidator<>)); - services.AddTransient(); - - return services; - } - - - - - - /// - /// 添加指定程序集中的所有验证程序 - /// - /// 服务的集合 - /// - /// 验证器的生存期。默认值是暂时的 - /// - - public static IServiceCollection AddValidatorsFromAssemblies(this IServiceCollection services, - IEnumerable assemblies, ServiceLifetime lifetime = ServiceLifetime.Transient) - { - foreach (var assembly in assemblies) - services.AddValidatorsFromAssembly(assembly, lifetime); - - return services; - } - - /// - /// 添加指定程序集中的所有验证程序 - /// - /// 服务的集合 - /// 要扫描的程序集 - /// 验证器的生存期。默认值是暂时的 - /// - - public static IServiceCollection AddValidatorsFromAssembly(this IServiceCollection services, Assembly assembly, - ServiceLifetime lifetime = ServiceLifetime.Transient) - { - AssemblyScanner - .FindValidatorsInAssembly(assembly) - .ForEach(scanResult => services.AddScanResult(scanResult, lifetime)); - - return services; - } - - - /// - /// 在指定类型的程序集中添加所有验证程序 - /// - /// 服务的集合 - /// 要扫描其程序集的类型 - /// 验证器的生存期。默认值是暂时的 - /// - public static IServiceCollection AddValidatorsFromAssemblyContaining(this IServiceCollection services, - Type type, ServiceLifetime lifetime = ServiceLifetime.Transient) - => services.AddValidatorsFromAssembly(type.Assembly, lifetime); - - /// - /// 添加泛型参数指定类型的程序集中的所有验证器 - /// - /// - /// 服务的集合 - /// 验证器的生存期。默认值是暂时的 - /// - public static IServiceCollection AddValidatorsFromAssemblyContaining(this IServiceCollection services, - ServiceLifetime lifetime = ServiceLifetime.Transient) - => services.AddValidatorsFromAssembly(typeof(T).Assembly, lifetime); - - /// - /// 从AssemblyScanner结果注册验证器的帮助器方法 - /// - /// 服务的集合 - /// 扫描结果 - /// 验证器的生存期。默认值是暂时的 - /// - private static IServiceCollection AddScanResult(this IServiceCollection services, - AssemblyScanner.AssemblyScanResult scanResult, ServiceLifetime lifetime) - { - - services.Add( - new ServiceDescriptor( - scanResult.InterfaceType, - scanResult.ValidatorType, - lifetime)); - - - services.Add( - new ServiceDescriptor( - scanResult.ValidatorType, - scanResult.ValidatorType, - lifetime)); - - return services; - } - } -} diff --git a/src/Destiny.Core.Flow.FluentValidation/FluentValidationModelValidator.cs b/src/Destiny.Core.Flow.FluentValidation/FluentValidationModelValidator.cs deleted file mode 100644 index f4dbe5dc..00000000 --- a/src/Destiny.Core.Flow.FluentValidation/FluentValidationModelValidator.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Destiny.Core.Flow.Validation; -using FluentValidation; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Destiny.Core.Flow.FluentValidation -{ - internal class FluentValidationModelValidator : ModelValidator - { - private readonly IValidatorFactory _factory; - - public FluentValidationModelValidator(IValidatorFactory factory) - { - _factory = factory ?? throw new ArgumentNullException(nameof(factory)); - } - - public override IEnumerable Validate(T model) - { - var fvValidator = _factory.GetValidator(model.GetType()); - - if (fvValidator == null) return Enumerable.Empty(); - var context = new ValidationContext(model); - var validationResult = fvValidator.Validate(context); - var failures = validationResult.Errors - .Select(e => new ValidationFailure(e.PropertyName, e.ErrorMessage)) - .ToList(); - - return failures; - } - } -} diff --git a/src/Destiny.Core.Flow.FluentValidation/FluentValidationModuleBase.cs b/src/Destiny.Core.Flow.FluentValidation/FluentValidationModuleBase.cs deleted file mode 100644 index fd0d11e1..00000000 --- a/src/Destiny.Core.Flow.FluentValidation/FluentValidationModuleBase.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Destiny.Core.Flow.Reflection; -using Destiny.Core.Flow.Validation; -using FluentValidation; - -namespace Destiny.Core.Flow.FluentValidation -{ - public class FluentValidationModuleBase : AppModule - { - - public override void ConfigureServices(ConfigureServicesContext context) - { - var assemblyFinder = context.Services.GetOrAddSingletonService(); - assemblyFinder.NotNull(nameof(assemblyFinder)); - context.Services.AddValidatorsFromAssemblies(assemblyFinder.FindAll()); - context.Services.WithFluentValidation(); - context.Services.WithModelValidation(); - } - - - - } -} diff --git a/src/Destiny.Core.Flow.FluentValidation/ServiceProviderValidatorFactory.cs b/src/Destiny.Core.Flow.FluentValidation/ServiceProviderValidatorFactory.cs deleted file mode 100644 index 81e3519f..00000000 --- a/src/Destiny.Core.Flow.FluentValidation/ServiceProviderValidatorFactory.cs +++ /dev/null @@ -1,23 +0,0 @@ -using FluentValidation; -using System; - -namespace Destiny.Core.Flow.FluentValidation -{ - /// - /// 服务提供商验证程序工厂 - /// - internal sealed class ServiceProviderValidatorFactory : ValidatorFactoryBase - { - private readonly IServiceProvider _serviceProvider; - - public ServiceProviderValidatorFactory(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - - public override IValidator CreateInstance(Type validatorType) - { - return _serviceProvider.GetService(validatorType) as IValidator; - } - } -} diff --git a/src/Destiny.Core.Flow.GateWay/Destiny.Core.Flow.GateWay.csproj b/src/Destiny.Core.Flow.GateWay/Destiny.Core.Flow.GateWay.csproj deleted file mode 100644 index a5956962..00000000 --- a/src/Destiny.Core.Flow.GateWay/Destiny.Core.Flow.GateWay.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - net5.0 - - - - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.GateWay/Program.cs b/src/Destiny.Core.Flow.GateWay/Program.cs deleted file mode 100644 index cf2e4d89..00000000 --- a/src/Destiny.Core.Flow.GateWay/Program.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Destiny.Core.Flow.GateWay -{ - public class Program - { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); - } -} diff --git a/src/Destiny.Core.Flow.GateWay/Properties/launchSettings.json b/src/Destiny.Core.Flow.GateWay/Properties/launchSettings.json deleted file mode 100644 index 350adf75..00000000 --- a/src/Destiny.Core.Flow.GateWay/Properties/launchSettings.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:49155", - "sslPort": 44350 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "Destiny.Core.Flow.GateWay": { - "commandName": "Project", - "launchBrowser": true, - "applicationUrl": "https://localhost:5001;http://localhost:5000", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/src/Destiny.Core.Flow.GateWay/Startup.cs b/src/Destiny.Core.Flow.GateWay/Startup.cs deleted file mode 100644 index e1658283..00000000 --- a/src/Destiny.Core.Flow.GateWay/Startup.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace Destiny.Core.Flow.GateWay -{ - public class Startup - { - // This method gets called by the runtime. Use this method to add services to the container. - // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 - public void ConfigureServices(IServiceCollection services) - { - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - app.UseRouting(); - - app.UseEndpoints(endpoints => - { - endpoints.MapGet("/", async context => - { - await context.Response.WriteAsync("Hello World!"); - }); - }); - } - } -} diff --git a/src/Destiny.Core.Flow.GateWay/appsettings.Development.json b/src/Destiny.Core.Flow.GateWay/appsettings.Development.json deleted file mode 100644 index 8983e0fc..00000000 --- a/src/Destiny.Core.Flow.GateWay/appsettings.Development.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - } -} diff --git a/src/Destiny.Core.Flow.GateWay/appsettings.json b/src/Destiny.Core.Flow.GateWay/appsettings.json deleted file mode 100644 index d9d9a9bf..00000000 --- a/src/Destiny.Core.Flow.GateWay/appsettings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "AllowedHosts": "*" -} diff --git a/src/Destiny.Core.Flow.GateWay/ocelotconfigure.json b/src/Destiny.Core.Flow.GateWay/ocelotconfigure.json deleted file mode 100644 index 5f282702..00000000 --- a/src/Destiny.Core.Flow.GateWay/ocelotconfigure.json +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/Destiny.Core.Flow.IServices/Destiny.Core.Flow.IServices.csproj b/src/Destiny.Core.Flow.IServices/Destiny.Core.Flow.IServices.csproj index 3ee745e1..8ff39049 100644 --- a/src/Destiny.Core.Flow.IServices/Destiny.Core.Flow.IServices.csproj +++ b/src/Destiny.Core.Flow.IServices/Destiny.Core.Flow.IServices.csproj @@ -16,10 +16,10 @@ - + diff --git a/src/Destiny.Core.Flow.Identity/Destiny.Core.Flow.Identitys.csproj b/src/Destiny.Core.Flow.Identity/Destiny.Core.Flow.Identitys.csproj index 78fddff2..b8351634 100644 --- a/src/Destiny.Core.Flow.Identity/Destiny.Core.Flow.Identitys.csproj +++ b/src/Destiny.Core.Flow.Identity/Destiny.Core.Flow.Identitys.csproj @@ -6,17 +6,13 @@ + - - - - - True diff --git a/src/Destiny.Core.Flow.IdentityServer.Entities/Destiny.Core.Flow.IdentityServer.Entities.csproj b/src/Destiny.Core.Flow.IdentityServer.Entities/Destiny.Core.Flow.IdentityServer.Entities.csproj index cf601bc2..6cfc0c95 100644 --- a/src/Destiny.Core.Flow.IdentityServer.Entities/Destiny.Core.Flow.IdentityServer.Entities.csproj +++ b/src/Destiny.Core.Flow.IdentityServer.Entities/Destiny.Core.Flow.IdentityServer.Entities.csproj @@ -1,11 +1,11 @@ - + netstandard2.1 - + diff --git a/src/Destiny.Core.Flow.IdentityServer4/Destiny.Core.Flow.IdentityServer.csproj b/src/Destiny.Core.Flow.IdentityServer4/Destiny.Core.Flow.IdentityServer.csproj index 9e290cf1..89da34bd 100644 --- a/src/Destiny.Core.Flow.IdentityServer4/Destiny.Core.Flow.IdentityServer.csproj +++ b/src/Destiny.Core.Flow.IdentityServer4/Destiny.Core.Flow.IdentityServer.csproj @@ -5,13 +5,13 @@ + - diff --git a/src/Destiny.Core.Flow.Log4Net/Destiny.Core.Flow.Log4Net.csproj b/src/Destiny.Core.Flow.Log4Net/Destiny.Core.Flow.Log4Net.csproj deleted file mode 100644 index ca2d98e2..00000000 --- a/src/Destiny.Core.Flow.Log4Net/Destiny.Core.Flow.Log4Net.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - netstandard2.1 - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.Log4Net/Log4NetLogger.cs b/src/Destiny.Core.Flow.Log4Net/Log4NetLogger.cs deleted file mode 100644 index 246ccb99..00000000 --- a/src/Destiny.Core.Flow.Log4Net/Log4NetLogger.cs +++ /dev/null @@ -1,128 +0,0 @@ -using log4net; -using log4net.Repository; -using Microsoft.Extensions.Logging; -using System; -using System.Reflection; -using System.Xml; - -namespace Destiny.Core.Flow.Log4Net -{ - /// - /// 日志记录 - /// https://dotnetthoughts.net/how-to-use-log4net-with-aspnetcore-for-logging/ - /// - - public class Log4NetLogger : ILogger - { - - - private readonly string _name; - private readonly XmlElement _xmlElement; - private readonly ILog _log; - private ILoggerRepository _loggerRepository; - - - - public Log4NetLogger(string name, XmlElement xmlElement) - { - _name = name; - _xmlElement = xmlElement; - _loggerRepository = log4net.LogManager.CreateRepository( - Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy)); - _log = LogManager.GetLogger(_loggerRepository.Name, name); - log4net.Config.XmlConfigurator.Configure(_loggerRepository, xmlElement); - } - - public bool IsEnabled(LogLevel logLevel) - { - switch (logLevel) - { - case LogLevel.Critical: - return _log.IsFatalEnabled; - case LogLevel.Debug: - case LogLevel.Trace: - return _log.IsDebugEnabled; - case LogLevel.Error: - return _log.IsErrorEnabled; - case LogLevel.Information: - return _log.IsInfoEnabled; - case LogLevel.Warning: - return _log.IsWarnEnabled; - default: - throw new ArgumentOutOfRangeException(nameof(logLevel)); - } - } - - // - // 摘要: - // /// Writes a log entry. /// - // - // 参数: - // logLevel: - // Entry will be written on this level. - // - // eventId: - // Id of the event. - // - // state: - // The entry to be written. Can be also an object. - // - // exception: - // The exception related to this entry. - // - // formatter: - // Function to create a System.String message of the state and exception. - // - // 类型参数: - // TState: - // The type of the object to be written. - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) - { - if (!IsEnabled(logLevel)) - { - return; - } - - if (formatter == null) - { - throw new ArgumentNullException(nameof(formatter)); - } - string message = null; - if (null != formatter) - { - message = formatter(state, exception); - } - if (!string.IsNullOrEmpty(message) || exception != null) - { - switch (logLevel) - { - case LogLevel.Critical: - _log.Fatal(message); - break; - case LogLevel.Debug: - case LogLevel.Trace: - _log.Debug(message); - break; - case LogLevel.Error: - _log.Error(message); - break; - case LogLevel.Information: - _log.Info(message); - break; - case LogLevel.Warning: - _log.Warn(message); - break; - default: - _log.Warn($"遇到未知的日志级别{logLevel},正在作为信息写入。"); - _log.Info(message, exception); - break; - } - } - } - - public IDisposable BeginScope(TState state) - { - return null; - } - } -} diff --git a/src/Destiny.Core.Flow.Log4Net/Log4NetModuleBase.cs b/src/Destiny.Core.Flow.Log4Net/Log4NetModuleBase.cs deleted file mode 100644 index 6b58f6b0..00000000 --- a/src/Destiny.Core.Flow.Log4Net/Log4NetModuleBase.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Destiny.Core.Flow.Modules; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace Destiny.Core.Flow.Log4Net -{ - public class Log4NetModule : AppModule - { - - public override void ConfigureServices(ConfigureServicesContext context) - { - context.Services.AddTransient(); - context.Services.AddSingleton(); - } - - - } -} diff --git a/src/Destiny.Core.Flow.Log4Net/Log4NetProvider.cs b/src/Destiny.Core.Flow.Log4Net/Log4NetProvider.cs deleted file mode 100644 index 7cae7c85..00000000 --- a/src/Destiny.Core.Flow.Log4Net/Log4NetProvider.cs +++ /dev/null @@ -1,64 +0,0 @@ -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Concurrent; -using System.IO; -using System.Xml; - -namespace Destiny.Core.Flow.Log4Net -{ - /// - /// log4net 日志对象提供者 - /// https://dotnetthoughts.net/how-to-use-log4net-with-aspnetcore-for-logging/ - /// - public class Log4NetProvider : ILoggerProvider - { - private const string _defaultLog4NetFileName = "log4net.config"; - private readonly string _log4NetConfigFile; - private readonly ConcurrentDictionary _loggers = - new ConcurrentDictionary(); - - /// - /// - /// - public Log4NetProvider() : this(_defaultLog4NetFileName) - { - - } - public Log4NetProvider(string log4NetConfigFile) - { - _log4NetConfigFile = log4NetConfigFile; - } - - public ILogger CreateLogger(string categoryName) - { - return _loggers.GetOrAdd(categoryName, CreateLoggerImplementation); - } - - protected virtual void Dispose(bool disposing) - { - if (!disposing) - { - return; - } - _loggers.Clear(); - } - - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - private Log4NetLogger CreateLoggerImplementation(string name) - { - return new Log4NetLogger(name, Parselog4NetConfigFile(_log4NetConfigFile)); - } - - private static XmlElement Parselog4NetConfigFile(string filename) - { - XmlDocument log4netConfig = new XmlDocument(); - log4netConfig.Load(File.OpenRead(filename)); - return log4netConfig["log4net"]; - } - } -} diff --git a/src/Destiny.Core.Flow.Log4Net/MNZ.CMS.Core.Log4Net.csproj b/src/Destiny.Core.Flow.Log4Net/MNZ.CMS.Core.Log4Net.csproj deleted file mode 100644 index c318408b..00000000 --- a/src/Destiny.Core.Flow.Log4Net/MNZ.CMS.Core.Log4Net.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - netstandard2.1 - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.Log4Net/log4net.config b/src/Destiny.Core.Flow.Log4Net/log4net.config deleted file mode 100644 index 3f172ca1..00000000 --- a/src/Destiny.Core.Flow.Log4Net/log4net.config +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Destiny.Core.Flow.MiniProfiler/Destiny.Core.Flow.MiniProfiler.csproj b/src/Destiny.Core.Flow.MiniProfiler/Destiny.Core.Flow.MiniProfiler.csproj deleted file mode 100644 index 1652bca0..00000000 --- a/src/Destiny.Core.Flow.MiniProfiler/Destiny.Core.Flow.MiniProfiler.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - netstandard2.1 - Destiny.Core.Flow - - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.MiniProfiler/MiniProfilerModule.cs b/src/Destiny.Core.Flow.MiniProfiler/MiniProfilerModule.cs deleted file mode 100644 index a68d7105..00000000 --- a/src/Destiny.Core.Flow.MiniProfiler/MiniProfilerModule.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; - -namespace Destiny.Core.Flow.MiniProfiler -{ - public class MiniProfilerModule : AppModule - { - private const string _name = "Destiny:IsOpenMiniProfiler"; - - public override void ApplicationInitialization(ApplicationContext context) - { - var app = context.GetApplicationBuilder(); - var isOpen = context.GetConfiguration()[_name].AsTo(); - if (isOpen.IsTrue()) - { - app.UseMiniProfiler(); - } - - } - - public override void ConfigureServices(ConfigureServicesContext context) - { - var isOpen= context.GetConfiguration()[_name].AsTo(); - if (isOpen.IsTrue()) - { - context.Services.AddMiniProfiler().AddEntityFramework(); - } - - } - } -} diff --git a/src/Destiny.Core.Flow.Model/Destiny.Core.Flow.Model.csproj b/src/Destiny.Core.Flow.Model/Destiny.Core.Flow.Model.csproj index 70e4f5d8..fb36d171 100644 --- a/src/Destiny.Core.Flow.Model/Destiny.Core.Flow.Model.csproj +++ b/src/Destiny.Core.Flow.Model/Destiny.Core.Flow.Model.csproj @@ -11,13 +11,14 @@ + + - diff --git a/src/Destiny.Core.Flow.MongoDB/DbContexts/DefaultMongoDbContext.cs b/src/Destiny.Core.Flow.MongoDB/DbContexts/DefaultMongoDbContext.cs deleted file mode 100644 index 90c7f2af..00000000 --- a/src/Destiny.Core.Flow.MongoDB/DbContexts/DefaultMongoDbContext.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace Destiny.Core.Flow.MongoDB.DbContexts -{ - public class DefaultMongoDbContext : MongoDbContextBase - { - public DefaultMongoDbContext([NotNull] MongoDbContextOptions options) : base(options) - { - - } - - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/DbContexts/MongoDbContextBase.cs b/src/Destiny.Core.Flow.MongoDB/DbContexts/MongoDbContextBase.cs deleted file mode 100644 index 7df81099..00000000 --- a/src/Destiny.Core.Flow.MongoDB/DbContexts/MongoDbContextBase.cs +++ /dev/null @@ -1,64 +0,0 @@ - -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Extensions; -using MongoDB.Driver; -using System; -using System.Diagnostics.CodeAnalysis; - - -namespace Destiny.Core.Flow.MongoDB.DbContexts -{ - public abstract class MongoDbContextBase : IDisposable - { - private readonly MongoDbContextOptions _options; - public MongoDbContextBase([NotNull] MongoDbContextOptions options) - { - _options = options; - } - - private string ConnectionString => _options.ConnectionString; - - public IMongoDatabase Database => GetDbContext(); - - public IMongoCollection Collection() - { - return Database.GetCollection(GetTableName()); - } - - private string GetTableName() - { - Type t = typeof(TEntity); - var table = t.GetAttribute(); - - if (table == null) - { - return t.Name; - } - if (table.TableName.IsNullOrEmpty()) - { - throw new AppException("Table name does not exist!"); - } - return table.TableName; - - } - - - private IMongoDatabase GetDbContext() - { - var mongoUrl = new MongoUrl(ConnectionString); - var databaseName = mongoUrl.DatabaseName; - if (databaseName.IsNullOrEmpty()) - { - throw new AppException($"{mongoUrl}不存DatabaseName名!!!"); - } - - var database = new MongoClient(mongoUrl).GetDatabase(databaseName); - return database; - } - - public void Dispose() - { - - } - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/Destiny.Core.Flow.MongoDB.csproj b/src/Destiny.Core.Flow.MongoDB/Destiny.Core.Flow.MongoDB.csproj deleted file mode 100644 index e61fa8e3..00000000 --- a/src/Destiny.Core.Flow.MongoDB/Destiny.Core.Flow.MongoDB.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - netstandard2.1 - Destiny.Core.Flow - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.MongoDB/FindFluentExtensions.cs b/src/Destiny.Core.Flow.MongoDB/FindFluentExtensions.cs deleted file mode 100644 index 425b5c3e..00000000 --- a/src/Destiny.Core.Flow.MongoDB/FindFluentExtensions.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Filter; -using MongoDB.Driver; - -namespace Destiny.Core.Flow -{ - public static class FindFluentExtensions - { - - public static IOrderedFindFluent OrderBy(this IFindFluent findFluent, OrderCondition[] orderConditions) - { - IOrderedFindFluent orderFindFluent = null; - if (orderConditions == null || orderConditions.Length == 0) - { - orderFindFluent = FindFluentSortBy.OrderBy(findFluent, "Id", Destiny.Core.Flow.Enums.SortDirection.Ascending); - } - orderConditions.ForEach((e, i) => - { - orderFindFluent = i == 0 ? FindFluentSortBy.OrderBy(findFluent, e.SortField, e.SortDirection) : - FindFluentSortBy.ThenBy(orderFindFluent, e.SortField, e.SortDirection); - }); - - return orderFindFluent; - - } - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/FindFluentSortBy.cs b/src/Destiny.Core.Flow.MongoDB/FindFluentSortBy.cs deleted file mode 100644 index 1c18969e..00000000 --- a/src/Destiny.Core.Flow.MongoDB/FindFluentSortBy.cs +++ /dev/null @@ -1,66 +0,0 @@ -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Extensions; -using MongoDB.Driver; -using System; -using System.Collections.Concurrent; -using System.Linq.Expressions; -using System.Reflection; - -namespace Destiny.Core.Flow -{ - public static class FindFluentSortBy - { - private static readonly ConcurrentDictionary>> Cache = new ConcurrentDictionary>>(); - public static IOrderedFindFluent OrderBy(IFindFluent findFluent, string propertyName, Flow.Enums.SortDirection sortDirection) - { - - propertyName.NotNullOrEmpty("propertyName"); - var keySelector = GetKeySelector(propertyName); - return sortDirection == Flow.Enums.SortDirection.Ascending - ? IFindFluentExtensions.SortBy(findFluent, keySelector) : IFindFluentExtensions.SortByDescending(findFluent, keySelector); - } - - public static IOrderedFindFluent ThenBy(IOrderedFindFluent orderedFind, string propertyName, Flow.Enums.SortDirection sortDirection) - { - propertyName.NotNullOrEmpty("propertyName"); - var keySelector = GetKeySelector(propertyName); - return sortDirection == Flow.Enums.SortDirection.Ascending - ? IFindFluentExtensions.ThenBy(orderedFind, keySelector) - : IFindFluentExtensions.ThenByDescending(orderedFind, keySelector); - } - - private static Expression> GetKeySelector(string keyName) - { - Type type = typeof(TEntity); - string key = $"{type.FullName}.{keyName}"; - if (Cache.ContainsKey(key)) - { - return Cache[key]; - } - ParameterExpression param = Expression.Parameter(type); - string[] propertyNames = keyName.Split("."); - Expression propertyAccess = param; - - foreach (var propertyName in propertyNames) - { - PropertyInfo property = type.GetProperty(propertyName); - if (property.IsNull()) - { - throw new AppException($"查找类似 指定对象中不存在名称为“{propertyName}”的属性"); - } - type = property.PropertyType; - propertyAccess = Expression.Property(propertyAccess, propertyName); - } - var convertExpression = Expression.Convert(propertyAccess, typeof(object)); - Expression> keySelector = - Expression.Lambda>( - convertExpression, - new ParameterExpression[] { - param - }); - Cache[key] = keySelector; - return keySelector; - } - - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/Infrastructure/IMongoDbContextOptions.cs b/src/Destiny.Core.Flow.MongoDB/Infrastructure/IMongoDbContextOptions.cs deleted file mode 100644 index 3e39734d..00000000 --- a/src/Destiny.Core.Flow.MongoDB/Infrastructure/IMongoDbContextOptions.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Destiny.Core.Flow.MongoDB.Infrastructure -{ - public interface IMongoDbContextOptions - { - - string ConnectionString { get; set; } - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/Metadata/Builders/MongoDBFilterBuilder.cs b/src/Destiny.Core.Flow.MongoDB/Metadata/Builders/MongoDBFilterBuilder.cs deleted file mode 100644 index 384642c2..00000000 --- a/src/Destiny.Core.Flow.MongoDB/Metadata/Builders/MongoDBFilterBuilder.cs +++ /dev/null @@ -1,163 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.ExpressionUtil; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Filter; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Text; - -namespace Destiny.Core.Flow.Metadata.Builders -{ - - public class MongoDBFilterBuilder - { - - - public static Func GetOperateExpression = (operate, member, expression) => { - - switch (operate) - { - case FilterOperator.Equal: - return Expression.Equal(member, expression); - - case FilterOperator.NotEqual: - return Expression.NotEqual(member, expression); - - case FilterOperator.GreaterThan: - return Expression.GreaterThan(member, expression); - - case FilterOperator.GreaterThanOrEqual: - return Expression.GreaterThanOrEqual(member, expression); - - case FilterOperator.LessThan: - return Expression.LessThan(member, expression); - - case FilterOperator.LessThanOrEqual: - return Expression.LessThanOrEqual(member, expression); - - case FilterOperator.Like: - return Contains((member as MemberExpression), expression as ConstantExpression); - default: - throw new AppException($"此{operate}过滤条件不支持!!"); - - } - - - }; - - /// - /// 得到表达式目录树 - /// - /// 动态类型 - /// 查询过滤 - /// - public static Expression> GetExpression(QueryFilter queryFilter) - { - queryFilter.NotNull("queryFilter"); - ParameterExpression param = Expression.Parameter(typeof(T), "m"); - - Expression expression = GetExpressionBody(param, queryFilter); - return Expression.Lambda>(expression, param); - } - - private static Expression GetExpressionBody(ParameterExpression param, QueryFilter queryFilter) - { - - List expressions = new List(); - Expression expression = Expression.Constant(true); - if (queryFilter is null || (queryFilter?.Conditions.Count() == 0 && queryFilter?.Filters.Count() == 0)) //为空 - { - return expression; - } - foreach (var item in queryFilter.Conditions) - { - expressions.Add(GetExpressionBody(param, item)); - } - foreach (var item in queryFilter.Filters) - { - expressions.Add(GetExpressionBody(param, item)); - } - - if (queryFilter.FilterConnect == FilterConnect.And) - { - return expressions.Aggregate(Expression.AndAlso); - } - else - { - return expressions.Aggregate(Expression.OrElse); - } - } - - private static Expression GetExpressionBody(ParameterExpression param, FilterCondition filter) - { - - var lambda = GetPropertyLambdaExpression(param, filter); - var constant = ChangeTypeToExpression(filter, lambda.Body.Type); - - return GetOperateExpression(filter.Operator, lambda.Body, constant); - - } - - - /// - /// 得到值 - /// - /// - /// - /// - - private static Expression ChangeTypeToExpression(FilterCondition filter, Type conversionType) - { - var constant = Expression.Constant(true); - - if (conversionType.Name != typeof(string).Name&&filter.Operator==FilterOperator.Like) - { - - throw new AppException("此{conversionType.Name}类型不支持Like,只有{typeof(string).Name}才支持Like!!!"); - } - - var value = filter.Value.AsTo(conversionType); - if (value == null) - { - return constant; - } - - return Expression.Constant(value, conversionType); - } - - - - - - private static LambdaExpression GetPropertyLambdaExpression(ParameterExpression parameter, FilterCondition filter) - { - var type = parameter.Type; - var property = type.GetProperty(filter.Field, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance); - if (property == null) - { - throw new AppException($"没有得到{filter.Field}该名字!!!"); - } - MemberExpression propertyAccess = Expression.MakeMemberAccess(parameter, property); - return Expression.Lambda(propertyAccess, parameter); - } - - - - private static readonly MethodInfo stringContainsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) }); - - - public static Expression Contains(MemberExpression member, ConstantExpression constant1) - { - Expression constant = constant1.TrimToLower(); - - return Expression.Call(member.TrimToLower(), stringContainsMethod, constant); - - } - - - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/MongoCollectionExtensions.cs b/src/Destiny.Core.Flow.MongoDB/MongoCollectionExtensions.cs deleted file mode 100644 index 019a3dcb..00000000 --- a/src/Destiny.Core.Flow.MongoDB/MongoCollectionExtensions.cs +++ /dev/null @@ -1,40 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Filter; -using Destiny.Core.Flow.Filter.Abstract; -using MongoDB.Driver; -using System; -using System.Linq.Expressions; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow -{ - public static class MongoCollectionExtensions - { - - public static async Task> ToPageAsync(this IMongoCollection collection, Expression> predicate, IPagedRequest request) - { - var count = predicate.IsNotNull() ? await collection.CountDocumentsAsync(predicate) : await collection.CountDocumentsAsync(FilterDefinition.Empty); - var findFluent = collection.Find(predicate).Skip(request.PageSize * (request.PageIndex - 1)).Limit(request.PageSize); - - findFluent = findFluent.OrderBy(request.OrderConditions); - var lists = await findFluent.ToListAsync(); - return new PageResult() { ItemList = lists, Message = "加载成功", Success = true, Total = count.AsTo() }; - - } - - public static async Task> ToPageAsync(this IMongoCollection collection, Expression> predicate, IPagedRequest request, Expression> selector) - { - var count = predicate.IsNotNull() ? await collection.CountDocumentsAsync(predicate) : await collection.CountDocumentsAsync(FilterDefinition.Empty); - var findFluent = collection.Find(predicate).Skip(request.PageSize * (request.PageIndex - 1)).Limit(request.PageSize); - - findFluent = findFluent.OrderBy(request.OrderConditions); - var lists = await findFluent.Project(selector).ToListAsync(); - return new PageResult() { ItemList = lists, Message = "加载成功", Success = true, Total = count.AsTo() }; - - } - - - - - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/MongoDBModuleBase.cs b/src/Destiny.Core.Flow.MongoDB/MongoDBModuleBase.cs deleted file mode 100644 index c6e8aaba..00000000 --- a/src/Destiny.Core.Flow.MongoDB/MongoDBModuleBase.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Destiny.Core.Flow.Modules; -using Destiny.Core.Flow.MongoDB.Repositorys; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace Destiny.Core.Flow -{ - public abstract class MongoDBModuleBase : AppModule - { - - public override void ConfigureServices(ConfigureServicesContext context) - { - - AddDbContext(context.Services); - AddRepository(context.Services); - } - - - - - - public virtual void AddRepository(IServiceCollection services) - { - - services.TryAddScoped(typeof(IMongoDBRepository<,>), typeof(MongoDBRepository<,>)); - } - - - - protected abstract void AddDbContext(IServiceCollection services); - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/MongoDBServiceCollectionExtensions.cs b/src/Destiny.Core.Flow.MongoDB/MongoDBServiceCollectionExtensions.cs deleted file mode 100644 index a85e9553..00000000 --- a/src/Destiny.Core.Flow.MongoDB/MongoDBServiceCollectionExtensions.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Destiny.Core.Flow.MongoDB; -using Destiny.Core.Flow.MongoDB.DbContexts; -using JetBrains.Annotations; -using System; - -namespace Microsoft.Extensions.DependencyInjection -{ - public static class MongoDBServiceCollectionExtensions - { - - public static IServiceCollection AddMongoDbContext(this IServiceCollection services, [CanBeNull] Action optionsAction) where TContext : MongoDbContextBase - { - MongoDbContextOptions options = new MongoDbContextOptions(); - optionsAction(options); - services.AddSingleton(options); - services.AddScoped(); - return services; - } - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/MongoDbContextOptions.cs b/src/Destiny.Core.Flow.MongoDB/MongoDbContextOptions.cs deleted file mode 100644 index 3d72ff2d..00000000 --- a/src/Destiny.Core.Flow.MongoDB/MongoDbContextOptions.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Destiny.Core.Flow.MongoDB.Infrastructure; - -namespace Destiny.Core.Flow.MongoDB -{ - public class MongoDbContextOptions : IMongoDbContextOptions - { - public string ConnectionString { get; set; } - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/MongoEntity.cs b/src/Destiny.Core.Flow.MongoDB/MongoEntity.cs deleted file mode 100644 index 8b88a549..00000000 --- a/src/Destiny.Core.Flow.MongoDB/MongoEntity.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Destiny.Core.Flow.Entity; -using MongoDB.Bson; - -namespace Destiny.Core.Flow -{ - public abstract class MongoEntity : IEntity - { - - public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/Repositorys/IMongoDBRepository.cs b/src/Destiny.Core.Flow.MongoDB/Repositorys/IMongoDBRepository.cs deleted file mode 100644 index 03d7ed64..00000000 --- a/src/Destiny.Core.Flow.MongoDB/Repositorys/IMongoDBRepository.cs +++ /dev/null @@ -1,54 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Ui; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.MongoDB.Repositorys -{ - public interface IMongoDBRepository - where TEntity : IEntity - { - //Find – 返回集合中与提供的搜索条件匹配的所有文档。 - //InsertOne – 插入提供的对象作为集合中的新文档。 - //ReplaceOne – 将与提供的搜索条件匹配的单个文档替换为提供的对象。 - //DeleteOne – 删除与提供的搜索条件匹配的单个文档。 - /// - /// 创建 - /// - /// - /// - Task InsertAsync(TEntity entity); - /// - /// 数组创建 - /// - /// - /// - Task InsertAsync(TEntity[] entitys); - IMongoQueryable Entities { get; } - - IMongoCollection Collection { get; } - - /// - /// 根据键查询 - /// - /// - /// - Task FindByIdAsync(Tkey key); - - /// - /// 更新 - /// - /// - - Task UpdateAsync(Tkey key, UpdateDefinition update); - - /// - /// 删除 - /// - /// - /// - Task DeleteAsync(Tkey key); - - } -} diff --git a/src/Destiny.Core.Flow.MongoDB/Repositorys/MongoDBRepository.cs b/src/Destiny.Core.Flow.MongoDB/Repositorys/MongoDBRepository.cs deleted file mode 100644 index 786ec762..00000000 --- a/src/Destiny.Core.Flow.MongoDB/Repositorys/MongoDBRepository.cs +++ /dev/null @@ -1,121 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.MongoDB.DbContexts; -using Destiny.Core.Flow.Ui; -using Microsoft.Extensions.DependencyInjection; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Security.Principal; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.MongoDB.Repositorys -{ - public class MongoDBRepository : IMongoDBRepository - where TEntity : class, IEntity - where Tkey : IEquatable - { - private readonly MongoDbContextBase _mongoDbContext = null; - - private readonly IPrincipal _principal; - public virtual IMongoCollection Collection { get; private set; } - //BsonDocument - public MongoDBRepository(IServiceProvider serviceProvider, MongoDbContextBase mongoDbContext) - { - _mongoDbContext = mongoDbContext; - - Collection = _mongoDbContext.Collection(); - _principal = serviceProvider.GetService(); - - } - public async Task InsertAsync(TEntity entity) - { - entity = entity.CheckInsert(_principal); - await Collection.InsertOneAsync(entity); - } - public async Task InsertAsync(TEntity[] entitys) - { - entitys = entitys.CheckInsert(_principal); - await Collection.InsertManyAsync(entitys); - - } - - - public async Task FindByIdAsync(Tkey key) - { - - return await Collection.Find(CreateEntityFilter(key)).FirstOrDefaultAsync(); - } - - - private IMongoQueryable CreateQuery() - { - var entities = Collection.AsQueryable(); - if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity))) - { - entities = entities.Where(m => ((ISoftDelete)m).IsDeleted == false); - - } - return entities; - } - - - private Expression> CreateExpression(Expression> expression) - { - Expression> expression1 = o => true; - if (expression == null) - { - expression = o => true; - } - if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity))) - { - expression1 = m => ((ISoftDelete)m).IsDeleted == false; - expression = expression.And(expression1); - } - return expression; - - - } - public virtual IMongoQueryable Entities => CreateQuery(); - - - private FilterDefinition CreateEntityFilter(Tkey id) - { - var filters = new List> - { - Builders.Filter.Eq(e => e.Id, id) - }; - AddGlobalFilters(filters); - return Builders.Filter.And(filters); - } - private void AddGlobalFilters(List> filters) - { - if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity))) - { - filters.Add(Builders.Filter.Eq(e => ((ISoftDelete)e).IsDeleted, false)); - } - - } - - public async Task UpdateAsync(Tkey key, UpdateDefinition update) - { - - var filters = this.CreateEntityFilter(key); - - - var result = await Collection.UpdateManyAsync(filters, update); - return result.ModifiedCount > 0 ? OperationResponse.Ok("更新成功") : OperationResponse.Error("更新失败"); - } - - public async Task DeleteAsync(Tkey key) - { - var filters = this.CreateEntityFilter(key); - var result = await Collection.DeleteOneAsync(filters); - return result.DeletedCount > 0 ? OperationResponse.Ok("删除成功") : OperationResponse.Error("删除失败"); - } - } -} - diff --git a/src/Destiny.Core.Flow.Repository/Destiny.Core.Flow.Repository.csproj b/src/Destiny.Core.Flow.Repository/Destiny.Core.Flow.Repository.csproj index 6cd2ae7b..6bab07cf 100644 --- a/src/Destiny.Core.Flow.Repository/Destiny.Core.Flow.Repository.csproj +++ b/src/Destiny.Core.Flow.Repository/Destiny.Core.Flow.Repository.csproj @@ -5,7 +5,11 @@ - + + + + + diff --git a/src/Destiny.Core.Flow.SeriLog/Destiny.Core.Flow.SeriLog.csproj b/src/Destiny.Core.Flow.SeriLog/Destiny.Core.Flow.SeriLog.csproj index 623054a8..7f4d9d9d 100644 --- a/src/Destiny.Core.Flow.SeriLog/Destiny.Core.Flow.SeriLog.csproj +++ b/src/Destiny.Core.Flow.SeriLog/Destiny.Core.Flow.SeriLog.csproj @@ -5,6 +5,7 @@ + @@ -15,8 +16,4 @@ - - - - diff --git a/src/Destiny.Core.Flow.Services/Audit/AuditStore.cs b/src/Destiny.Core.Flow.Services/Audit/AuditStore.cs index bd3ab189..75274b69 100644 --- a/src/Destiny.Core.Flow.Services/Audit/AuditStore.cs +++ b/src/Destiny.Core.Flow.Services/Audit/AuditStore.cs @@ -10,7 +10,6 @@ using Destiny.Core.Flow.MongoDB.Repositorys; using Destiny.Core.Flow.Ui; using Microsoft.AspNetCore.Identity; - using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Linq; diff --git a/src/Destiny.Core.Flow.Services/Destiny.Core.Flow.Services.csproj b/src/Destiny.Core.Flow.Services/Destiny.Core.Flow.Services.csproj index ce9a852d..9c8e4db0 100644 --- a/src/Destiny.Core.Flow.Services/Destiny.Core.Flow.Services.csproj +++ b/src/Destiny.Core.Flow.Services/Destiny.Core.Flow.Services.csproj @@ -9,14 +9,17 @@ - - + + + + + + + - - diff --git a/src/Destiny.Core.Flow.Swagger/Destiny.Core.Flow.Swagger.csproj b/src/Destiny.Core.Flow.Swagger/Destiny.Core.Flow.Swagger.csproj deleted file mode 100644 index f29641c4..00000000 --- a/src/Destiny.Core.Flow.Swagger/Destiny.Core.Flow.Swagger.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - netstandard2.1 - - - - - - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow.Swagger/Filter/AutoRestSchemaFilter.cs b/src/Destiny.Core.Flow.Swagger/Filter/AutoRestSchemaFilter.cs deleted file mode 100644 index 9ead4ce2..00000000 --- a/src/Destiny.Core.Flow.Swagger/Filter/AutoRestSchemaFilter.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Destiny.Core.Flow.Swagger.Filter -{ - - - public class AutoRestSchemaFilter : ISchemaFilter - { - public void Apply(OpenApiSchema schema, SchemaFilterContext context) - { - //var type = context.Type; - //if (type.IsEnum) - //{ - // schema.Extensions.Add( - // "x-ms-enum", - // new OpenApiObject - // { - // ["name"] = new OpenApiString(type.ToDescription()), - // ["modelAsString"] = new OpenApiBoolean(false), - // ["values"] = new OpenApiString("[{ value: \"dfdf\", description: \"3434\", name: \"1\" }]") - // } - // ); - //}; - } - } -} diff --git a/src/Destiny.Core.Flow.Swagger/Filter/TagDescriptionsDocumentFilter.cs b/src/Destiny.Core.Flow.Swagger/Filter/TagDescriptionsDocumentFilter.cs deleted file mode 100644 index 088a11b9..00000000 --- a/src/Destiny.Core.Flow.Swagger/Filter/TagDescriptionsDocumentFilter.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Destiny.Core.Flow.Swagger.Filter -{ - public class TagDescriptionsDocumentFilter : IDocumentFilter - { - public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) - { - - } - } -} diff --git a/src/Destiny.Core.Flow.Swagger/SwaggerModule.cs b/src/Destiny.Core.Flow.Swagger/SwaggerModule.cs deleted file mode 100644 index 3a005134..00000000 --- a/src/Destiny.Core.Flow.Swagger/SwaggerModule.cs +++ /dev/null @@ -1,144 +0,0 @@ -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.PlatformAbstractions; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; -using Swashbuckle.AspNetCore.SwaggerUI; -using System; -using System.IO; -using System.Reflection; - -namespace Destiny.Core.Flow.Swagger -{ - public class SwaggerModule : AppModule - { - - - - private string _url = string.Empty; - private string _title = string.Empty; - - public override void ConfigureServices(ConfigureServicesContext context) - { - IConfiguration configuration = context.GetConfiguration(); - var title = configuration["Destiny:Swagger:Title"]; - var version = configuration["Destiny:Swagger:Version"]; - var url = configuration["Destiny:Swagger:Url"]; - var html= configuration["Destiny:Swagger:Html"]; ; - - if (url.IsNullOrEmpty()) - { - throw new AppException("Url不能为空 !!!"); - } - - if (version.IsNullOrEmpty()) - { - throw new AppException("版本号不能为空 !!!"); - } - - if (title.IsNullOrEmpty()) - { - - throw new AppException("标题不能为空 !!!"); - } - _url = url; - _title = title; - - context.Services.AddSwaggerGen(s => - { - - - s.SwaggerDoc(version, new OpenApiInfo { Title = title, Version = version, Contact = new OpenApiContact { Name= "Destiny出品",Url = new Uri("https://github.com/DestinyCore/Destiny.Core.Flow") } }); - var basePath = PlatformServices.Default.Application.ApplicationBasePath; - - var files = Directory.GetFiles(basePath, "*.xml"); - foreach (var file in files) - { - s.IncludeXmlComments(file, true); - } - //s.OperationFilter(); - // - // Use method name as operationId - s.CustomOperationIds(apiDesc => - { - return apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null; - }); - // TODO:一定要返回true! - s.DocInclusionPredicate((docName, description) => - { - return true; - }); - - ////https://github.com/domaindrivendev/Swashbuckle.AspNetCore - //s.OperationFilter(); - //s.OperationFilter(); // 很重要!这里配置安全校验,和之前的版本不一样 - s.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"", - Name = "Authorization",//jwt默认的参数名称 - In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中) - Type = SecuritySchemeType.ApiKey, - Scheme = "Bearer", - - }); - - s.AddSecurityRequirement(new OpenApiSecurityRequirement { - { - - new OpenApiSecurityScheme{ - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } - }, - new[] { "readAccess", "writeAccess" } - } - }); - - //s.SchemaFilter(); - //s.DocumentFilter(); - - - }); - } - - - - public virtual Stream GetIndexStream() - { - - return null; - } - - public override void ApplicationInitialization(ApplicationContext context) - { - - var app = context.GetApplicationBuilder(); - app.UseSwagger(); - app.UseSwaggerUI(c => - { - - if (this.GetIndexStream() != null) { - c.IndexStream = ()=>this.GetIndexStream(); - } - c.DefaultModelExpandDepth(2); - c.DefaultModelRendering(ModelRendering.Example); - c.DefaultModelsExpandDepth(-1); - - c.DisplayRequestDuration(); - c.DocExpansion(DocExpansion.None); - c.EnableDeepLinking(); - c.EnableFilter(); - c.MaxDisplayedTags(int.MaxValue); - c.ShowExtensions(); - c.EnableValidator(); - - c.SwaggerEndpoint(_url, _title); - c.RoutePrefix = string.Empty; - }); - } - - - } -} diff --git a/src/Destiny.Core.Flow.TestBase/Destiny.Core.Flow.TestBase.csproj b/src/Destiny.Core.Flow.TestBase/Destiny.Core.Flow.TestBase.csproj index e81ad8bd..1d0cb7da 100644 --- a/src/Destiny.Core.Flow.TestBase/Destiny.Core.Flow.TestBase.csproj +++ b/src/Destiny.Core.Flow.TestBase/Destiny.Core.Flow.TestBase.csproj @@ -5,11 +5,8 @@ + - - - - diff --git a/src/Destiny.Core.Flow/Application/CrudServiceAsync.cs b/src/Destiny.Core.Flow/Application/CrudServiceAsync.cs deleted file mode 100644 index e9933be4..00000000 --- a/src/Destiny.Core.Flow/Application/CrudServiceAsync.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Ui; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Application -{ - public abstract class CrudServiceAsync : ICrudServiceAsync - where TEntity : IEntity, IEquatable - { - private readonly IServiceProvider _serviceProvider = null; - private readonly IRepository _efCoreRepository = null; - - public CrudServiceAsync(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - _efCoreRepository = _serviceProvider.GetService>(); - } - - public Task AddAsync(TEntity entity) - { - throw new NotImplementedException(); - } - - public Task DeleteAsync(TPrimaryKey key) - { - throw new NotImplementedException(); - } - - public Task UpdateAsync(TEntity entity) - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Application/ICrudServiceAsync.cs b/src/Destiny.Core.Flow/Application/ICrudServiceAsync.cs deleted file mode 100644 index d3936d39..00000000 --- a/src/Destiny.Core.Flow/Application/ICrudServiceAsync.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Ui; -using System; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Application -{ - public interface ICrudServiceAsync - where TEntity : IEntity, IEquatable - { - - - /// - /// 异步添加 - /// - /// - /// - Task AddAsync(TEntity entity); - - /// - /// 异步更新 - /// - /// - /// - Task UpdateAsync(TEntity entity); - - - /// - /// 异步删除sss - /// - /// - /// - Task DeleteAsync(TPrimaryKey key); - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Attributes/Base/AttributeBase.cs b/src/Destiny.Core.Flow/Attributes/Base/AttributeBase.cs deleted file mode 100644 index 34d4db8f..00000000 --- a/src/Destiny.Core.Flow/Attributes/Base/AttributeBase.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Attributes.Base -{ - public abstract class AttributeBase : Attribute - { - public abstract string Description(); - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Attributes/MongoDBTableAttribute.cs b/src/Destiny.Core.Flow/Attributes/MongoDBTableAttribute.cs deleted file mode 100644 index 106ac46a..00000000 --- a/src/Destiny.Core.Flow/Attributes/MongoDBTableAttribute.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; - -namespace Destiny.Core.Flow -{ - /// - /// MongoDb表名称特性 - /// - [AttributeUsage(AttributeTargets.Class)] - public class MongoDBTableAttribute : Attribute - { - public MongoDBTableAttribute(string tablename) - { - TableName = tablename; - } - - /// - /// MongoDB表名称 - /// - public string TableName { get; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Audit/AuditChange.cs b/src/Destiny.Core.Flow/Audit/AuditChange.cs deleted file mode 100644 index 13dedefc..00000000 --- a/src/Destiny.Core.Flow/Audit/AuditChange.cs +++ /dev/null @@ -1,77 +0,0 @@ -using Destiny.Core.Flow.Audit.Dto; -using Destiny.Core.Flow.Enums; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; - -namespace Destiny.Core.Flow.Audit -{ - /// - /// 审计 - /// - public class AuditChangeBase - { - - /// - /// 浏览器信息 - /// - [DisplayName("浏览器信息")] - public string BrowserInformation { get; set; } - - /// - /// IP地址 - /// - [DisplayName("IP地址")] - public string Ip { get; set; } - - /// - /// 功能名称 - /// - [DisplayName("功能名称")] - public string FunctionName { get; set; } - - /// - /// 操作Action - /// - [DisplayName("操作Action")] - public string Action { get; set; } - - /// - /// 执行时长 - /// - [DisplayName("执行时长")] - public double ExecutionDuration { get; set; } - - - - [DisplayName("结果类型")] - - /// - /// 结果类型 - /// - public AjaxResultType ResultType { get; set; } - - public string UserId { get; set; } - - - public string Message { get; set; } - - - } - - - public class AuditChange: AuditChangeBase - { - public AuditChange() - { - AuditEntitys = new List(); - } - /// - /// 审计实体集合 - /// - - public List AuditEntitys { get; set; } - public DateTime StartTime { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Audit/AuditEntry.cs b/src/Destiny.Core.Flow/Audit/AuditEntry.cs deleted file mode 100644 index 7cdb2b01..00000000 --- a/src/Destiny.Core.Flow/Audit/AuditEntry.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Destiny.Core.Flow.Data; -using Destiny.Core.Flow.Entity; -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; -using System; -using System.Collections.Generic; -using System.ComponentModel; - -namespace Destiny.Core.Flow.Audit -{ - [DisplayName("审计日志实体")] - [MongoDBTable("DestinyAuditEntityLog")] - public class AuditEntry : EntityBase - { - public AuditEntry() - { - Id = ObjectId.GenerateNewId(); - } - - /// - /// 实体名称 - /// - [DisplayName("实体名称")] - public string EntityAllName { get; set; } - - /// - /// 功能名称 - /// - [DisplayName("实体显示名称")] - public string EntityDisplayName { get; set; } - - /// - /// 表名称 - /// - [DisplayName("表名称")] - public string TableName { get; set; } - - /// - /// 主键 - /// - [DisplayName("主键")] - public Dictionary KeyValues { get; set; } = new Dictionary(); - - /// - /// 操作类型 - /// - [DisplayName("操作类型")] - public DataOperationType OperationType { get; set; } - - - - [BsonDateTimeOptions(Kind = DateTimeKind.Local)] - - - public virtual DateTime CreatedTime { get; set; } - - - public ObjectId AuditLogId { get; set; } - - public string UserId { get; set; } - - public string NickName { get; set; } - - public string UserName { get; set; } - - public virtual string LastModifionTime { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Audit/AuditLog.cs b/src/Destiny.Core.Flow/Audit/AuditLog.cs deleted file mode 100644 index 89f10610..00000000 --- a/src/Destiny.Core.Flow/Audit/AuditLog.cs +++ /dev/null @@ -1,74 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Enums; -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; -using System; -using System.ComponentModel; - -namespace Destiny.Core.Flow.Audit -{ - /// - /// 日志主表 - /// - [DisplayName("日志主表")] - [MongoDBTable("DestinyAuditLog")]// - public class AuditLog : EntityBase - { - public AuditLog() - { - Id = ObjectId.GenerateNewId(); - } - - /// - /// 浏览器信息 - /// - [DisplayName("浏览器信息")] - public string BrowserInformation { get; set; } - - /// - /// IP地址 - /// - [DisplayName("IP地址")] - public string Ip { get; set; } - - /// - /// 功能名称 - /// - [DisplayName("功能名称")] - public string FunctionName { get; set; } - - /// - /// 操作Action - /// - [DisplayName("操作Action")] - public string Action { get; set; } - - /// - /// 执行时长 - /// - [DisplayName("执行时长")] - public double ExecutionDuration { get; set; } - - [BsonDateTimeOptions(Kind = DateTimeKind.Local)] - - - [DisplayName("审计时间")] - public virtual DateTime CreatedTime { get; set; } - - public AjaxResultType? OperationType { get; set; } - - public string UserId { get; set; } - - public string Message { get; set; } - - [DisplayName("用户名")] - /// - /// 获取或设置 操作用户名 - /// - public string UserName { get; set; } - - - /// - public string NickName { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Audit/AuditPropertysEntry.cs b/src/Destiny.Core.Flow/Audit/AuditPropertysEntry.cs deleted file mode 100644 index 29fa0451..00000000 --- a/src/Destiny.Core.Flow/Audit/AuditPropertysEntry.cs +++ /dev/null @@ -1,55 +0,0 @@ -using Destiny.Core.Flow.Data; -using Destiny.Core.Flow.Entity; -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; -using System; -using System.ComponentModel; - -namespace Destiny.Core.Flow.Audit -{ - [DisplayName("审计日志属性")] - [MongoDBTable("DestinyAuditPropertyEntry")] - public class AuditPropertysEntry : EntityBase - { - public AuditPropertysEntry() - { - Id = ObjectId.GenerateNewId(); - } - - /// - /// 属性名称 - /// - [DisplayName("属性名称")] - public string Properties { get; set; } - - /// - /// 属性名称 - /// - [DisplayName("属性显示名称")] - public string PropertieDisplayName { get; set; } - - /// - /// 修改前数据 - /// - [DisplayName("修改前数据")] - public string OriginalValues { get; set; } - - /// - /// 修改后数据 - /// - [DisplayName("修改后数据")] - public string NewValues { get; set; } - - /// - /// 属性类型 - /// - [DisplayName("属性类型")] - public string PropertiesType { get; set; } - - /// - /// 审计日志实体Id - /// - [DisplayName("审计日志实体Id")] - public ObjectId AuditEntryId { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Audit/DataOperationType.cs b/src/Destiny.Core.Flow/Audit/DataOperationType.cs deleted file mode 100644 index e8cfa1ff..00000000 --- a/src/Destiny.Core.Flow/Audit/DataOperationType.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Destiny.Core.Flow.Audit -{ - public enum DataOperationType : sbyte - { - None, - Add, - Delete, - Update - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Audit/DisableAuditingAttribute.cs b/src/Destiny.Core.Flow/Audit/DisableAuditingAttribute.cs deleted file mode 100644 index 747a662a..00000000 --- a/src/Destiny.Core.Flow/Audit/DisableAuditingAttribute.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Audit -{ - /// - /// 禁用审计 - /// - /// 审计实体 - /// - public class AuditEntryBaseDto - { - - /// - /// 实体名称 - /// - [DisplayName("实体名称")] - public string EntityName { get; set; } - - /// - /// 功能名称 - /// - [DisplayName("实体显示名称")] - public string DisplayName { get; set; } - - - /// - /// 主键 - /// - [DisplayName("主键")] - public Dictionary KeyValues { get; set; } = new Dictionary(); - - /// - /// 操作类型 - /// - [DisplayName("操作类型")] - public DataOperationType OperationType { get; set; } - - - public virtual string TypeName { get; set; } - - - } - - public class AuditEntryDto: AuditEntryBaseDto - { - - public AuditEntryDto() - { - AuditPropertys = new List(); - } - public List AuditPropertys { get; set; } - - - } - - - -} diff --git a/src/Destiny.Core.Flow/Audit/Dto/AuditEntryOutputPageDto.cs b/src/Destiny.Core.Flow/Audit/Dto/AuditEntryOutputPageDto.cs deleted file mode 100644 index 25a8b2cb..00000000 --- a/src/Destiny.Core.Flow/Audit/Dto/AuditEntryOutputPageDto.cs +++ /dev/null @@ -1,63 +0,0 @@ -using Destiny.Core.Flow.Entity; -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; -using System; -using System.Collections.Generic; -using System.ComponentModel; - -namespace Destiny.Core.Flow.Audit.Dto -{ - /// - /// 实体输出Dto - /// - [DisplayName("日志实体输出")] - public class AuditEntryOutputPageDto : OutputDto - { - /// - /// 实体名称 - /// - [DisplayName("实体名称")] - public string EntityAllName { get; set; } - - /// - /// 功能名称 - /// - [DisplayName("实体显示名称")] - public string EntityDisplayName { get; set; } - - /// - /// 表名称 - /// - [DisplayName("表名称")] - public string TableName { get; set; } - - /// - /// 主键 - /// - [DisplayName("主键")] - public Dictionary KeyValues { get; set; } = new Dictionary(); - - /// - /// 操作类型 - /// - [DisplayName("操作类型")] - public DataOperationType OperationType { get; set; } - - [DisplayName("用户名")] - /// - /// 获取或设置 操作用户名 - /// - public string UserName { get; set; } - - [DisplayName("昵称")] - /// - /// 获取或设置 操作昵称 - /// - public string NickName { get; set; } - - [BsonDateTimeOptions(Kind = DateTimeKind.Local)] - public DateTime? CreatedTime { get; set; } - - public string UserId { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Audit/Dto/AuditLogOutputPageDto.cs b/src/Destiny.Core.Flow/Audit/Dto/AuditLogOutputPageDto.cs deleted file mode 100644 index 4a2af798..00000000 --- a/src/Destiny.Core.Flow/Audit/Dto/AuditLogOutputPageDto.cs +++ /dev/null @@ -1,54 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Enums; -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; -using System; -using System.ComponentModel; - -namespace Destiny.Core.Flow.Audit.Dto -{ - /// - /// 审计日志分页输出Dto - /// - [DisplayName("审计日志分页列表")] - public class AuditLogOutputPageDto : OutputDto - { - - public string BrowserInformation { get; set; } - - public string Ip { get; set; } - - - public string FunctionName { get; set; } - - - public string Action { get; set; } - - public double ExecutionDuration { get; set; } - - - [BsonDateTimeOptions(Kind = DateTimeKind.Local)] - /// - ///获取或设置 创建时间 - /// - [DisplayName("审计时间")] - public DateTime CreatedTime { get; set; } - - [DisplayName("用户名")] - /// - /// 获取或设置 操作用户名 - /// - public string UserName { get; set; } - - - /// - public string NickName { get; set; } - - - public AjaxResultType? OperationType { get; set; } - - public string UserId { get; set; } - - public string Message { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Audit/Dto/AuditPropertyDto.cs b/src/Destiny.Core.Flow/Audit/Dto/AuditPropertyDto.cs deleted file mode 100644 index a0f373fc..00000000 --- a/src/Destiny.Core.Flow/Audit/Dto/AuditPropertyDto.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; - -namespace Destiny.Core.Flow.Audit.Dto -{ - /// - /// 审计属性 - /// - public class AuditPropertyDto - { - - - /// - /// 属性名称 - /// - [DisplayName("属性名称")] - public string PropertyName { get; set; } - - /// - /// 属性名称 - /// - [DisplayName("属性显示名称")] - public string PropertyDisplayName { get; set; } - - /// - /// 修改前数据 - /// - [DisplayName("修改前数据")] - public string OriginalValues { get; set; } - - /// - /// 修改后数据 - /// - [DisplayName("修改后数据")] - public string NewValues { get; set; } - - /// - /// 属性类型 - /// - [DisplayName("属性类型")] - public string PropertyType { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Audit/Dto/AuditPropertyEntryOutputPageDto.cs b/src/Destiny.Core.Flow/Audit/Dto/AuditPropertyEntryOutputPageDto.cs deleted file mode 100644 index 207f0982..00000000 --- a/src/Destiny.Core.Flow/Audit/Dto/AuditPropertyEntryOutputPageDto.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Destiny.Core.Flow.Entity; -using MongoDB.Bson; -using System; -using System.ComponentModel; - -namespace Destiny.Core.Flow.Audit.Dto -{ - /// - /// 日志属性输出Dto - /// - [DisplayName("日志属性输出Dto")] - public class AuditPropertyEntryOutputPageDto:OutputDtoBase - { - /// - /// 属性名称 - /// - [DisplayName("属性名称")] - public string Properties { get; set; } - - /// - /// 属性名称 - /// - [DisplayName("属性显示名称")] - public string PropertieDisplayName { get; set; } - - /// - /// 修改前数据 - /// - [DisplayName("修改前数据")] - public string OriginalValues { get; set; } - - /// - /// 修改后数据 - /// - [DisplayName("修改后数据")] - public string NewValues { get; set; } - - /// - /// 属性类型 - /// - [DisplayName("属性类型")] - public string PropertiesType { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Audit/EntityHistory/AuditHelper.cs b/src/Destiny.Core.Flow/Audit/EntityHistory/AuditHelper.cs deleted file mode 100644 index f4e2658c..00000000 --- a/src/Destiny.Core.Flow/Audit/EntityHistory/AuditHelper.cs +++ /dev/null @@ -1,157 +0,0 @@ -using Destiny.Core.Flow.Audit.Dto; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Helpers; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.ChangeTracking; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using Microsoft.EntityFrameworkCore.Metadata; - -namespace Destiny.Core.Flow.Audit.EntityHistory -{ - public class AuditHelper : IAuditHelper - { - public IEnumerable GetAuditEntity(IEnumerable entityEntries) - { - List auditEntries = new List(); - EntityState[] states = { EntityState.Added, EntityState.Modified, EntityState.Deleted }; - return entityEntries.Where(m => m.Entity != null && states.Contains(m.State) && m.GetType().IsDefined(typeof(DisableAuditingAttribute)) == false).ToArray().Select(o => this.CreateAuditEntity(o)).ToList(); - - } - - /// - /// 创建审计 - /// - /// - /// - private AuditEntryDto CreateAuditEntity(EntityEntry entityEntry) - { - var entity = entityEntry.Entity; - var type = entity.GetType(); - var displayName = type.ToDescription(); //得到实体上特性 - DataOperationType changeType= DataOperationType.Add; - - switch (entityEntry.State) - { - //case EntityState.Detached: - // changeType = DataOperationType.None; - // break; - - //case EntityState.Unchanged: - // changeType = DataOperationType.None; - // break; - - case EntityState.Deleted: - changeType = DataOperationType.Delete; - break; - - case EntityState.Modified: - changeType = DataOperationType.Update; - break; - - case EntityState.Added: - changeType = DataOperationType.Add; - break; - - } - AuditEntryDto audit = new AuditEntryDto(); - audit.KeyValues = new Dictionary(); - audit.EntityName = type.FullName; - audit.DisplayName = displayName; - audit.TypeName = type.FullName; - audit.OperationType = changeType; - audit.AuditPropertys = GetAuditPropertys(entityEntry); - audit.KeyValues = new Dictionary() { - { "Id",GetEntityKey(entity)} - }; - return audit; - } - - /// - /// 得到实体主键 - /// - /// - /// - private string GetEntityKey(object entityAsObj) - { - return entityAsObj - .GetType().GetProperty("Id")? - .GetValue(entityAsObj)? - .ToJson(); - } - - /// - /// 得到审计属性 - /// - /// - /// - private List GetAuditPropertys(EntityEntry entityEntry) - { - List propertyDtos = new List(); - - foreach (var propertie in entityEntry.CurrentValues.Properties.Where(p => !p.IsConcurrencyToken && p.PropertyInfo.GetCustomAttribute() == null)) - { - var propertyEntry = entityEntry.Property(propertie.Name);//获取字段名 - AuditPropertyDto propertyDto = new AuditPropertyDto(); - propertyDto.PropertyName = propertie.Name; - propertyDto.PropertyDisplayName = propertyEntry.Metadata.PropertyInfo.ToDescription(); - propertyDto.PropertyType = propertie.ClrType.FullName; - if (propertie.IsPrimaryKey()) - { - continue; - } - if (entityEntry.State == EntityState.Added) - { - var currentValue = propertyEntry.CurrentValue?.ToString(); - propertyDto.NewValues = currentValue; - propertyDtos.Add(propertyDto); - } - else if (entityEntry.State == EntityState.Modified) - { - var originalValue = propertyEntry.OriginalValue?.ToString(); - var currentValue = propertyEntry.CurrentValue?.ToString(); - if (currentValue != originalValue) - { - propertyDto.NewValues = currentValue; - - propertyDto.OriginalValues = originalValue; - propertyDtos.Add(propertyDto); - } - - - } - else if (entityEntry.State == EntityState.Deleted) - { - - var originalValue = propertyEntry.OriginalValue?.ToString(); - propertyDto.OriginalValues = originalValue; - propertyDtos.Add(propertyDto); - } - - - } - - return propertyDtos; - //return entityEntry.Metadata.GetProperties().Where(p => !p.IsConcurrencyToken && p.PropertyInfo.GetCustomAttribute() == null).Select(p => - //{ - // var propertyEntry = entityEntry.Property(p.Name);//获取字段名 - // AuditPropertyDto propertyDto = new AuditPropertyDto(); - // propertyDto.PropertyName = p.Name; - // propertyDto.PropertyDisplayName = propertyEntry.Metadata.PropertyInfo.ToDescription(); - // propertyDto.PropertyType = p.ClrType.FullName; - // var currentValue = propertyEntry.CurrentValue?.ToString(); - // var originalValue = propertyEntry.OriginalValue?.ToString(); - // propertyDto.NewValues = currentValue; - // propertyDto.OriginalValues = originalValue; - // return propertyDto; - - //}).ToList(); - - - } - - } -} diff --git a/src/Destiny.Core.Flow/Audit/EntityHistory/IAuditHelper.cs b/src/Destiny.Core.Flow/Audit/EntityHistory/IAuditHelper.cs deleted file mode 100644 index 85633688..00000000 --- a/src/Destiny.Core.Flow/Audit/EntityHistory/IAuditHelper.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Destiny.Core.Flow.Audit.Dto; -using Destiny.Core.Flow.Dependency; -using Microsoft.EntityFrameworkCore.ChangeTracking; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Audit.EntityHistory -{ - /// - /// 审计帮助 - /// - public interface IAuditHelper : ITransientDependency - { - /// - /// 得到实体审计 - /// - /// - /// - IEnumerable GetAuditEntity(IEnumerable entityEntries); - } -} diff --git a/src/Destiny.Core.Flow/Audit/IAuditStore.cs b/src/Destiny.Core.Flow/Audit/IAuditStore.cs deleted file mode 100644 index 937bfda8..00000000 --- a/src/Destiny.Core.Flow/Audit/IAuditStore.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Destiny.Core.Flow.Audit.Dto; -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Filter; -using Destiny.Core.Flow.Filter.Abstract; -using Destiny.Core.Flow.Ui; -using MongoDB.Bson; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Audit -{ - public interface IAuditStore : IScopedDependency - { - - - /// - /// 异步保存 - /// - /// - /// - Task SaveAsync(AuditChange auditChange); - /// - /// 分页获取审计日志 - /// - /// - /// - Task> GetAuditLogPageAsync(PageRequest request); - - - /// - /// 分页获取数据实体审计 - /// - /// - /// - Task> GetAuditEntryPageAsync(PageRequest request); - - - /// - /// 分页获取数据实体属性审计 - /// - /// - /// - Task> GetAuditEntryPropertyPageAsync(PageRequest request); - - - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/ConsulEntity/ServiceEntity.cs b/src/Destiny.Core.Flow/ConsulEntity/ServiceEntity.cs deleted file mode 100644 index 12dd2b8c..00000000 --- a/src/Destiny.Core.Flow/ConsulEntity/ServiceEntity.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Destiny.Core.Flow.ConsulEntity -{ - public class ServiceEntity - { - /// - /// 服务IP(自动获取) - /// - public string IP { get; set; } - - /// - /// 服务端口 - /// - public int Port { get; set; } - - /// - /// 服务名称 - /// - public string ServiceName { get; set; } - - /// - /// Consul注册IP - /// - public string ConsulIP { get; set; } - - /// - /// Consul注册端口 - /// - public int ConsulPort { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Data/ComnGuid.cs b/src/Destiny.Core.Flow/Data/ComnGuid.cs deleted file mode 100644 index 74e4674e..00000000 --- a/src/Destiny.Core.Flow/Data/ComnGuid.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Data -{ - public static class ComnGuid - { - /// - /// 转为有序的GUID - /// - /// - public static Guid NewGuid() - { - byte[] guidArray = Guid.NewGuid().ToByteArray(); - - DateTime baseDate = new DateTime(1900, 1, 1); - DateTime now = DateTime.Now; - - // Get the days and milliseconds which will be used to build the byte string - TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks); - TimeSpan msecs = now.TimeOfDay; - - // Convert to a byte array Note that SQL Server is accurate to 1/300th of a millisecond - // so we divide by 3.333333 - byte[] daysArray = BitConverter.GetBytes(days.Days); - byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333)); - - // Reverse the bytes to match SQL Servers ordering - Array.Reverse(daysArray); - Array.Reverse(msecsArray); - - // Copy the bytes into the guid - Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2); - Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4); - - return new Guid(guidArray); - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Data/Core/Collections/ITypeList.cs b/src/Destiny.Core.Flow/Data/Core/Collections/ITypeList.cs deleted file mode 100644 index e6463d66..00000000 --- a/src/Destiny.Core.Flow/Data/Core/Collections/ITypeList.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Destiny.Core.Flow.Data.Core.Collections -{ - public interface ITypeList : ITypeList - { - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Data/Core/Collections/ITypeListOfModel.cs b/src/Destiny.Core.Flow/Data/Core/Collections/ITypeListOfModel.cs deleted file mode 100644 index ea9c8a9a..00000000 --- a/src/Destiny.Core.Flow/Data/Core/Collections/ITypeListOfModel.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Data.Core.Collections -{ - public interface ITypeList : IList - { - void Add() where T : TBaseType; - - bool Contains() where T : TBaseType; - - void Remove() where T : TBaseType; - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Data/Core/Collections/TypeList.cs b/src/Destiny.Core.Flow/Data/Core/Collections/TypeList.cs deleted file mode 100644 index 04840d9f..00000000 --- a/src/Destiny.Core.Flow/Data/Core/Collections/TypeList.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Data.Core.Collections -{ - public class TypeList : TypeList, ITypeList - { - } - - public class TypeList : ITypeList - { - public int Count => _typeList.Count; - - public bool IsReadOnly => false; - - public Type this[int index] - { - get => _typeList[index]; - set - { - CheckType(value); - _typeList[index] = value; - } - } - - private readonly List _typeList; - - public TypeList() - { - _typeList = new List(); - } - - public void Add() where T : TBaseType - { - _typeList.Add(typeof(T)); - } - - public void Add(Type item) - { - CheckType(item); - _typeList.Add(item); - } - - public void Insert(int index, Type item) - { - _typeList.Insert(index, item); - } - - public int IndexOf(Type item) - { - return _typeList.IndexOf(item); - } - - public bool Contains() where T : TBaseType - { - return Contains(typeof(T)); - } - - public bool Contains(Type item) - { - return _typeList.Contains(item); - } - - /// - public void Remove() where T : TBaseType - { - _typeList.Remove(typeof(T)); - } - - public bool Remove(Type item) - { - return _typeList.Remove(item); - } - - /// - public void RemoveAt(int index) - { - _typeList.RemoveAt(index); - } - - public void Clear() - { - _typeList.Clear(); - } - - public void CopyTo(Type[] array, int arrayIndex) - { - _typeList.CopyTo(array, arrayIndex); - } - - public IEnumerator GetEnumerator() - { - return _typeList.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return _typeList.GetEnumerator(); - } - - private static void CheckType(Type item) - { - if (!typeof(TBaseType).IsAssignableFrom(item)) - { - throw new ArgumentException("给定项的类型不是" + typeof(TBaseType).AssemblyQualifiedName, nameof(item)); - } - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Data/Core/Function/FunctionAttribute.cs b/src/Destiny.Core.Flow/Data/Core/Function/FunctionAttribute.cs deleted file mode 100644 index 79445340..00000000 --- a/src/Destiny.Core.Flow/Data/Core/Function/FunctionAttribute.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Data.Core -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] - public class FunctionAttribute : Attribute - { - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Data/Core/Function/FunctionInfo.cs b/src/Destiny.Core.Flow/Data/Core/Function/FunctionInfo.cs deleted file mode 100644 index 1483b4da..00000000 --- a/src/Destiny.Core.Flow/Data/Core/Function/FunctionInfo.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Destiny.Core.Flow.Data.Core -{ - public class FunctionInfo - { - public string Name { get; set; } - - public bool IsEnabled { get; set; } - - public string Description { get; set; } - - public string LinkUrl { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Data/Dto/SelectItem.cs b/src/Destiny.Core.Flow/Data/Dto/SelectItem.cs deleted file mode 100644 index f0a722b1..00000000 --- a/src/Destiny.Core.Flow/Data/Dto/SelectItem.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Data.Dto -{ - /// - /// 选择项 - /// - public class SelectItem - { - public string Key { get; set; } - public string Text { get; set; } - - - public string Value { get; set; } - - } - - -} diff --git a/src/Destiny.Core.Flow/Data/LazyConcurrentDictionary.cs b/src/Destiny.Core.Flow/Data/LazyConcurrentDictionary.cs deleted file mode 100644 index 90d72603..00000000 --- a/src/Destiny.Core.Flow/Data/LazyConcurrentDictionary.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; - -namespace Destiny.Core.Flow.Data -{ - public class LazyConcurrentDictionary - { - private readonly ConcurrentDictionary> _dictionary; - - public LazyConcurrentDictionary() - { - _dictionary = new ConcurrentDictionary>(); - } - - public LazyConcurrentDictionary(IEqualityComparer comparer) - { - _dictionary = new ConcurrentDictionary>(comparer); - } - - public TValue GetOrAdd(TKey key, Func valueFactory) - { - var lazyResult = _dictionary.GetOrAdd(key, - k => new Lazy(() => valueFactory(k), LazyThreadSafetyMode.ExecutionAndPublication)); - return lazyResult.Value; - } - - public TValue AddOrUpdate(TKey key, TValue addValue, Func updateValueFactory) - { - var lazyResult = _dictionary.AddOrUpdate( - key, - new Lazy(() => addValue), - (k, currentValue) => new Lazy(() => updateValueFactory(k, currentValue.Value), - LazyThreadSafetyMode.ExecutionAndPublication)); - return lazyResult.Value; - } - - public TValue AddOrUpdate(TKey key, Func addValueFactory, Func updateValueFactory) - { - var lazyResult = _dictionary.AddOrUpdate( - key, - k => new Lazy(() => addValueFactory(k)), - (k, currentValue) => new Lazy(() => updateValueFactory(k, currentValue.Value), - LazyThreadSafetyMode.ExecutionAndPublication)); - return lazyResult.Value; - } - - public int Count => _dictionary.Count; - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/DependencyAppModule.cs b/src/Destiny.Core.Flow/Dependency/DependencyAppModule.cs deleted file mode 100644 index a02dd6b2..00000000 --- a/src/Destiny.Core.Flow/Dependency/DependencyAppModule.cs +++ /dev/null @@ -1,96 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Destiny.Core.Flow.Reflection; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Linq; -using System.Reflection; - -namespace Destiny.Core.Flow.Dependency -{ - /// - /// 自动注入模块 - /// - public class DependencyAppModule : AppModule - { - public override void ConfigureServices(ConfigureServicesContext context) - { - - context.Services.AddTransient(typeof(Lazy<>), typeof(LazyFactory<>)); - var services = context.Services; - - AddAutoInjection(services); - } - - private void AddAutoInjection(IServiceCollection services) - { - //var servicesTypes = AssemblyHelper.GetAssembliesByName("Destiny.Core.Flow.Services", "Destiny.Core.Flow.Repository").SelectMany(type=>type.DefinedTypes); - - var typeFinder = services.GetOrAddSingletonService(); - var baseTypes = new Type[] { typeof(IScopedDependency), typeof(ITransientDependency), typeof(ISingletonDependency) }; - - var types = typeFinder.FindAll().Distinct(); - - types = types.Where(type => type.IsClass && !type.IsAbstract && (baseTypes.Any(b => b.IsAssignableFrom(type))) || type.GetCustomAttribute() != null); - foreach (var implementedInterType in types) - { - var attr = implementedInterType.GetCustomAttribute(); - var typeInfo = implementedInterType.GetTypeInfo(); - var serviceTypes = typeInfo.ImplementedInterfaces.Where(x => x.HasMatchingGenericArity(typeInfo) && !x.HasAttribute() && x != typeof(IDisposable)).Select(t => t.GetRegistrationType(typeInfo)); - - var lifetime = GetServiceLifetime(implementedInterType); - - if (lifetime == null) - { - break; - } - if (serviceTypes.Count() == 0) - { - services.Add(new ServiceDescriptor(implementedInterType, implementedInterType, lifetime.Value)); - continue; - } - - if (attr?.AddSelf == true) - { - services.Add(new ServiceDescriptor(implementedInterType, implementedInterType, lifetime.Value)); - } - - foreach (var serviceType in serviceTypes.Where(o => !o.HasAttribute())) - { - services.Add(new ServiceDescriptor(serviceType, implementedInterType, lifetime.Value)); - } - } - } - - private ServiceLifetime? GetServiceLifetime(Type type) - { - var attr = type.GetCustomAttribute(); - if (attr != null) - { - return attr.Lifetime; - } - - if (typeof(IScopedDependency).IsAssignableFrom(type)) - { - return ServiceLifetime.Scoped; - } - - if (typeof(ITransientDependency).IsAssignableFrom(type)) - { - return ServiceLifetime.Transient; - } - - if (typeof(ISingletonDependency).IsAssignableFrom(type)) - { - return ServiceLifetime.Singleton; - } - - return null; - } - - public override void ApplicationInitialization(ApplicationContext context) - { - var app = context.GetApplicationBuilder(); - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/DependencyAttribute.cs b/src/Destiny.Core.Flow/Dependency/DependencyAttribute.cs deleted file mode 100644 index fcd635a0..00000000 --- a/src/Destiny.Core.Flow/Dependency/DependencyAttribute.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; - -namespace Destiny.Core.Flow.Dependency -{ - [AttributeUsage(AttributeTargets.Class)] - public class DependencyAttribute : Attribute - { - /// - /// 初始化一个 类型的新实例 - /// - public DependencyAttribute(ServiceLifetime lifetime) - { - Lifetime = lifetime; - } - - /// - /// 获取 生命周期类型,代替 , , 三个接口的作用 - /// - public ServiceLifetime Lifetime { get; } - - /// - /// 获取或设置 是否注册自身类型,默认没有接口的类型会注册自身,当此属性值为true时,也会注册自身 - /// - public bool AddSelf { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/DictionaryScoped.cs b/src/Destiny.Core.Flow/Dependency/DictionaryScoped.cs deleted file mode 100644 index 0d97fc97..00000000 --- a/src/Destiny.Core.Flow/Dependency/DictionaryScoped.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Destiny.Core.Flow.Audit; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Dependency -{ - [Dependency(ServiceLifetime.Scoped, AddSelf = true)] - public class DictionaryScoped : ConcurrentDictionary, IDisposable - { - - - /// - /// 是否管理 - /// - public bool IsAdmin { get; set; } - - /// - /// 是否系统 - /// - public bool IsSystem { get; set; } - - /// - /// 角色名集合 - /// - public List RoleNames { get; set; } - - /// - /// 角色集合 - /// - public List RoleIds { get; set; } - - - /// - /// 审计 - /// - public AuditChange AuditChange { get; set; } = new AuditChange(); - public virtual void Dispose() - { - this.Clear(); - this.IsAdmin = false; - this.IsSystem = false; - this.RoleNames?.Clear(); - this.RoleIds?.Clear(); - this.AuditChange = null; - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/IScopedDependency.cs b/src/Destiny.Core.Flow/Dependency/IScopedDependency.cs deleted file mode 100644 index b1643439..00000000 --- a/src/Destiny.Core.Flow/Dependency/IScopedDependency.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Destiny.Core.Flow.Dependency -{ /// - /// 实现此接口的类型将自动注册为模式 - [IgnoreDependency] - public interface IScopedDependency - { - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/IServiceProviderAccessor.cs b/src/Destiny.Core.Flow/Dependency/IServiceProviderAccessor.cs deleted file mode 100644 index 768ed47a..00000000 --- a/src/Destiny.Core.Flow/Dependency/IServiceProviderAccessor.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Dependency -{ - /// - /// 服务提供者访问器 - /// - public interface IServiceProviderAccessor - { - IServiceProvider ServiceProvider { get; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/ISingletonDependency.cs b/src/Destiny.Core.Flow/Dependency/ISingletonDependency.cs deleted file mode 100644 index 2d4cce7a..00000000 --- a/src/Destiny.Core.Flow/Dependency/ISingletonDependency.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Destiny.Core.Flow.Dependency -{ - /// - /// 实现此接口的类型将自动注册为 模式 - /// - [IgnoreDependency] - public interface ISingletonDependency - { - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/ITransientDependency.cs b/src/Destiny.Core.Flow/Dependency/ITransientDependency.cs deleted file mode 100644 index a65924ff..00000000 --- a/src/Destiny.Core.Flow/Dependency/ITransientDependency.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Destiny.Core.Flow.Dependency -{ - /// - /// 实现此接口的类型将自动注册为 模式 - /// - [IgnoreDependency] - public interface ITransientDependency - { - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/IgnoreDependencyAttribute.cs b/src/Destiny.Core.Flow/Dependency/IgnoreDependencyAttribute.cs deleted file mode 100644 index 295fea77..00000000 --- a/src/Destiny.Core.Flow/Dependency/IgnoreDependencyAttribute.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Dependency -{ - /// - /// 标注了此特性的类,将忽略依赖注入自动映射 - /// - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] - public class IgnoreDependencyAttribute : Attribute - { - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/IocManage.cs b/src/Destiny.Core.Flow/Dependency/IocManage.cs deleted file mode 100644 index 28dd441f..00000000 --- a/src/Destiny.Core.Flow/Dependency/IocManage.cs +++ /dev/null @@ -1,67 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using System; - -namespace Destiny.Core.Flow.Dependency -{ - /// - /// Ioc管理 - /// - public sealed class IocManage - { - private IServiceProvider _provider; - - private IServiceCollection _services; - - /// - /// Ioc管理实例 - /// - private static readonly Lazy InstanceLazy = new Lazy(() => new IocManage()); - - private IocManage() - { - } - - public static IocManage Instance => InstanceLazy.Value; - - /// - /// 设置应用程序服务提供者 - /// - internal void SetApplicationServiceProvider(IServiceProvider provider) - { - provider.NotNull(nameof(provider)); - _provider = provider; - } - - internal void SetServiceCollection(IServiceCollection services) - { - services.NotNull(nameof(services)); - _services = services; - } - - /// - /// 得到服务 - /// - /// - /// - - public T GetService() - { - _provider.NotNull(nameof(_provider)); - _services.NotNull(nameof(_services)); - return _provider.GetService(); - } - - /// - /// 得到日志记录 - /// - /// - /// - public ILogger GetLogger() - { - ILoggerFactory factory = _provider.GetService(); - return factory.CreateLogger(); - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/LazyFactory.cs b/src/Destiny.Core.Flow/Dependency/LazyFactory.cs deleted file mode 100644 index eba97a9b..00000000 --- a/src/Destiny.Core.Flow/Dependency/LazyFactory.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; - -namespace Destiny.Core.Flow.Dependency -{ - public sealed class LazyFactory : Lazy where T : class - { - public LazyFactory(IServiceProvider provider) - : base(provider.GetRequiredService) - { - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Dependency/ObjectAccessor.cs b/src/Destiny.Core.Flow/Dependency/ObjectAccessor.cs deleted file mode 100644 index cdb8425c..00000000 --- a/src/Destiny.Core.Flow/Dependency/ObjectAccessor.cs +++ /dev/null @@ -1,23 +0,0 @@ -using JetBrains.Annotations; - -namespace Destiny.Core.Flow.Dependency -{ - public interface IObjectAccessor - { - TType Value { get; set; } - } - - public class ObjectAccessor : IObjectAccessor - { - public ObjectAccessor([CanBeNull] TType obj) - { - Value = obj; - } - - public ObjectAccessor() - { - } - - public TType Value { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Destiny.Core.Flow.csproj b/src/Destiny.Core.Flow/Destiny.Core.Flow.csproj deleted file mode 100644 index 3114be09..00000000 --- a/src/Destiny.Core.Flow/Destiny.Core.Flow.csproj +++ /dev/null @@ -1,41 +0,0 @@ - - - - netstandard2.1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Destiny.Core.Flow/Disposables/IDisposable2.cs b/src/Destiny.Core.Flow/Disposables/IDisposable2.cs deleted file mode 100644 index 806a4107..00000000 --- a/src/Destiny.Core.Flow/Disposables/IDisposable2.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using System.Threading; - -namespace Destiny.Core.Flow -{ - /// - /// 释放接口 - /// - public interface IDisposable2 : IDisposable - { - /// - /// 已释放 - /// - bool Disposed { get; } - - /// - /// 被销毁时触发事件 - /// - event EventHandler OnDisposed; - } - - public class DisposeBase : IDisposable2 - { - public bool Disposed => _disposed > 0; - - public event EventHandler OnDisposed; - - private Int32 _disposed = 0; - - public void Dispose() - { - Dispose(true); - ///告诉GC,不要调用析构函数 - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (Interlocked.CompareExchange(ref _disposed, 1, 0) != 0) - { - return; - } - if (disposing) - { - ///告诉GC,不要调用析构函数 - GC.SuppressFinalize(this); - } - - OnDisposed?.Invoke(this, EventArgs.Empty); - } - - ~DisposeBase() - { - Dispose(false); - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Entity/DatabaseType.cs b/src/Destiny.Core.Flow/Entity/DatabaseType.cs deleted file mode 100644 index 43b9c723..00000000 --- a/src/Destiny.Core.Flow/Entity/DatabaseType.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Entity -{ - /// - /// 表示数据类型 - /// - public enum DatabaseType - { - /// - /// MySql数据库类型 - /// - - MySql, - - /// - /// SqlServer数据库类型 - /// - SqlServer - } -} diff --git a/src/Destiny.Core.Flow/Entity/DestinyContextOptionsBuilder.cs b/src/Destiny.Core.Flow/Entity/DestinyContextOptionsBuilder.cs deleted file mode 100644 index e805cb30..00000000 --- a/src/Destiny.Core.Flow/Entity/DestinyContextOptionsBuilder.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Entity -{ - /// - /// 上下文选项生成器 - /// - public class DestinyContextOptionsBuilder - { - /// - /// 迁移Assembly名字 - /// - public string MigrationsAssemblyName { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Entity/EntityBase.cs b/src/Destiny.Core.Flow/Entity/EntityBase.cs deleted file mode 100644 index e10303bc..00000000 --- a/src/Destiny.Core.Flow/Entity/EntityBase.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using System; -using System.ComponentModel; - -namespace Destiny.Core.Flow.Entity -{ - public abstract class EntityBase : IEntity where TKey : IEquatable - { - public EntityBase() - { - } - - [Description("主键")] - public TKey Id { get; set; } - - /// - /// 判断两个实体是否是同一数据记录的实体 - /// - /// 要比较的实体信息 - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - if (!(obj is EntityBase entity)) - { - return false; - } - return IsKeyEqual(entity.Id, Id); - } - - /// - /// 实体ID是否相等 - /// - public static bool IsKeyEqual(TKey id1, TKey id2) - { - if (id1 == null && id2 == null) - { - return true; - } - if (id1 == null || id2 == null) - { - return false; - } - - Type type = typeof(TKey); - if (type.IsDeriveClassFrom(typeof(IEquatable))) - { - return id1.Equals(id2); - } - return Equals(id1, id2); - } - - /// - /// 用作特定类型的哈希函数。 - /// - /// - /// 当前 的哈希代码。
    如果 Idnull 则返回0, 如果不为 - /// null 则返回 Id 对应的哈希值 - ///
    - public override int GetHashCode() - { - if (Id == null) - { - return 0; - } - return Id.ToString().GetHashCode(); - } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Entity/ICreatedTime.cs b/src/Destiny.Core.Flow/Entity/ICreatedTime.cs deleted file mode 100644 index 7e868330..00000000 --- a/src/Destiny.Core.Flow/Entity/ICreatedTime.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Destiny.Core.Flow.Audit; -using System; - -namespace Destiny.Core.Flow.Entity -{ - /// - /// 创建时间 - /// - public interface ICreatedTime - { - [DisableAuditing] - DateTime CreatedTime { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Entity/ICreationAudited.cs b/src/Destiny.Core.Flow/Entity/ICreationAudited.cs deleted file mode 100644 index 991b41fd..00000000 --- a/src/Destiny.Core.Flow/Entity/ICreationAudited.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Destiny.Core.Flow.Audit; - -namespace Destiny.Core.Flow.Entity -{ - /// - /// 定义创建审计 - /// - public interface ICreationAudited : ICreatedTime - - where TUserKey : struct - { - /// - /// 创建者用户ID - /// - - [DisableAuditing] - TUserKey? CreatorUserId { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Entity/IDto.cs b/src/Destiny.Core.Flow/Entity/IDto.cs deleted file mode 100644 index 47a34d9d..00000000 --- a/src/Destiny.Core.Flow/Entity/IDto.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - public interface IDto - { - TKey Id { get; set; } - } - - - public abstract class DtoBase : IDto - { - public virtual TKey Id { get; set; } - - - } -} diff --git a/src/Destiny.Core.Flow/Entity/IEntity.cs b/src/Destiny.Core.Flow/Entity/IEntity.cs deleted file mode 100644 index 35bc9bcf..00000000 --- a/src/Destiny.Core.Flow/Entity/IEntity.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - - /// - /// - /// - public interface IEntity - { - } -} diff --git a/src/Destiny.Core.Flow/Entity/IEntityExtensions.cs b/src/Destiny.Core.Flow/Entity/IEntityExtensions.cs deleted file mode 100644 index ebe86f79..00000000 --- a/src/Destiny.Core.Flow/Entity/IEntityExtensions.cs +++ /dev/null @@ -1,96 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using System; -using System.Security.Principal; - -namespace Destiny.Core.Flow.Entity -{ - - public static class IEntityExtensions - { - - public static TEntity[] CheckInsert(this TEntity[] entitys, IPrincipal principal) - where TEntity : class, IEntity - where TPrimaryKey : IEquatable - { - - for (int i = 0; i < entitys.Length; i++) - { - var entity = entitys[i]; - entitys[i] = entity.CheckInsert(principal); - } - return entitys; - } - - - public static TEntity CheckInsert(this TEntity entity, IPrincipal principal) - where TEntity : class, IEntity - where TPrimaryKey : IEquatable - { - - entity = entity.CheckICreatedTime(); - - var creationAudited = entity.GetType().GetInterface(/*$"ICreationAudited`1"*/typeof(ICreationAudited<>).Name); - if (creationAudited == null) - { - return entity; - } - - var typeArguments = creationAudited?.GenericTypeArguments[0]; - var fullName = typeArguments?.FullName; - if (fullName == typeof(Guid).FullName) - { - entity = entity.CheckICreationAudited(principal); - - } - - return entity; - - } - - - public static TEntity CheckICreatedTime(this TEntity entity) - where TEntity : class, IEntity - where TPrimaryKey : IEquatable - { - if (!(entity is ICreatedTime)) - { - return entity; - } - ICreatedTime entity1 = (ICreatedTime)entity; - - entity1.CreatedTime = DateTime.Now; - return (TEntity)entity1; - } - - - public static TEntity CheckICreationAudited(this TEntity entity, IPrincipal principal) - - where TUserKey : struct, IEquatable - { - if (!entity.GetType().IsBaseOn(typeof(ICreationAudited<>))) - { - return entity; - } - - ICreationAudited entity1 = (ICreationAudited)entity; - entity1.CreatorUserId = principal?.Identity.GetUesrId(); - entity1.CreatedTime = DateTime.Now; - return (TEntity)entity1; - } - - public static TEntity CheckIModificationAudited(this TEntity entity, IPrincipal principal) - - where TUserKey : struct, IEquatable - { - if (!entity.GetType().IsBaseOn(typeof(IModificationAudited<>))) - { - return entity; - } - - IModificationAudited entity1 = (IModificationAudited)entity; - entity1.LastModifierUserId = principal?.Identity?.GetUesrId(); - entity1.LastModifionTime = DateTime.Now; - return (TEntity)entity1; - } - } -} diff --git a/src/Destiny.Core.Flow/Entity/IEntityOfModel.cs b/src/Destiny.Core.Flow/Entity/IEntityOfModel.cs deleted file mode 100644 index 589ab33f..00000000 --- a/src/Destiny.Core.Flow/Entity/IEntityOfModel.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.ComponentModel; - -namespace Destiny.Core.Flow.Entity -{ - /// - /// 实体接口 - /// - /// - public interface IEntity : IEntity - { - [Description("主键")] - TKey Id { get; } - } - - - -} diff --git a/src/Destiny.Core.Flow/Entity/IFullAuditedEntityOfModel.cs b/src/Destiny.Core.Flow/Entity/IFullAuditedEntityOfModel.cs deleted file mode 100644 index 2aba55bd..00000000 --- a/src/Destiny.Core.Flow/Entity/IFullAuditedEntityOfModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - /// - /// - /// - /// - public interface IFullAuditedEntity : ICreationAudited, IModificationAudited, ISoftDelete - where TPrimaryKey : struct - { - - - } - - - -} diff --git a/src/Destiny.Core.Flow/Entity/IInputDto.cs b/src/Destiny.Core.Flow/Entity/IInputDto.cs deleted file mode 100644 index d0997fbf..00000000 --- a/src/Destiny.Core.Flow/Entity/IInputDto.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - /// - /// 定义输入DTO底层接口 - /// - /// - public interface IInputDto - { - /// - /// 获取或设置 主键,唯一标识 - /// - TKey Id { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Entity/IModificationAudited.cs b/src/Destiny.Core.Flow/Entity/IModificationAudited.cs deleted file mode 100644 index 30cad86a..00000000 --- a/src/Destiny.Core.Flow/Entity/IModificationAudited.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Destiny.Core.Flow.Audit; - -namespace Destiny.Core.Flow.Entity -{ - /// - /// 修改审核信息 - /// - public interface IModificationAudited : IModificationTime - where TUserKey : struct - - { - /// - /// 最后修改用户ID - /// - [DisableAuditing] - TUserKey? LastModifierUserId { get; set; } - } - -} diff --git a/src/Destiny.Core.Flow/Entity/IModificationTime.cs b/src/Destiny.Core.Flow/Entity/IModificationTime.cs deleted file mode 100644 index b3bec489..00000000 --- a/src/Destiny.Core.Flow/Entity/IModificationTime.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Destiny.Core.Flow.Audit; -using System; - -namespace Destiny.Core.Flow.Entity -{ - public interface IModificationTime - { - /// - /// 最后修改时间 - /// - [DisableAuditing] - DateTime? LastModifionTime { get; set; } - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/Entity/IOutputDto.cs b/src/Destiny.Core.Flow/Entity/IOutputDto.cs deleted file mode 100644 index 927f179f..00000000 --- a/src/Destiny.Core.Flow/Entity/IOutputDto.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - /// - /// 定义输出DTO - /// - public interface IOutputDto - { - - } - - /// - /// 继承第一层DTO接口 - /// - /// - public interface IOutputDto : IOutputDto - { - - TKey Id { get; set; } - - } - /// - /// 实现DTO接口 - /// - /// - public class OutputDtoBase : IOutputDto - { - - public TKey Id { get; set; } - - } -} diff --git a/src/Destiny.Core.Flow/Entity/IRepository.cs b/src/Destiny.Core.Flow/Entity/IRepository.cs deleted file mode 100644 index e8f9b3a2..00000000 --- a/src/Destiny.Core.Flow/Entity/IRepository.cs +++ /dev/null @@ -1,196 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Ui; -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow -{ - public interface IRepository - where TEntity : IEntity - { - - IUnitOfWork UnitOfWork { get; } - #region 查询 - /// - /// 获取 不跟踪数据更改(NoTracking)的查询数据源 - /// - - IQueryable Entities { get; } - - - /// - /// 获取 跟踪数据更改(Tracking)的查询数据源 - /// - - IQueryable TrackEntities { get; } - - - /// - /// 根据ID得到实体 - /// - /// 主键 - /// 返回查询后实体 - TEntity GetById(TPrimaryKey primaryKey); - - /// - /// 异步根据ID得到实体 - /// - /// 主键 - /// 返回查询后实体 - Task GetByIdAsync(TPrimaryKey primaryKey); - - - - /// - ///查询不跟踪数据源 - /// - /// 条件 - /// 返回查询后数据源 - IQueryable Query(Expression> predicate); - - - /// - /// 查询不跟踪数据源 - /// - /// - /// 条件 - /// 数据筛选表达式 - /// 返回查询后数据源 - IQueryable Query(Expression> predicate, Expression> selector); - /// - ///查询跟踪数据源 - /// - /// 条件 - /// 返回查询后数据源 - IQueryable TrackQuery(Expression> predicate); - - /// - /// 异步得到实体 - /// - /// 条件 - /// 返回查询后实体 - Task GetAsync(Expression> predicate); - - /// - /// 异步判断是否存 - /// - /// 要判断的条件 - /// 返回true/false,若存在true,则false - Task ExistAsync(Expression> predicate); - - #endregion - - - #region 添加 - - /// - /// 以异步DTO插入实体 - /// - /// 添加DTO类型 - /// 添加DTO - /// 添加信息合法性检查委托 - /// 由DTO到实体的转换委托 - /// 业务操作结果 - Task InsertAsync(TInputDto dto, Func checkFunc = null, Func> insertFunc = null, Func completeFunc = null) where TInputDto : IInputDto; - - /// - /// 以异步插入实体 - /// - /// 要插入实体 - /// 影响的行数 - Task InsertAsync(TEntity entity); - /// - /// 异步添加单条实体 - /// - /// - /// - Task InsertAsync(TEntity entity, Func checkFunc = null, Func> insertFunc = null, Func completeFunc = null); - - /// - /// 以异步批量插入实体 - /// - /// 要插入实体集合 - /// 影响的行数 - Task InsertAsync(TEntity[] entitys); - - - /// - /// 批量插入实体 - /// - /// 要插入实体集合 - /// - int Insert(params TEntity[] entitys); - #endregion - - - #region 更新 - - - /// - /// 以异步DTO更新实体 - /// - /// 更新DTO类型 - /// 更新DTO - /// 添加信息合法性检查委托 - /// 由DTO到实体的转换委托 - /// 业务操作结果 - Task UpdateAsync(TInputDto dto, Func checkFunc = null, Func> updateFunc = null) where TInputDto : class, IInputDto, new(); - - - /// - /// 异步更新 - /// - /// 要更新实体 - /// 返回更新受影响条数 - Task UpdateAsync(TEntity entity); - - - /// - /// 同步更新 - /// - /// 要更新实体 - /// 返回更新受影响条数 - int Update(TEntity entity); - #endregion - - #region 删除 - /// - /// 删除 - /// - /// - /// 删除合法性检查委托 - /// - Task DeleteAsync(TPrimaryKey primaryKey, Func checkFunc = null); - - - - - /// - /// 删除 - /// - /// 要删除实体 - /// 返回删除受影响条数 - Task DeleteAsync(TEntity entity); - - /// - /// 异步删除所有符合特定条件的实体 - /// - /// 查询条件谓语表达式 - /// 操作影响的行数 - Task DeleteBatchAsync(Expression> predicate, CancellationToken cancellationToken = default); - - /// - /// 删除 - /// - /// 要删除实体集合 - /// 操作影响的行数 - int Delete(params TEntity[] entitys); - - - - #endregion - } -} diff --git a/src/Destiny.Core.Flow/Entity/ISeedData.cs b/src/Destiny.Core.Flow/Entity/ISeedData.cs deleted file mode 100644 index 633a007c..00000000 --- a/src/Destiny.Core.Flow/Entity/ISeedData.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - /// - /// 设置种子数据 - /// - public interface ISeedData - { - - /// - ///种子数据初始化 - /// - void Initialize(); - - int Order { get; } - - bool Disable { get; } - } -} diff --git a/src/Destiny.Core.Flow/Entity/ISoftDelete.cs b/src/Destiny.Core.Flow/Entity/ISoftDelete.cs deleted file mode 100644 index b81776b4..00000000 --- a/src/Destiny.Core.Flow/Entity/ISoftDelete.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - /// - /// 软删除 - /// - public interface ISoftDelete - { - - bool IsDeleted { get; set; } - - } -} diff --git a/src/Destiny.Core.Flow/Entity/IStateDto.cs b/src/Destiny.Core.Flow/Entity/IStateDto.cs deleted file mode 100644 index c88bad85..00000000 --- a/src/Destiny.Core.Flow/Entity/IStateDto.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Destiny.Core.Flow.Enums; -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Entity -{ - public interface IStateDto : IDto - { - DtoState DtoState { get; set; } - } - - - public abstract class StateDto : DtoBase, IStateDto - { - protected StateDto() - { - - - DtoState = IsNew() == true ? DtoState.Add : DtoState.Update; - } - - public bool IsNew() => - EqualityComparer.Default.Equals(Id, default); - public virtual DtoState DtoState { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Entity/IUnitOfWork.cs b/src/Destiny.Core.Flow/Entity/IUnitOfWork.cs deleted file mode 100644 index 750e6a32..00000000 --- a/src/Destiny.Core.Flow/Entity/IUnitOfWork.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Destiny.Core.Flow.Ui; -using Microsoft.EntityFrameworkCore; -using System; -using System.Data.Common; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Entity -{ - /// - /// 工作单元 - /// - public interface IUnitOfWork : IDisposable - { - /// - /// 是否提交 - /// - bool HasCommit(); - - - /// - /// 释放时触发 - /// - Action OnDispose { get;set; } - - /// - /// 得到上下文 - /// - /// - DbContext GetDbContext(); - - /// - /// 开启事务 - /// - void BeginTransaction(); - - /// - /// 提交事务 - /// - void Commit(); - - /// - /// 开启异步事务 - /// - /// - /// - Task BeginTransactionAsync(CancellationToken cancellationToken = default(CancellationToken)); - - /// - /// 回滚事务 - /// - void Rollback(); - - - /// - /// 异步提交事务 - /// - /// - Task CommitAsync(); - - /// - /// 异步回滚 - /// - /// - Task RollbackAsync(); - - void Push(); - - void Pop(); - - } -} diff --git a/src/Destiny.Core.Flow/Entity/IUnitOfWorkAccessor.cs b/src/Destiny.Core.Flow/Entity/IUnitOfWorkAccessor.cs deleted file mode 100644 index 82ddc08e..00000000 --- a/src/Destiny.Core.Flow/Entity/IUnitOfWorkAccessor.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - interface IUnitOfWorkAccessor - { - } -} diff --git a/src/Destiny.Core.Flow/Entity/IUnitOfWorkManager.cs b/src/Destiny.Core.Flow/Entity/IUnitOfWorkManager.cs deleted file mode 100644 index 606113a7..00000000 --- a/src/Destiny.Core.Flow/Entity/IUnitOfWorkManager.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - public interface IUnitOfWorkManager - { - - IUnitOfWork Current { get; } - - } -} diff --git a/src/Destiny.Core.Flow/Entity/InputDto.cs b/src/Destiny.Core.Flow/Entity/InputDto.cs deleted file mode 100644 index 0a38222c..00000000 --- a/src/Destiny.Core.Flow/Entity/InputDto.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - public class InputDto : IInputDto - { - public virtual TKey Id { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Entity/InputWaitStateDto.cs b/src/Destiny.Core.Flow/Entity/InputWaitStateDto.cs deleted file mode 100644 index 4f57529b..00000000 --- a/src/Destiny.Core.Flow/Entity/InputWaitStateDto.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - public class InputWaitStateDto : StateDto, IInputDto - { - } -} diff --git a/src/Destiny.Core.Flow/Entity/Modules/MigrationModuleBase.cs b/src/Destiny.Core.Flow/Entity/Modules/MigrationModuleBase.cs deleted file mode 100644 index fd362999..00000000 --- a/src/Destiny.Core.Flow/Entity/Modules/MigrationModuleBase.cs +++ /dev/null @@ -1,60 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Destiny.Core.Flow.Entity.Modules -{ - public abstract class MigrationModuleBase : AppModule - { - - - /// - /// 是否自动迁移 - /// - /// - /// - protected abstract bool IsAutoMigration(ApplicationContext context); - - /// - /// 是否添加种子数据 - /// - /// - /// - protected abstract bool IsAddSeedData(ApplicationContext context); - - public override void ApplicationInitialization(ApplicationContext context) - { - var app = context.GetApplicationBuilder(); - - if (IsAutoMigration(context)) { - context.ServiceProvider.CreateScoped(provider => - { - var unitOfWork = provider.GetService(); - var dbContext = unitOfWork.GetDbContext(); - string[] migrations = dbContext.Database.GetPendingMigrations().ToArray(); - if (migrations.Length > 0) - { - dbContext.Database.Migrate(); - } - }); - } - - - if (IsAddSeedData(context)) - { - var seedDatas = context.ServiceProvider.GetServices(); - - foreach (var seed in seedDatas?.OrderBy(o => o.Order).Where(o => !o.Disable)) - { - seed.Initialize(); - } - } - - } - } -} diff --git a/src/Destiny.Core.Flow/Entity/OutputDto.cs b/src/Destiny.Core.Flow/Entity/OutputDto.cs deleted file mode 100644 index 90158a60..00000000 --- a/src/Destiny.Core.Flow/Entity/OutputDto.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Destiny.Core.Flow.Entity -{ - public class OutputDto : OutputDtoBase - { - - } - - -} diff --git a/src/Destiny.Core.Flow/Entity/SeedDataBase.cs b/src/Destiny.Core.Flow/Entity/SeedDataBase.cs deleted file mode 100644 index 9e8b6338..00000000 --- a/src/Destiny.Core.Flow/Entity/SeedDataBase.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Linq.Expressions; - -namespace Destiny.Core.Flow.Entity -{ - - public abstract class SeedDataBase : ISeedData - where TEntity : IEntity - where TKey : IEquatable - { - public IServiceProvider _serviceProvider = null; - - public virtual int Order { get; protected set; } = 0; - - /// - /// 是否禁用 - /// - public virtual bool Disable { get; protected set; } = false; - - - /// - /// - /// - /// - protected SeedDataBase(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - - public virtual void Initialize() - { - var entities = SetSeedData(); - SaveDatabase(entities); - } - - protected abstract TEntity[] SetSeedData(); - - /// - /// 同步保存到数据库中 - /// - /// - protected abstract void SaveDatabase(TEntity[] entities); - - - /// - /// 条件表达树 - /// - /// - /// - protected abstract Expression> Expression(TEntity entity); - - - } -} diff --git a/src/Destiny.Core.Flow/Enums/Enums.cs b/src/Destiny.Core.Flow/Enums/Enums.cs deleted file mode 100644 index d41fc08b..00000000 --- a/src/Destiny.Core.Flow/Enums/Enums.cs +++ /dev/null @@ -1,183 +0,0 @@ -using Destiny.Core.Flow.Filter; -using System.ComponentModel; - -namespace Destiny.Core.Flow.Enums -{ - - public enum OperationResponseType - { - - [Description("操作成功")] - Success = 0, - - [Description("操作引发错误")] - Error = 5, - - - [Description("系统出现异常")] - Exp = 10, - - [Description("数据源不存在")] - QueryNull = 15, - - - [Description("操作没有引发任何变化")] - NoChanged = 20, - } - - - public enum AuthResultType - { - /// - /// 未经授权 - /// - [Description("未经授权")] - Unauthorized = 401, - - /// - /// 已登录但权限不足 - /// - [Description("当前用户权限不足")] - Uncertified = 403, - - /// - /// 功能资源找不到 - /// - [Description("当前功能资源找不到")] - NoFound = 404, - - /// - /// 成功 - /// - [Description("成功")] - Success = 200, - } - - public enum AjaxResultType - { - /// - /// 消息结果 - /// - [Description("消息结果")] - - Info = 203, - - /// - /// 成功 - /// - [Description("成功")] - Success = 200, - - /// - /// 错误 - /// - [Description("错误")] - Error = 500, - - /// - /// 未经授权 - /// - [Description("未经授权")] - Unauthorized = 401, - - /// - /// 已登录但权限不足 - /// - [Description("当前用户权限不足")] - Uncertified = 403, - - /// - /// 功能资源找不到 - /// - [Description("当前功能资源找不到")] - NoFound = 404 - - - } - - [Description("姓别")] - public enum Sex - { - [Description("男")] - Man, - [Description("女")] - Female - } - - - /// - /// 排序方向 - /// - public enum SortDirection - { - - Ascending = 0, - - Descending = 1 - } - - - [Description("过滤操作器")] - - //过滤操作器 - public enum FilterOperator - { - - /// - /// - /// - - [Description("等于")] - Equal, - - [Description("大于")] - GreaterThan, - - - [Description("大于或等于")] - GreaterThanOrEqual, - - - [Description("小于")] - LessThan, - - - [Description("小于或等于")] - LessThanOrEqual, - - - [Description("不等于")] - NotEqual, - - - [Description("包含")] - In, - - - [Description("模糊查询")] - Like, - - [Description("不包含")] - NotIn - } - - [Description("过滤连接器")] - public enum FilterConnect - { - [FilterCode("and")] - And, - - [FilterCode("or")] - Or - } - - [Description("Dto状态")] - public enum DtoState - { - - [Description("新增")] - Add = 0, - [Description("更新")] - Update = 5 - } -} diff --git a/src/Destiny.Core.Flow/Events/Abstractions/IEventBase.cs b/src/Destiny.Core.Flow/Events/Abstractions/IEventBase.cs deleted file mode 100644 index bcd41b9d..00000000 --- a/src/Destiny.Core.Flow/Events/Abstractions/IEventBase.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Events.Abstractions -{ - /// - /// 事件基类 - /// - public interface IEventBase - { /// - /// 事件发布时间 - /// - DateTimeOffset EventAt { get; } - - /// - /// 事件ID - /// - string EventId { get; } - - - } -} diff --git a/src/Destiny.Core.Flow/Events/Abstractions/IEventHandlerBase.cs b/src/Destiny.Core.Flow/Events/Abstractions/IEventHandlerBase.cs deleted file mode 100644 index c965f867..00000000 --- a/src/Destiny.Core.Flow/Events/Abstractions/IEventHandlerBase.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Events.Abstractions -{ - public interface IEventHandlerBase where TEvent : class, IEventBase - { - - Task Handle(TEvent notification, CancellationToken cancellationToken); - - } -} diff --git a/src/Destiny.Core.Flow/Events/CacheEventDataBase.cs b/src/Destiny.Core.Flow/Events/CacheEventDataBase.cs deleted file mode 100644 index 75056d65..00000000 --- a/src/Destiny.Core.Flow/Events/CacheEventDataBase.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.ComponentModel; - -namespace Destiny.Core.Flow.Events -{ - public abstract class CacheEventDataBase : Notification - { - - public EventState EventState { get; set; } = EventState.Add; - } - - [Description("事件状态")] - public enum EventState - { - [Description("添加")] - Add = 5, - [Description("更新")] - Update = 10, - [Description("移除")] - Remove = 15, - } -} diff --git a/src/Destiny.Core.Flow/Events/EventBase.cs b/src/Destiny.Core.Flow/Events/EventBase.cs deleted file mode 100644 index f65b44a4..00000000 --- a/src/Destiny.Core.Flow/Events/EventBase.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Destiny.Core.Flow.Events.Abstractions; -using MediatR; -using Newtonsoft.Json; -using System; - -namespace Destiny.Core.Flow.Events -{ - public abstract class EventBase : IEventBase, INotification - { - - protected EventBase() - { - EventAt = DateTimeOffset.UtcNow; - EventId = Guid.NewGuid().ToString(); - } - - protected EventBase(string eventId) - { - EventId = eventId; - EventAt = DateTimeOffset.UtcNow; - } - - - public EventBase(string eventId, DateTimeOffset eventAt) - { - EventId = eventId; - EventAt = eventAt; - } - - - [JsonIgnore] - public virtual DateTimeOffset EventAt { get; private set; } - - [JsonIgnore] - public virtual string EventId { get; private set; } - } -} diff --git a/src/Destiny.Core.Flow/Events/EventBus/IEventBus.cs b/src/Destiny.Core.Flow/Events/EventBus/IEventBus.cs deleted file mode 100644 index 6babbee9..00000000 --- a/src/Destiny.Core.Flow/Events/EventBus/IEventBus.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Destiny.Core.Flow.Events.Abstractions; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Events.EventBus -{ - /// - /// 事件总线 - /// - public interface IEventBus - { - - - /// - /// 发布事件 - /// - /// - /// - /// - /// - Task PublishAsync(T @event, CancellationToken cancellationToken = default) where T : class, IEventBase; - - } -} diff --git a/src/Destiny.Core.Flow/Events/EventBus/IMediatorHandler.cs b/src/Destiny.Core.Flow/Events/EventBus/IMediatorHandler.cs deleted file mode 100644 index d5a88c8a..00000000 --- a/src/Destiny.Core.Flow/Events/EventBus/IMediatorHandler.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Destiny.Core.Flow.Events.Abstractions; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Events.EventBus -{ - /// - /// 中介者处理器 - /// - public interface IMediatorHandler - { - /// - /// 发布事件 - /// - /// - /// - /// - /// - Task PublishAsync(T @event, CancellationToken cancellationToken = default) where T : class, IEventBase; - } -} diff --git a/src/Destiny.Core.Flow/Events/EventBus/InMemoryBus.cs b/src/Destiny.Core.Flow/Events/EventBus/InMemoryBus.cs deleted file mode 100644 index 22907962..00000000 --- a/src/Destiny.Core.Flow/Events/EventBus/InMemoryBus.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Destiny.Core.Flow.Events.Abstractions; -using MediatR; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Events.EventBus -{ - public sealed class InMemoryDefaultBus : IMediatorHandler - { - private readonly IMediator _mediator; - - public InMemoryDefaultBus(IMediator mediator) - { - _mediator = mediator; - } - - - /// - /// 发布事件 - /// - /// - /// - /// - /// - public Task PublishAsync(T @event, CancellationToken cancellationToken = default) where T : class, IEventBase - - { - return _mediator.Publish(@event); - } - - - } -} diff --git a/src/Destiny.Core.Flow/Events/EventBusExtensions.cs b/src/Destiny.Core.Flow/Events/EventBusExtensions.cs deleted file mode 100644 index eafd7257..00000000 --- a/src/Destiny.Core.Flow/Events/EventBusExtensions.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Destiny.Core.Flow.Events.EventBus; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace Destiny.Core.Flow.Events -{ - public static class EventBusExtensions - { - - public static IServiceCollection AddEvents(this IServiceCollection services) - { - - return services; - } - - } -} diff --git a/src/Destiny.Core.Flow/Events/EventHandlerBase.cs b/src/Destiny.Core.Flow/Events/EventHandlerBase.cs deleted file mode 100644 index 898df011..00000000 --- a/src/Destiny.Core.Flow/Events/EventHandlerBase.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Destiny.Core.Flow.Events.Abstractions; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Events -{ - public abstract class EventHandlerBase : IEventHandlerBase where TEvent : class, IEventBase - { - public abstract Task Handle(TEvent eventData, CancellationToken cancellationToken); - } -} diff --git a/src/Destiny.Core.Flow/Events/EventQueue.cs b/src/Destiny.Core.Flow/Events/EventQueue.cs deleted file mode 100644 index d4e3b232..00000000 --- a/src/Destiny.Core.Flow/Events/EventQueue.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Collections.Concurrent; - -namespace Destiny.Core.Flow.Events -{ - public class EventQueue - { - private readonly ConcurrentDictionary> _eventQueues = - new ConcurrentDictionary>(); - - public void Enqueue(string queueName, TEvent @event) where TEvent : EventBase - { - var queue = _eventQueues.GetOrAdd(queueName, q => new ConcurrentQueue()); - queue.Enqueue(@event); - } - - public bool TryDequeue(string queueName, out EventBase @event) - { - var queue = _eventQueues.GetOrAdd(queueName, q => new ConcurrentQueue()); - return queue.TryDequeue(out @event); - } - - public bool TryRemoveQueue(string queueName) - { - return _eventQueues.TryRemove(queueName, out _); - } - - public bool ContainsQueue(string queueName) => _eventQueues.ContainsKey(queueName); - - public ConcurrentQueue this[string queueName] => _eventQueues[queueName]; - } -} diff --git a/src/Destiny.Core.Flow/Events/MediatorAppModule.cs b/src/Destiny.Core.Flow/Events/MediatorAppModule.cs deleted file mode 100644 index b39346fb..00000000 --- a/src/Destiny.Core.Flow/Events/MediatorAppModule.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Destiny.Core.Flow.Events.EventBus; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Modules; -using Destiny.Core.Flow.Reflection; -using MediatR; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace Destiny.Core.Flow.Events -{ - public class MediatorAppModule : AppModule - { - - - public override void ConfigureServices(ConfigureServicesContext context) - { - var services = context.Services; - var assemblys = services.GetOrAddSingletonService()?.FindAll(); - services.AddMediatR(assemblys); - services.TryAddTransient(); - } - - - - } -} diff --git a/src/Destiny.Core.Flow/Events/Notification.cs b/src/Destiny.Core.Flow/Events/Notification.cs deleted file mode 100644 index 36362bec..00000000 --- a/src/Destiny.Core.Flow/Events/Notification.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Destiny.Core.Flow.Events -{ - public abstract class Notification : EventBase - { - - - - - } -} diff --git a/src/Destiny.Core.Flow/Events/NotificationHandlerBase.cs b/src/Destiny.Core.Flow/Events/NotificationHandlerBase.cs deleted file mode 100644 index ec991b04..00000000 --- a/src/Destiny.Core.Flow/Events/NotificationHandlerBase.cs +++ /dev/null @@ -1,9 +0,0 @@ -using MediatR; - -namespace Destiny.Core.Flow.Events -{ - public abstract class NotificationHandlerBase : EventHandlerBase, INotificationHandler where TEvent : EventBase - { - - } -} diff --git a/src/Destiny.Core.Flow/Exceptions/AppException.cs b/src/Destiny.Core.Flow/Exceptions/AppException.cs deleted file mode 100644 index e2551923..00000000 --- a/src/Destiny.Core.Flow/Exceptions/AppException.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Exceptions -{ - public class AppException : Exception - { - - - - public AppException() - { - - } - public AppException(string message) : base(message) - { - - } - public AppException(string message, Exception innerException) : base(message, innerException) - { - - } - - public AppException ThrowIf(bool flag) - { - if (flag) - { - throw this; - } - return this; - } - } -} diff --git a/src/Destiny.Core.Flow/Exceptions/MessageBox.cs b/src/Destiny.Core.Flow/Exceptions/MessageBox.cs deleted file mode 100644 index 2a3e55ec..00000000 --- a/src/Destiny.Core.Flow/Exceptions/MessageBox.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Exceptions -{ - public class MessageBox - { - - - /// - /// 显示消息 - /// - /// - public static void Show(string message) => throw new AppException(message); - - - public static void Show(string message, Exception ex) => throw new AppException(message, ex); - - public static void ShowIf(string message, bool flag) { - - if (flag) - { - throw new AppException(message); - } - } - - } -} diff --git a/src/Destiny.Core.Flow/Exceptions/MissingTypeRegistrationException.cs b/src/Destiny.Core.Flow/Exceptions/MissingTypeRegistrationException.cs deleted file mode 100644 index be249331..00000000 --- a/src/Destiny.Core.Flow/Exceptions/MissingTypeRegistrationException.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.Extensions.Internal; -using System; - -namespace Destiny.Core.Flow.Exceptions -{ - /// - /// 缺少类型注册异常 - /// - - public class MissingTypeRegistrationException : InvalidOperationException - { - public MissingTypeRegistrationException(Type serviceType) - : base($"找不到类型的任何注册服务 '{TypeNameHelper.GetTypeDisplayName(serviceType)}'.") - { - ServiceType = serviceType; - } - - public Type ServiceType { get; } - } -} diff --git a/src/Destiny.Core.Flow/ExpressionUtil/Expressionable.cs b/src/Destiny.Core.Flow/ExpressionUtil/Expressionable.cs deleted file mode 100644 index b9c2f505..00000000 --- a/src/Destiny.Core.Flow/ExpressionUtil/Expressionable.cs +++ /dev/null @@ -1,328 +0,0 @@ -using System; -using System.Linq.Expressions; - -namespace Destiny.Core.Flow -{ - /// - /// 表达树 - /// - /// - public class Expressionable where T : class, new() - { - Expression> _exp = null; - - /// - /// 表达树and操作 - /// - /// - /// - public Expressionable And(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.AndAlso(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - /// - /// 表达树and操作并且加上判断条件 - /// - /// - /// - /// - public Expressionable AndIf(bool isAnd, Expression> exp) - { - if (isAnd) - And(exp); - return this; - } - - - /// - /// 表达树Or操作 - /// - /// - /// - public Expressionable Or(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.OrElse(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - /// - /// 表达树Or操作 - /// - /// - /// - public Expressionable OrIf(bool isOr, Expression> exp) - { - if (isOr) - Or(exp); - return this; - } - - /// - /// 转成表达树 - /// - /// - public Expression> ToExpression() - { - if (_exp == null) - _exp = it => true; - return _exp; - } - } - public class Expressionable where T : class, new() where T2 : class, new() - { - Expression> _exp = null; - - public Expressionable And(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.AndAlso(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - public Expressionable AndIf(bool isAnd, Expression> exp) - { - if (isAnd) - And(exp); - return this; - } - - public Expressionable Or(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.OrElse(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - public Expressionable OrIf(bool isOr, Expression> exp) - { - if (isOr) - Or(exp); - return this; - } - - - public Expression> ToExpression() - { - if (_exp == null) - _exp = (it, t2) => true; - return _exp; - } - } - public class Expressionable where T : class, new() where T2 : class, new() where T3 : class, new() - { - Expression> _exp = null; - - public Expressionable And(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.AndAlso(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - public Expressionable AndIf(bool isAnd, Expression> exp) - { - if (isAnd) - And(exp); - return this; - } - - public Expressionable Or(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.OrElse(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - public Expressionable OrIf(bool isOr, Expression> exp) - { - if (isOr) - Or(exp); - return this; - } - - - - public Expression> ToExpression() - { - if (_exp == null) - _exp = (it, t2, t3) => true; - return _exp; - } - } - public class Expressionable where T : class, new() where T2 : class, new() where T3 : class, new() where T4 : class, new() - { - Expression> _exp = null; - - public Expressionable And(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.AndAlso(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - public Expressionable AndIf(bool isAnd, Expression> exp) - { - if (isAnd) - And(exp); - return this; - } - - public Expressionable Or(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.OrElse(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - public Expressionable OrIf(bool isOr, Expression> exp) - { - if (isOr) - Or(exp); - return this; - } - - - public Expression> ToExpression() - { - if (_exp == null) - _exp = (it, t2, t3, t4) => true; - return _exp; - } - } - public class Expressionable where T : class, new() where T2 : class, new() where T3 : class, new() where T4 : class, new() where T5 : class, new() - { - Expression> _exp = null; - - public Expressionable And(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.AndAlso(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - public Expressionable AndIf(bool isAnd, Expression> exp) - { - if (isAnd) - And(exp); - return this; - } - - public Expressionable Or(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.OrElse(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - public Expressionable OrIf(bool isOr, Expression> exp) - { - if (isOr) - Or(exp); - return this; - } - - - public Expression> ToExpression() - { - if (_exp == null) - _exp = (it, t2, t3, t4, T5) => true; - return _exp; - } - } - - public class Expressionable where T : class, new() where T2 : class, new() where T3 : class, new() where T4 : class, new() where T5 : class, new() where T6 : class, new() - { - Expression> _exp = null; - - public Expressionable And(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.AndAlso(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - public Expressionable AndIf(bool isAnd, Expression> exp) - { - if (isAnd) - And(exp); - return this; - } - - public Expressionable Or(Expression> exp) - { - if (_exp == null) - _exp = exp; - else - _exp = Expression.Lambda>(Expression.OrElse(_exp.Body, exp.Body), _exp.Parameters); - return this; - } - - public Expressionable OrIf(bool isOr, Expression> exp) - { - if (isOr) - Or(exp); - return this; - } - - - public Expression> ToExpression() - { - if (_exp == null) - _exp = (it, t2, t3, t4, T5, t6) => true; - return _exp; - } - } - public class Expressionable - { - public static Expressionable Create() where T : class, new() - { - return new Expressionable(); - } - public static Expressionable Create() where T : class, new() where T2 : class, new() - { - return new Expressionable(); - } - public static Expressionable Create() where T : class, new() where T2 : class, new() where T3 : class, new() - { - return new Expressionable(); - } - public static Expressionable Create() where T : class, new() where T2 : class, new() where T3 : class, new() where T4 : class, new() - { - return new Expressionable(); - } - public static Expressionable Create() where T : class, new() where T2 : class, new() where T3 : class, new() where T4 : class, new() where T5 : class, new() - { - return new Expressionable(); - } - public static Expressionable Create() where T : class, new() where T2 : class, new() where T3 : class, new() where T4 : class, new() where T5 : class, new() where T6 : class, new() - { - return new Expressionable(); - } - } -} diff --git a/src/Destiny.Core.Flow/ExpressionUtil/ExtensionMethods.cs b/src/Destiny.Core.Flow/ExpressionUtil/ExtensionMethods.cs deleted file mode 100644 index c64a998d..00000000 --- a/src/Destiny.Core.Flow/ExpressionUtil/ExtensionMethods.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Linq.Expressions; -using System.Reflection; - -namespace Destiny.Core.Flow.ExpressionUtil -{ - public static partial class Extensions - { - - private static readonly MethodInfo trimMethod = typeof(string).GetMethod("Trim", new Type[0]); - private static readonly MethodInfo toLowerMethod = typeof(string).GetMethod("ToLower", new Type[0]); - - /// - ///获取特定属性的成员表达式 - /// - /// - /// - /// - public static MemberExpression GetMemberExpression(this ParameterExpression param, string propertyName) - { - return GetMemberExpression((Expression)param, propertyName); - } - - private static MemberExpression GetMemberExpression(Expression param, string propertyName) - { - if (!propertyName.Contains(".")) - { - return Expression.PropertyOrField(param, propertyName); - } - - var index = propertyName.IndexOf("."); - var subParam = Expression.PropertyOrField(param, propertyName.Substring(0, index)); - return GetMemberExpression(subParam, propertyName.Substring(index + 1)); - } - - /// - /// 将string Trim和ToLower方法应用于ExpressionMember。 - /// - /// 将对其应用to方法的成员。 - /// - public static Expression TrimToLower(this MemberExpression member) - { - var trimMemberCall = Expression.Call(member, trimMethod); - return Expression.Call(trimMemberCall, toLowerMethod); - } - - /// - /// 将string Trim和ToLower方法应用于ExpressionMember。 - /// - /// 将应用到方法的常数. - /// - public static Expression TrimToLower(this ConstantExpression constant) - { - var trimMemberCall = Expression.Call(constant, trimMethod); - return Expression.Call(trimMemberCall, toLowerMethod); - } - - /// - /// 将“空检查”添加到表达式(在原始表达式之前)。 - /// - /// 将挂起空检查的表达式。 - /// 将被检查的成员。 - /// - public static Expression AddNullCheck(this Expression expression, MemberExpression member) - { - Expression memberIsNotNull = Expression.NotEqual(member, Expression.Constant(null)); - return Expression.AndAlso(memberIsNotNull, expression); - } - - - } -} diff --git a/src/Destiny.Core.Flow/ExpressionUtil/FilterBuilder.cs b/src/Destiny.Core.Flow/ExpressionUtil/FilterBuilder.cs deleted file mode 100644 index a69d57c4..00000000 --- a/src/Destiny.Core.Flow/ExpressionUtil/FilterBuilder.cs +++ /dev/null @@ -1,172 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Filter; -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; - -namespace Destiny.Core.Flow.ExpressionUtil -{ - /// - /// 过滤器构建器 - /// - public class FilterBuilder - { - - public static Func GetOperateExpression = (operate, member, expression) => - { - - switch (operate) - { - case FilterOperator.Equal: - return Expression.Equal(member, expression); - - case FilterOperator.NotEqual: - return Expression.NotEqual(member, expression); - - case FilterOperator.GreaterThan: - return Expression.GreaterThan(member, expression); - - case FilterOperator.GreaterThanOrEqual: - return Expression.GreaterThanOrEqual(member, expression); - - case FilterOperator.LessThan: - return Expression.LessThan(member, expression); - - case FilterOperator.LessThanOrEqual: - return Expression.LessThanOrEqual(member, expression); - - case FilterOperator.Like: - return Like(member, expression); - case FilterOperator.In: - return (member as MemberExpression).In(expression); - - case FilterOperator.NotIn: - return Expression.Not((member as MemberExpression).In(expression)); - default: - throw new AppException($"此{operate}过滤条件不存在!!!"); - - } - - - }; - - /// - /// 得到表达式目录树 - /// - /// 动态类型 - /// 查询过滤 - /// - public static Expression> GetExpression(QueryFilter queryFilter) - { - queryFilter.NotNull("queryFilter"); - ParameterExpression param = Expression.Parameter(typeof(T), "m"); - - Expression expression = GetExpressionBody(param, queryFilter); - return Expression.Lambda>(expression, param); - } - - private static Expression GetExpressionBody(ParameterExpression param, QueryFilter queryFilter) - { - - List expressions = new List(); - Expression expression = Expression.Constant(true); - if (queryFilter is null || (queryFilter?.Conditions.Count() == 0 && queryFilter?.Filters.Count() == 0)) //为空 - { - return expression; - } - foreach (var item in queryFilter.Conditions) - { - expressions.Add(GetExpressionBody(param, item)); - } - foreach (var item in queryFilter.Filters) - { - expressions.Add(GetExpressionBody(param, item)); - } - - if (queryFilter.FilterConnect == FilterConnect.And) - { - return expressions.Aggregate(Expression.AndAlso); - } - else - { - return expressions.Aggregate(Expression.OrElse); - } - } - - private static Expression GetExpressionBody(ParameterExpression param, FilterCondition filter) - { - - var lambda = GetPropertyLambdaExpression(param, filter); - var constant = ChangeTypeToExpression(filter, lambda.Body.Type); - - return GetOperateExpression(filter.Operator, lambda.Body, constant); - - } - - - /// - /// 得到值 - /// - /// - /// - /// - - private static Expression ChangeTypeToExpression(FilterCondition filter, Type conversionType) - { - var constant = Expression.Constant(true); - - if (filter.Operator == FilterOperator.In) - { - - return Expression.Constant(filter.Value); - } - - var value = filter.Value.AsTo(conversionType); - if (value == null) - { - return constant; - } - - return Expression.Constant(value, conversionType); - } - - - - private static Expression Like(Expression member, Expression expression) - { - if (expression.Type != typeof(string)) - { - throw new NotSupportedException("“Like”比较方式只支持字符串类型的数据"); - } - var functions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions))); - var like = typeof(DbFunctionsExtensions).GetMethod(nameof(DbFunctionsExtensions.Like), new Type[] { functions.Type, typeof(string), typeof(string) }); - var methodCallExpression = Expression.Call( - null, - like, - functions, - member, - expression); - return methodCallExpression; - } - - private static LambdaExpression GetPropertyLambdaExpression(ParameterExpression parameter, FilterCondition filter) - { - var type = parameter.Type; - var property = type.GetProperty(filter.Field, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance); - if (property == null) - { - throw new AppException($"没有得到{filter.Field}该名字!!!"); - } - MemberExpression propertyAccess = Expression.MakeMemberAccess(parameter, property); - return Expression.Lambda(propertyAccess, parameter); - } - } - - -} diff --git a/src/Destiny.Core.Flow/Extensions/AutoMapperExtensions.cs b/src/Destiny.Core.Flow/Extensions/AutoMapperExtensions.cs deleted file mode 100644 index 2f32441b..00000000 --- a/src/Destiny.Core.Flow/Extensions/AutoMapperExtensions.cs +++ /dev/null @@ -1,92 +0,0 @@ -using AutoMapper; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; - -namespace Destiny.Core.Flow.Extensions -{ - /// - /// AutoMapper扩展 - /// - public static partial class Extensions - { - private static IMapper _mapper = null; - - /// - /// - /// - - public static void SetMapper(IMapper mapper) - { - mapper.NotNull(nameof(mapper)); - _mapper = mapper; - } - - private static void CheckMapper() - { - - - _mapper.NotNull(nameof(_mapper)); - } - /// 将对象映射为指定类型 - /// - /// 要映射的目标类型 - /// 源对象 - /// 目标类型的对象 - public static TTarget MapTo(this object source) - { - CheckMapper(); - source.NotNull(nameof(source)); - - return _mapper.Map(source); - } - - /// - /// 使用源类型的对象更新目标类型的对象 - /// - /// 源类型 - /// 目标类型 - /// 源对象 - /// 待更新的目标对象 - /// 更新后的目标类型对象 - public static TTarget MapTo(this TSource source, TTarget target) - { - CheckMapper(); - source.NotNull(nameof(source)); - target.NotNull(nameof(target)); - return _mapper.Map(source, target); - } - - /// - /// 将数据源映射为指定的集合 - /// - /// 动态实体 - /// 数据源 - /// - - public static IEnumerable MapToList(this IEnumerable sources) - { - CheckMapper(); - sources.NotNull(nameof(sources)); - return _mapper.Map>(sources); - } - - - - - - /// - /// 将数据源映射为指定的集合 - /// - /// 数据源 - /// 成员展开 - public static IQueryable ToOutput(this IQueryable source, - params Expression>[] membersToExpand) - { - CheckMapper(); - return _mapper.ProjectTo(source, membersToExpand); - - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/BooleanWitnBoolExtensions.cs b/src/Destiny.Core.Flow/Extensions/BooleanWitnBoolExtensions.cs deleted file mode 100644 index 92e028e8..00000000 --- a/src/Destiny.Core.Flow/Extensions/BooleanWitnBoolExtensions.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - - /// - /// 可空Bool转成Bool - /// - /// - /// - public static bool NullableBoolToBool(bool? @bool) - { - return @bool == null || @bool == false ? false : true; - } - - /// - /// 是否等于true - /// - /// 要判断的值 - /// 如何等于True,返回True,否则False - public static bool IsTrue(this object value) - { - if (bool.TryParse(value.ToString(), out bool result) && result == true) - { - return true; - } - return false; - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/CheckExtensions.cs b/src/Destiny.Core.Flow/Extensions/CheckExtensions.cs deleted file mode 100644 index e539bc5e..00000000 --- a/src/Destiny.Core.Flow/Extensions/CheckExtensions.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - - -namespace Destiny.Core.Flow.Extensions -{ - /// - /// 检查扩展 - /// - public static partial class Extensions - { - /// - /// 验证指定值的断言是否为真,如果不为真,抛出指定消息的指定类型异常 - /// - /// 异常类型 - /// 要验证的断言。 - /// 异常消息。 - private static void Require(bool assertion, string message) - where TException : Exception - { - if (assertion) - { - return; - } - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentNullException(nameof(message)); - } - TException exception = (TException)Activator.CreateInstance(typeof(TException), message); - throw exception; - } - - /// - /// 验证指定值的断言表达式是否为真,不为值抛出异常 - /// - /// - /// 要验证的断言表达式 - /// 异常消息 - public static void Required(this T value, Func assertionFunc, string message) - { - if (assertionFunc == null) - { - throw new ArgumentNullException(nameof(assertionFunc)); - } - Require(assertionFunc(value), message); - } - - /// - /// 验证指定值的断言表达式是否为真,不为真抛出异常 - /// - /// 要判断的值的类型 - /// 抛出的异常类型 - /// 要判断的值 - /// 要验证的断言表达式 - /// 异常消息 - public static void Required(this T value, Func assertionFunc, string message) where TException : Exception - { - if (assertionFunc == null) - { - throw new ArgumentNullException(nameof(assertionFunc)); - } - Require(assertionFunc(value), message); - } - - /// - /// 检查参数不能为空引用,否则抛出异常。 - /// - /// - /// 参数名称 - /// - public static void NotNull(this T value, string paramName) - { - Require(value != null, $"参数“{paramName}”不能为空引用。"); - } - /// - /// 检查字符串不能为空引用或空字符串,否则抛出异常或异常。 - /// - /// - /// 参数名称。 - /// - /// - public static void NotNullOrEmpty(this string value, string paramName) - { - Require(!string.IsNullOrEmpty(value), $"参数“{paramName}”不能为空引用或空字符串。"); - } - - /// - /// 检查Guid值不能为Guid.Empty,否则抛出异常。 - /// - /// - /// 参数名称。 - /// - public static void NotEmpty(this Guid value, string paramName) - { - Require(value != Guid.Empty, $"参数“{paramName}”的值不能为Guid.Empty"); - } - - /// - /// 检查集合不能为空引用或空集合,否则抛出异常或异常。 - /// - /// 集合项的类型。 - /// - /// 参数名称。 - /// - /// - public static void NotNullOrEmpty(this IEnumerable collection, string paramName) - { - NotNull(collection, paramName); - Require(collection.Any(), $"参数“{paramName}”不能为空引用或空集合。"); - } - /// - /// 检查集合不能为空委托,否则抛出异常或异常。 - /// - /// 委托类型 - /// 委托类型 - /// 委托 - /// 参数名称。 - public static void NotNull(this Func func, string paramName) - { - NotNull(func, paramName); - Require(func.IsNotNull(), $"参数“{paramName}”不能为空委托。"); - } - /// - /// 检查指定路径的文件夹必须存在,否则抛出异常。 - /// - /// - /// 参数名称。 - /// - /// - public static void DirectoryExists(this string directory, string paramName = null) - { - NotNull(directory, paramName); - Require(Directory.Exists(directory), $"指定的目录路径“{directory}”不存在。"); - } - /// - /// 检查指定路径的文件必须存在,否则抛出异常。 - /// - /// - /// 参数名称。 - /// 当文件路径为null时 - /// 当文件路径不存在时 - public static void FileExists(this string filename, string paramName = null) - { - NotNull(filename, paramName); - Require(File.Exists(filename), $"指定的文件路径“{filename}”不存在"); - } - - /// - /// 检查指定路径的文件必须存在,否则抛出异常。 - /// - /// - /// 文件不存在消息。 - /// 参数名称。 - /// 当文件路径为null时 - /// 当文件路径不存在时 - public static void FileExists(this string filename,string fileNotExistsMsg, string paramName = null) - { - NotNull(filename, paramName); - Require(File.Exists(filename), fileNotExistsMsg); - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/ClaimsIdentityExtensions.cs b/src/Destiny.Core.Flow/Extensions/ClaimsIdentityExtensions.cs deleted file mode 100644 index 7dced220..00000000 --- a/src/Destiny.Core.Flow/Extensions/ClaimsIdentityExtensions.cs +++ /dev/null @@ -1,230 +0,0 @@ - -using System; -using System.Security.Claims; -using System.Security.Principal; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - /// - /// 得到用户ID - /// - /// - /// - /// - public static T GetUesrId(this IIdentity identity, string type = ClaimTypes.NameIdentifier) - { - - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return default(T); - } - string value = claimsIdentity.FindFirst(type)?.Value; - if (value == null) - { - return default(T); - } - return value.AsTo(); - } - /// - /// 得到用户ID - /// - /// - /// - /// - public static string GetUesrId(this IIdentity identity, string type = ClaimTypes.NameIdentifier) - { - - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return null; - } - string value = claimsIdentity.FindFirst(type)?.Value; - return value; - } - /// - /// 得到用户名 - /// - /// - /// - /// - public static string GetUserName(this IIdentity identity, string type = ClaimTypes.Name) - { - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return string.Empty; - } - return claimsIdentity.FindFirst(type)?.Value; - } - /// - /// 获取昵称 - /// - public static string GetNickName(this IIdentity identity) - { - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return string.Empty; - } - return claimsIdentity.FindFirst(ClaimTypes.GivenName)?.Value; - } - /// - /// 得到过期时间 - /// - /// - /// - /// - public static T GetExpiration(this IIdentity identity) - { - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return default(T); - } - string value = claimsIdentity.FindFirst(ClaimTypes.Expiration)?.Value; - if (value == null) - { - return default(T); - } - return value.AsTo(); - - } - /// - /// 得到角色 - /// - /// - /// - /// - /// - public static string[] GetRoles(this IIdentity identity, string type = ClaimTypes.Role) - { - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return new string[0]; - } - string value = claimsIdentity.FindFirst(type)?.Value; - return value != null ? value.Split() : new string[0]; - } - - /// - /// 获取登陆人Id - /// - /// - /// - public static string GetIdentityServer4SubjectId(this IIdentity identity) - { - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return null; - } - return ((identity as ClaimsIdentity).FindFirst("sub") ?? throw new InvalidOperationException("sub claim is missing")).Value; - } - /// - /// 获取登陆人Id泛型 - /// - /// - /// - /// - public static T GetIdentityServer4SubjectId(this IIdentity identity) - { - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return default(T); - } - var value = ((identity as ClaimsIdentity).FindFirst("sub") ?? throw new InvalidOperationException("sub claim is missing")).Value; - if (value == null) - { - return default(T); - } - return value.AsTo(); - } - /// - /// 获取租户Id - /// - /// - /// - /// - public static T GetTenantId(this IIdentity identity) - { - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return default(T); - } - var value = ((identity as ClaimsIdentity).FindFirst("TenantId") ?? throw new InvalidOperationException("TenantId claim is missing")).Value; - if (value == null) - { - return default(T); - } - return value.AsTo(); - } - /// - /// 获取租户Id - /// - /// - /// - /// - public static string GetTenantId(this IIdentity identity) - { - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return null; - } - var value = ((identity as ClaimsIdentity).FindFirst("TenantId") ?? throw new InvalidOperationException("TenantId claim is missing")).Value; - return value; - } - - /// - /// 查找对应类型 - /// - /// - /// - /// - /// - public static T FindFirst(this IIdentity identity,string type) - { - - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return default(T); - } - string value = claimsIdentity.FindFirst(type)?.Value; - if (value == null) - { - return default(T); - } - return value.AsTo(); - } - - - - - /// - /// 查找对应类型 - /// - /// - /// - /// - /// - public static string FindFirst(this IIdentity identity, string type) - { - - identity.NotNull(nameof(identity)); - if (!(identity is ClaimsIdentity claimsIdentity)) - { - return null; - } - string value = claimsIdentity.FindFirst(type)?.Value; - return value; - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/CollectionExtensions.cs b/src/Destiny.Core.Flow/Extensions/CollectionExtensions.cs deleted file mode 100644 index 0167a4d1..00000000 --- a/src/Destiny.Core.Flow/Extensions/CollectionExtensions.cs +++ /dev/null @@ -1,259 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Text; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - - /// - /// 根据Index下标移除 - /// - /// - /// - /// - /// - public static List Remove(this List list, int index) where T : class, new() - { - list.RemoveAt(index); - return list; - - } - /// - /// 移除 - /// - /// - /// - /// - public static List RemoveAll(this List list) where T : class, new() - { - - list.NotNullOrEmpty(nameof(list)); - for (int i = list.Count - 1; i >= 0; i--) - { - list.RemoveAt(i); - } - return list; - } - /// 串联对象数组的各个元素,其中在每个元素之间使用指定的分隔符。 - /// 一个由 的元素组成的字符串,这些元素以 字符串分隔。如果 为空数组,该方法将返回 - /// 要用作分隔符的字符串。只有在 具有多个元素时, 才包括在返回的字符串中。 - /// 一个集合,其中包含要连接的元素。 - /// - /// 为 null。 - public static string ToJoin(this IEnumerable values, string separator = ",") where TSource : IEnumerable - { - values = values.Where(o => !o.AsTo().IsNullOrEmpty()); - return string.Join(separator, values); - } - /// - /// 去重 - /// - /// 去重数据源 - /// - /// 数据源 - /// 键条件 - /// - public static IEnumerable DistinctBy(this IEnumerable source, - Func keySelector) - { - return source.GroupBy(keySelector).Select(gropby => gropby.First()); - } - /// - /// 去重 - /// - /// 去重数据源 - /// - /// 数据源 - /// 键条件 - /// 返回去重后集合数据 - public static IList ToDistinctBy(this IEnumerable source, - Func keySelector) - { - - return source.DistinctBy(keySelector).ToList(); - } - /// - /// 把集合转成SqlIn - /// - /// - /// 要转换的值 - /// 分割符 - /// 左边符 - /// 右边符 - /// 返回组装好的值,例如"'a','b'" - public static string ToSqlIn(this IEnumerable values, string separator = ",", string left = "'", string right = "'") - { - StringBuilder sb = new StringBuilder(); - var enumerable = values as TSource[] ?? values.ToArray(); - if (!enumerable.Any()) - { - return string.Empty; - } - - enumerable.ToList().ForEach(o => - { - - sb.AppendFormat("{0}{1}{2}{3}", left, o, right, separator); - - }); - string newStr = sb.ToString()?.TrimEnd($"{separator}".ToCharArray()); - return newStr; - } - /// - /// 根据集合字典转成字典 - /// - /// 键的类型 - /// 值的类型 - /// 数据源 - /// 返回所需的字典 - public static IDictionary AsDictionary(this IEnumerable> keyValuePairs) - { - keyValuePairs.NotNullOrEmpty(nameof(keyValuePairs)); - IDictionary dic = new Dictionary(); - - foreach (KeyValuePair keys in keyValuePairs) - { - dic.Add(keys.Key, keys.Value); - } - return dic; - } - public static IEnumerable WhereIf(this IEnumerable source, Func predicate, bool condition) where TSource : IEnumerable - { - source.NotNullOrEmpty(nameof(source)); - predicate.NotNull(nameof(predicate)); - return condition ? source.Where(predicate) : source; - } - /// - /// 给IEnumerable拓展ForEach方法 - /// - /// 模型类 - /// 数据源 - /// 方法 - public static void ForEach(this IEnumerable iEnumberable, Action func) - { - foreach (var item in iEnumberable) - { - func(item); - } - } - /// - /// 给IEnumerable拓展ForEach方法 - /// - /// 模型类 - /// 数据源 - /// 方法 - public static void ForEach(this IEnumerable iEnumberable, Action func) - { - - var array = iEnumberable.ToArray(); - for (int i = 0; i < array.Count(); i++) - { - func(array[i], i); - } - } - /// - /// 将列表转换为树形结构(泛型无限递归) - /// - /// 类型 - /// 数据 - /// 根条件 - /// 节点条件 - /// 添加子节点 - /// - /// - public static List ToTree(this List list, Func rootwhere, Func childswhere, Action> addchilds, T entity = default(T)) - { - var treelist = new List(); - //空树 - if (list == null || list.Count == 0) - { - return treelist; - } - if (!list.Any(e => rootwhere(entity, e))) - { - return treelist; - } - //树根 - if (list.Any(e => rootwhere(entity, e))) - { - treelist.AddRange(list.Where(e => rootwhere(entity, e))); - } - //树叶 - foreach (var item in treelist) - { - if (list.Any(e => childswhere(item, e))) - { - var nodedata = list.Where(e => childswhere(item, e)); - foreach (var child in nodedata) - { - //添加子集 - var data = list.ToTree(childswhere, childswhere, addchilds, child); - addchilds(child, data); - } - addchilds(item, nodedata); - } - } - return treelist; - } - /// - /// 把集合的元素转成指定的类型 - /// - /// 要转换的类型 - /// 转换的数据源 - /// 返回转换后的集合 - public static IEnumerable AsToAll(this IEnumerable source) - { - source.NotNull(nameof(source)); - IEnumerable enumerable = source as IEnumerable; - if (enumerable != null) - { - return enumerable; - } - return CastIterator(source); - } - private static IEnumerable CastIterator(IEnumerable source) - { - foreach (object current in source) - { - yield return (current.AsTo()); - } - yield break; - } - - - public static void AddRange(this ICollection initial, IEnumerable other) - { - if (other == null) - return; - - if (initial is List list) - { - list.AddRange(other); - return; - } - - foreach (var item in other) - { - initial.Add(item); - } - } - - public static bool AddIfNotContains([NotNull] this ICollection source, T item) - { - source.NotNull(nameof(source)); - - if (source.Contains(item)) - { - return false; - } - - source.Add(item); - return true; - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/ComparableExtensions.cs b/src/Destiny.Core.Flow/Extensions/ComparableExtensions.cs deleted file mode 100644 index 2cfd8f0b..00000000 --- a/src/Destiny.Core.Flow/Extensions/ComparableExtensions.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - - public static bool IsBetween(this T value, T minInclusiveValue, T maxInclusiveValue) where T : IComparable - { - return value.CompareTo(minInclusiveValue) >= 0 && value.CompareTo(maxInclusiveValue) <= 0; - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/ControllerExtensions.cs b/src/Destiny.Core.Flow/Extensions/ControllerExtensions.cs deleted file mode 100644 index ef4e44ee..00000000 --- a/src/Destiny.Core.Flow/Extensions/ControllerExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using System; -using System.Reflection; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - public static bool IsController(this Type type) - { - return IsController(type.GetTypeInfo()); - } - /// - /// 是否控制器 - /// - /// - /// - - public static bool IsController(this TypeInfo typeInfo) - { - - return typeInfo.IsClass && !typeInfo.IsAbstract && typeInfo.IsPublic && (typeInfo.IsDefined(typeof(ControllerAttribute)) && typeInfo.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)); - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/DateExtensions.cs b/src/Destiny.Core.Flow/Extensions/DateExtensions.cs deleted file mode 100644 index 6b7fc531..00000000 --- a/src/Destiny.Core.Flow/Extensions/DateExtensions.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - /// - /// returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates) - /// - /// - /// - public static string UnixTicks(this DateTime dt) - { - DateTime d1 = new DateTime(1970, 1, 1); - DateTime d2 = dt.ToUniversalTime(); - TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks); - return Math.Round(ts.TotalMilliseconds).ToString(); - } - /// - /// 转换为Bool类型 - /// - /// - /// - public static bool ObjToBool(this object thisValue) - { - bool reval = false; - if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval)) - { - return reval; - } - return reval; - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/DbContextExtensions.cs b/src/Destiny.Core.Flow/Extensions/DbContextExtensions.cs deleted file mode 100644 index 2020ee1f..00000000 --- a/src/Destiny.Core.Flow/Extensions/DbContextExtensions.cs +++ /dev/null @@ -1,35 +0,0 @@ - -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage; - -namespace Destiny.Core.Flow.Extensions -{ - /// - /// 上下文扩展 - /// - public static partial class Extensions - { - - /// - /// 当前上下文是否是关系型数据库 - /// - public static bool IsRelationalTransaction(this DbContext context) - { - return context.Database.GetService() is IRelationalTransactionManager; - } - - - /// - /// 检测关系型数据库是否存在 - /// - public static bool ExistsRelationalDatabase(this DbContext context) - { - RelationalDatabaseCreator creator = context.Database.GetService() as RelationalDatabaseCreator; - return creator != null && creator.Exists(); - } - - - - } -} diff --git a/src/Destiny.Core.Flow/Extensions/EntityEntryExtensions.cs b/src/Destiny.Core.Flow/Extensions/EntityEntryExtensions.cs deleted file mode 100644 index 0b64c69b..00000000 --- a/src/Destiny.Core.Flow/Extensions/EntityEntryExtensions.cs +++ /dev/null @@ -1,54 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Microsoft.EntityFrameworkCore.ChangeTracking; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Principal; - -namespace Destiny.Core.Flow.Extensions -{ - public static class EntityEntryExtensions - { - public static IEnumerable CheckInsert(this IEnumerable entitys, IPrincipal principal) - { - - foreach (var item in entitys) - { - - } - return entitys; - } - public static EntityEntry CheckInsert(this EntityEntry entity, IPrincipal principal) - { - - var entityPropertys = typeof(ICreationAudited<>).GetProperties(); - foreach (var item in entityPropertys) - { - var entityProperty = entity.GetType().GetProperties().Where(x => x.Name == item.Name).FirstOrDefault(); - if (entityProperty != null) - { - //entityProperty.SetValue(entityProperty.Name,principal.Identity.GetUesrId<>) - } - } - - - var creationAudited = entity.GetType().GetInterface(/*$"ICreationAudited`1"*/typeof(ICreationAudited<>).Name); - if (creationAudited == null) - { - return entity; - } - entity.CheckICreatedTime(principal); - return entity; - } - public static EntityEntry CheckICreatedTime(this EntityEntry entity, IPrincipal principal) - { - if (!(entity is ICreatedTime)) - { - return entity; - } - ICreatedTime entity1 = (ICreatedTime)entity; - entity1.CreatedTime = DateTime.Now; - return (EntityEntry)entity1; - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/EntityExtensions.cs b/src/Destiny.Core.Flow/Extensions/EntityExtensions.cs deleted file mode 100644 index 21b7b79b..00000000 --- a/src/Destiny.Core.Flow/Extensions/EntityExtensions.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Destiny.Core.Flow.Entity; -using System; -using System.Linq.Expressions; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - public static Expression> ToEqualityExpression(this TKey id) - where TEntity : IEntity - where TKey : IEquatable - { - var lambdaParam = Expression.Parameter(typeof(TEntity)); - - var lambdaBody = Expression.Equal( - Expression.PropertyOrField(lambdaParam, nameof(IEntity.Id)), - Expression.Constant(id, typeof(TKey)) - ); - - return Expression.Lambda>(lambdaBody, lambdaParam); - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/EnumExtensions.cs b/src/Destiny.Core.Flow/Extensions/EnumExtensions.cs deleted file mode 100644 index cc8c9d78..00000000 --- a/src/Destiny.Core.Flow/Extensions/EnumExtensions.cs +++ /dev/null @@ -1,38 +0,0 @@ - -using Destiny.Core.Flow.Attributes.Base; -using System; -using System.Linq; -using System.Reflection; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - /// - /// 转成显示名字 - /// - /// - /// - public static string ToDescription(this Enum value) - { - var type = value.GetType(); - MemberInfo member = type.GetMember(value.ToString()).FirstOrDefault(); - return member.ToDescription(); - } - - - /// - /// 得到枚举值指定特性下描述 - /// - /// 要得到的特性 - /// 枚举值 - /// - public static string ToDescription(this Enum value) - where TAttribute : AttributeBase - { - var type = value.GetType(); - MemberInfo member = type.GetMember(value.ToString()).FirstOrDefault(); - return member.ToDescription(); - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/ExpressionExtensions.cs b/src/Destiny.Core.Flow/Extensions/ExpressionExtensions.cs deleted file mode 100644 index e450e543..00000000 --- a/src/Destiny.Core.Flow/Extensions/ExpressionExtensions.cs +++ /dev/null @@ -1,434 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; - -namespace Destiny.Core.Flow.Extensions -{ - /// - /// 表达式目录树扩展 - /// - public static partial class Extensions - { - /// - /// Parser语法分析器 - /// - /// 参数表达式 - /// - /// - private static Expression Parser(ParameterExpression parameter, Expression expression) - { - if (expression == null) return null; - switch (expression.NodeType) - { - //一元运算符 - case ExpressionType.Negate: - case ExpressionType.NegateChecked: - case ExpressionType.Not: - case ExpressionType.Convert: - case ExpressionType.ConvertChecked: - case ExpressionType.ArrayLength: - case ExpressionType.Quote: - case ExpressionType.TypeAs: - { - var unary = expression as UnaryExpression; - var exp = Parser(parameter, unary.Operand); - return Expression.MakeUnary(expression.NodeType, exp, unary.Type, unary.Method); - } - //二元运算符 - case ExpressionType.Add: - case ExpressionType.AddChecked: - case ExpressionType.Subtract: - case ExpressionType.SubtractChecked: - case ExpressionType.Multiply: - case ExpressionType.MultiplyChecked: - case ExpressionType.Divide: - case ExpressionType.Modulo: - case ExpressionType.And: - case ExpressionType.AndAlso: - case ExpressionType.Or: - case ExpressionType.OrElse: - case ExpressionType.LessThan: - case ExpressionType.LessThanOrEqual: - case ExpressionType.GreaterThan: - case ExpressionType.GreaterThanOrEqual: - case ExpressionType.Equal: - case ExpressionType.NotEqual: - case ExpressionType.Coalesce: - case ExpressionType.ArrayIndex: - case ExpressionType.RightShift: - case ExpressionType.LeftShift: - case ExpressionType.ExclusiveOr: - { - var binary = expression as BinaryExpression; - var left = Parser(parameter, binary.Left); - var right = Parser(parameter, binary.Right); - var conversion = Parser(parameter, binary.Conversion); - if (binary.NodeType == ExpressionType.Coalesce && binary.Conversion != null) - { - return Expression.Coalesce(left, right, conversion as LambdaExpression); - } - else - { - return Expression.MakeBinary(expression.NodeType, left, right, binary.IsLiftedToNull, - binary.Method); - } - } - //其他 - case ExpressionType.Call: - { - var call = expression as MethodCallExpression; - List arguments = new List(); - foreach (var argument in call.Arguments) - { - arguments.Add(Parser(parameter, argument)); - } - var instance = Parser(parameter, call.Object); - call = Expression.Call(instance, call.Method, arguments); - return call; - } - case ExpressionType.Lambda: - { - var lambda = expression as LambdaExpression; - return Parser(parameter, lambda.Body); - } - case ExpressionType.MemberAccess: - { - var memberAccess = expression as MemberExpression; - if (memberAccess.Expression == null) - { - memberAccess = Expression.MakeMemberAccess(null, memberAccess.Member); - } - else - { - var exp = Parser(parameter, memberAccess.Expression); - var member = exp.Type.GetMember(memberAccess.Member.Name).FirstOrDefault(); - memberAccess = Expression.MakeMemberAccess(exp, member); - } - return memberAccess; - } - case ExpressionType.Parameter: - return parameter; - case ExpressionType.Constant: - return expression; - case ExpressionType.TypeIs: - { - var typeis = expression as TypeBinaryExpression; - var exp = Parser(parameter, typeis.Expression); - return Expression.TypeIs(exp, typeis.TypeOperand); - } - default: - throw new Exception($"Unhandled expression type:{expression.NodeType}"); - } - } - /// - /// 表达树类型转换 - /// - /// 转入类型 - /// 要转成的类型 - /// - /// - public static Expression> Cast( - this Expression> expression) where TInput : class, new() - where TToProperty : class, new() - - { - var p = Expression.Parameter(typeof(TToProperty), "p"); - var x = Parser(p, expression); - return Expression.Lambda>(x, p); - } - /// - /// 得到表达树对应属性的名字 - /// - /// - /// - /// - public static string GetPropertyName(this Expression> expr) - { - expr.NotNull(nameof(expr)); - var name = string.Empty; - var body = expr.Body; - if (body is UnaryExpression) - { - var unaryExpression = body as UnaryExpression; - var operand = unaryExpression.Operand; - var memberExpression = operand as MemberExpression; - name = memberExpression?.Member.Name; - - } - else if (body is MemberExpression) - { - var memberExpression = body as MemberExpression; - - name = memberExpression.Member.Name; - } - else if (body is ParameterExpression) - { - var parameterExpression = body; - - name = parameterExpression.Type.Name; - } - return name; - } - ///// - ///// And操作 - ///// - ///// - ///// - ///// - ///// - public static Expression> And(this Expression> expr1, Expression> expr2) - { - if (expr1 == null) - { - return expr2; - } - - var exp = ReplaceParameter(expr1, expr2, out ParameterExpression newParameter); - - if (exp.left is ConstantExpression constant && constant.Value.IsTrue()) - { - - return expr2; - - } - var body = Expression.AndAlso(exp.left, exp.right); - return Expression.Lambda>(body, newParameter); - - } - - /// - /// And操作 - /// - /// - /// - /// - /// - /// - public static Expression> AndIf(this Expression> expr1, Expression> expr2, bool isAnd) - { - if (expr1 == null) - { - return expr2; - } - if (!isAnd) - { - return expr1; - } - - return expr1.And(expr2); - } - /// - /// Or操作 - /// - /// - /// - /// - /// - public static Expression> Or(this Expression> expr1, Expression> expr2) - { - if (expr1 == null) - { - return expr2; - } - - var exp = ReplaceParameter(expr1, expr2, out ParameterExpression newParameter); - var body = Expression.Or(exp.left, exp.right); - return Expression.Lambda>(body, newParameter); - } - - /// - /// Or操作 - /// - /// - /// - /// - /// - /// - public static Expression> OrIf(this Expression> expr1, Expression> expr2, bool isAnd) - { - if (expr1 == null) - { - return expr2; - } - if (!isAnd) - { - return expr1; - } - - return expr1.Or(expr2); - } - /// - /// 替换参数 - /// - /// 动态实体 - /// - /// - /// - /// - public static (Expression left, Expression right) ReplaceParameter(this Expression> expr1, - Expression> expr2, out ParameterExpression newParameter) - { - - newParameter = Expression.Parameter(typeof(T), "c"); - NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter); - - var left = visitor.Replace(expr1.Body); - var right = visitor.Replace(expr2.Body); - return (left, right); - } - - /// - /// In操作 - /// - /// - /// - /// - public static Expression In(this MemberExpression member,Expression constant) - { - var constantExpression = constant as ConstantExpression; - if (constantExpression is null) - { - throw new ArgumentException("“In”操作值只支持ConstantExpression类型"); - } - - if (!(constantExpression.Value is IList) || !constantExpression.Value.GetType().IsGenericType) - { - throw new ArgumentException("“In”操作只支持列表作为参数。"); - } - - - var type = constantExpression.Value.GetType(); - var inInfo = type.GetMethod("Contains", new[] { type.GetGenericArguments()[0] }); - return GetExpressionHandlingNullables(member, constantExpression, type, inInfo) ?? Expression.Call(constantExpression, inInfo, member); - } - - private static Expression GetExpressionHandlingNullables(MemberExpression member, ConstantExpression constant1, Type type, - MethodInfo inInfo) - { - var listUnderlyingType = Nullable.GetUnderlyingType(type.GetGenericArguments()[0]); - var memberUnderlingType = Nullable.GetUnderlyingType(member.Type); - if (listUnderlyingType != null && memberUnderlingType == null) - { - return Expression.Call(constant1, inInfo, member.Expression); - } - - return null; - } - public static Dictionary ExpressionToDictValues(this Expression> expression) - { - var dictValues = new Dictionary(); - var expressionBody = expression.Body; - - while (expressionBody.NodeType == ExpressionType.Convert || expressionBody.NodeType == ExpressionType.ConvertChecked) - { - expressionBody = ((UnaryExpression)expressionBody).Operand; - } - var entityType = typeof(T); - - - var memberInitExpression = expressionBody as MemberInitExpression; - if (memberInitExpression == null) - { - throw new Exception("无效的转换。表达式必须是MemberInitExpression类型。"); - } - - foreach (var binding in memberInitExpression.Bindings) - { - var propertyName = binding.Member.Name; - - var memberAssignment = binding as MemberAssignment; - if (memberAssignment == null) - { - throw new Exception("无效的转换。表达式MemberBinding必须是MemberAssignment类型。"); - } - - var memberExpression = memberAssignment.Expression; - - // CHECK if the assignement has a property from the entity. - var hasEntityProperty = false; - memberExpression.Visit((ParameterExpression p) => - { - if (p.Type == entityType) - { - hasEntityProperty = true; - } - - return p; - }); - - if (!hasEntityProperty) - { - object value; - - var constantExpression = memberExpression as ConstantExpression; - - if (constantExpression != null) - { - value = constantExpression.Value; - - } - else - { - // - var lambda = Expression.Lambda(memberExpression, null); - value = lambda.Compile().DynamicInvoke(); - - - } - - dictValues.Add(propertyName, value); - } - else - { - - memberExpression = memberExpression.Visit((MemberExpression m) => - { - if (m.Expression.NodeType == ExpressionType.Constant) - { - var lambda = Expression.Lambda(m, null); - var value = lambda.Compile().DynamicInvoke(); - var c = Expression.Constant(value, m.Type); - return c; - } - - return m; - }); - - - - - dictValues.Add(propertyName, memberExpression); - } - } - - - return dictValues; - } - - - public static Expression AddNullCheck(this Expression expression, MemberExpression member) - { - Expression memberIsNotNull = Expression.NotEqual(member, Expression.Constant(null)); - return Expression.AndAlso(memberIsNotNull, expression); - } - } - public class NewExpressionVisitor : ExpressionVisitor - { - public ParameterExpression NewParameter { get; private set; } - public NewExpressionVisitor(ParameterExpression param) - { - this.NewParameter = param; - } - public Expression Replace(Expression exp) - { - return this.Visit(exp); - } - protected override Expression VisitParameter(ParameterExpression node) - { - return this.NewParameter; - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/ExpressionVisitorExtensions.cs b/src/Destiny.Core.Flow/Extensions/ExpressionVisitorExtensions.cs deleted file mode 100644 index 059611fe..00000000 --- a/src/Destiny.Core.Flow/Extensions/ExpressionVisitorExtensions.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Linq.Expressions; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - public static Expression Visit(this Expression expression, Func visitor) where TExpression : Expression - { - return ExpressionVisitor.Visit(expression, visitor); - } - public static TReturn Visit(this TReturn expression, Func visitor) - where TExpression : Expression - where TReturn : Expression - { - return (TReturn)ExpressionVisitor.Visit(expression, visitor); - } - public static Expression Visit(this Expression expression, Func visitor) - where TExpression : Expression - { - return ExpressionVisitor.Visit(expression, visitor); - } - } - public class ExpressionVisitor : ExpressionVisitor where TExpression : Expression - { - private readonly Func _visitor; - - public ExpressionVisitor(Func visitor) - { - _visitor = visitor; - } - public override Expression Visit(Expression expression) - { - if (expression is TExpression && _visitor != null) - expression = _visitor(expression as TExpression); - - return base.Visit(expression); - } - public static Expression Visit(Expression expression, Func visitor) - { - return new ExpressionVisitor(visitor).Visit(expression); - } - public static Expression Visit(Expression expression, Func visitor) - { - return (Expression)new ExpressionVisitor(visitor).Visit(expression); - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/FileExtensions.cs b/src/Destiny.Core.Flow/Extensions/FileExtensions.cs deleted file mode 100644 index d906cc0e..00000000 --- a/src/Destiny.Core.Flow/Extensions/FileExtensions.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.IO; - -namespace Destiny.Core.Flow.Extensions -{ - public static class FileExtensions - { - - /// - /// 判断是否文件 - /// - /// 要判断文件名 - /// 要判断文件后缀名 - /// 如何是返回ture,则返回false - public static bool IsFile(this string fileName,string fileExtension) - { - - if (Path.GetExtension(fileName).ToLower() == fileExtension) //txt文件 - { - - return true; - } - return false; - - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/GetIPExtension.cs b/src/Destiny.Core.Flow/Extensions/GetIPExtension.cs deleted file mode 100644 index e693a1b7..00000000 --- a/src/Destiny.Core.Flow/Extensions/GetIPExtension.cs +++ /dev/null @@ -1,45 +0,0 @@ -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using System.Net; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - - /// - /// 获取本机IP - /// - /// - public static List GetHostIP() - { - List Ip = new List(); - IPAddress[] p = Dns.GetHostEntry(Dns.GetHostName()).AddressList; - foreach (var i in p) - { - if (i.IsIPv6LinkLocal && i.IsIPv6Teredo)//如果是非IPv6地址,添加到list - { - Ip.Add(i.ToString());// - } - } - return Ip; - } - - /// - /// 获取请求端的Ip地址 - /// string ip1 = HttpContext.Request.Headers["X-Real-IP"]; - /// - /// - /// - public static string GetClientIP(this HttpContext context) - { - //HttpContext. - var ip = context.Request.Headers["X-Forwarded-For"].ToString(); - if (string.IsNullOrEmpty(ip)) - { - ip = context.Connection.RemoteIpAddress.ToString(); - } - return ip; - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/GuidExtensions.cs b/src/Destiny.Core.Flow/Extensions/GuidExtensions.cs deleted file mode 100644 index 98588bd4..00000000 --- a/src/Destiny.Core.Flow/Extensions/GuidExtensions.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Extensions -{ - - public static partial class Extensions - { - /// - /// 转为有序的GUID - /// - /// - public static Guid ToSequentialGuid(this Guid guid) - { - byte[] guidArray = Guid.NewGuid().ToByteArray(); - - DateTime baseDate = new DateTime(1900, 1, 1); - DateTime now = DateTime.Now; - - // Get the days and milliseconds which will be used to build the byte string - TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks); - TimeSpan msecs = now.TimeOfDay; - - // Convert to a byte array - // Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333 - byte[] daysArray = BitConverter.GetBytes(days.Days); - byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333)); - - // Reverse the bytes to match SQL Servers ordering - Array.Reverse(daysArray); - Array.Reverse(msecsArray); - - // Copy the bytes into the guid - Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2); - Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4); - - return new Guid(guidArray); - } - - /// - /// 判断是否为空或NULL - /// - /// 要判断GUID - /// 返回true/false - public static bool IsNullOrEmpty(this Guid guid) - { - return guid == Guid.Empty || guid == null; - } - - - /// - /// 判断是否为空或NULL - /// - /// 要判断GUID - /// 返回true/false - public static bool IsNullOrEmpty(this Guid? guid) - { - - - return !guid.HasValue || guid.Value == Guid.Empty; - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/HashExtensions.cs b/src/Destiny.Core.Flow/Extensions/HashExtensions.cs deleted file mode 100644 index 9b8e3577..00000000 --- a/src/Destiny.Core.Flow/Extensions/HashExtensions.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Security.Cryptography; -using System.Text; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - public static string Sha256(this string input) - { - if (input.IsMissing()) - { - return string.Empty; - } - - using (SHA256 sHA = SHA256.Create()) - { - byte[] bytes = Encoding.UTF8.GetBytes(input); - return Convert.ToBase64String(sHA.ComputeHash(bytes)); - } - } - - - /// - /// AES解密 - /// - /// 密文 - /// 密钥 - /// - public static string Decrypt(string decryptStr, string key) - { - byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); - byte[] toEncryptArray = Convert.FromBase64String(decryptStr); - RijndaelManaged rDel = new RijndaelManaged(); - rDel.Key = keyArray; - rDel.Mode = CipherMode.ECB; - rDel.Padding = PaddingMode.PKCS7; - ICryptoTransform cTransform = rDel.CreateDecryptor(); - byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); - return UTF8Encoding.UTF8.GetString(resultArray); - } - - - public static byte[] Sha256(this byte[] input) - { - if (input == null) - { - return null; - } - - using (SHA256 sHA = SHA256.Create()) - { - return sHA.ComputeHash(input); - } - } - public static string Sha512(this string input) - { - if (input.IsMissing()) - { - return string.Empty; - } - - using (SHA512 sHA = SHA512.Create()) - { - byte[] bytes = Encoding.UTF8.GetBytes(input); - return Convert.ToBase64String(sHA.ComputeHash(bytes)); - } - } - public static bool IsMissing(this string value) - { - return string.IsNullOrWhiteSpace(value); - } - public static bool IsPresent(this string value) - { - return !string.IsNullOrWhiteSpace(value); - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/IdentityResultExtensions.cs b/src/Destiny.Core.Flow/Extensions/IdentityResultExtensions.cs deleted file mode 100644 index b1d1a605..00000000 --- a/src/Destiny.Core.Flow/Extensions/IdentityResultExtensions.cs +++ /dev/null @@ -1,39 +0,0 @@ - - -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Ui; -using Microsoft.AspNetCore.Identity; -using System.Linq; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - public static OperationResponse ToOperationResponse(this IdentityResult identityResult) - { - - - return identityResult.Succeeded ? new OperationResponse(OperationResponseType.Success) : new OperationResponse(identityResult.Errors.Select(o => o.Description).ToJoin(), OperationResponseType.Error); - } - - /// - /// 转成操作返回类型 - /// - /// - /// 成功后提示的信息 - /// - public static OperationResponse ToOperationResponse(this IdentityResult identityResult,string successMessage) - { - - - return identityResult.Succeeded ? new OperationResponse(successMessage, OperationResponseType.Success) : new OperationResponse(identityResult.Errors.Select(o => o.Description).ToJoin(), OperationResponseType.Error); - } - - public static IdentityResult Failed(this IdentityResult identityResult, params string[] errors) - { - var identityErrors = identityResult.Errors; - identityErrors = identityErrors.Union(errors.Select(m => new IdentityError() { Description = m })); - return IdentityResult.Failed(identityErrors.ToArray()); - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/ObjectExtensions.cs b/src/Destiny.Core.Flow/Extensions/ObjectExtensions.cs deleted file mode 100644 index 48b21c71..00000000 --- a/src/Destiny.Core.Flow/Extensions/ObjectExtensions.cs +++ /dev/null @@ -1,140 +0,0 @@ -using MongoDB.Bson; -using System; -using System.Reflection; - -namespace Destiny.Core.Flow.Extensions -{ - /// - /// 对象扩展方法 - /// - public static partial class Extensions - { - /// - /// 把对象类型转换为指定类型 - /// - /// 要转换的值 - /// 要转换的类型 - /// - public static object AsTo(this object value, Type type) - { - if (value == null || value is DBNull) - { - return null; - } - - - //如果是Nullable类型 - if (type.IsNullableType()) - { - - type = type.GetUnNullableType(); - - } - - - //枚举类型 - if (type.IsEnum) - { - return Enum.Parse(type, value.ToString()); - } - - //if (type == typeof(Enum)) - //{ - // return Enum.Parse(type, value.ToString()); - //} - - - if (type == typeof(Guid)) - { - Guid.TryParse(value.ToString(), out var newGuid); - return newGuid; - } - - if (value?.GetType() == typeof(Guid)) - { - - return value.ToString(); - } - - if (type == typeof(ObjectId)) - { - - ObjectId.TryParse(value.ToString(),out var newValue); - return newValue; - } - - return Convert.ChangeType(value, type); - } - - /// - /// 把对象类型转换为指定类型 - /// - /// 动态类型 - /// 要转换对象 - /// 转化后的指定类型的对象 - - public static T AsTo(this object value) - { - - return (T)AsTo(value, typeof(T)); - } - - /// - /// 类型转换 - /// - /// - /// - /// - - public static T As(this object obj) where T : class - { - - return (T)obj; - } - /// - /// 是否为Null - /// - /// 判断的值 - /// true为null,false不为null - public static bool IsNull(this object value) - { - - return value == null ? true : false; - } - - public static bool IsNotNull(this object value) - { - - return !value.IsNull(); - } - - - - /// - /// 判断特性相应是否存在 - /// - /// 动态类型要判断的特性 - /// - /// - /// 如果存在还在返回true,否则返回false - public static bool HasAttribute(this MemberInfo memberInfo, bool inherit = true) where T : Attribute - { - return memberInfo.IsDefined(typeof(T), inherit); - } - - - /// - /// 检查对象是否为泛型列表。 - /// - /// 要转换对象 - /// 如果对象是泛型列表,则为true。 - public static bool IsGenericList(this object o) - { - var oType = o.GetType(); - return (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.List<>))); - } - - - - } -} diff --git a/src/Destiny.Core.Flow/Extensions/QueryableExtensions.cs b/src/Destiny.Core.Flow/Extensions/QueryableExtensions.cs deleted file mode 100644 index b40153fc..00000000 --- a/src/Destiny.Core.Flow/Extensions/QueryableExtensions.cs +++ /dev/null @@ -1,272 +0,0 @@ -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.ExpressionUtil; -using Destiny.Core.Flow.Filter; -using Destiny.Core.Flow.Filter.Abstract; -using Destiny.Core.Flow.Ui; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; -using Microsoft.EntityFrameworkCore.Query.Internal; -using Microsoft.EntityFrameworkCore.Query.SqlExpressions; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Dynamic.Core; -using System.Linq.Expressions; -using System.Reflection; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Extensions -{ - /// - /// Queryable扩展 - /// - public static partial class Extensions - { - - - /// - /// 把排序条件集合转成排序查询 - /// - /// 要排序实体 - /// 源 - /// 排序条件集合 - /// - public static IOrderedQueryable OrderBy(this IQueryable source, OrderCondition[] orderConditions) - { - IOrderedQueryable orderSource = null; - if (orderConditions == null || orderConditions.Length == 0) - { - orderSource = CollectionPropertySorter.OrderBy(source, "Id", SortDirection.Ascending); - } - - int count = 0; - - foreach (OrderCondition orderCondition in orderConditions) - { - orderSource = count == 0 - ? CollectionPropertySorter.OrderBy(source, orderCondition.SortField, orderCondition.SortDirection) - : CollectionPropertySorter.ThenBy(orderSource, orderCondition.SortField, orderCondition.SortDirection); - count++; - } - - return orderSource; - } - - - /// - /// 从集合中查询指定数据筛选的分页信息 - /// - /// 动态实体类型 - /// 数据源 - /// 查询条件表达式 - /// 分页参数 - /// - public static async Task> ToPageAsync(this IQueryable source, Expression> predicate, IPagedRequest request) - - { - request.NotNull(nameof(request)); - - var result = await source.WhereAsync(request.PageIndex, request.PageSize, predicate, request.OrderConditions); - var list = await result.data.ToArrayAsync(); - var total = result.totalNumber; - return new PageResult(list, total); - - } - - /// - /// 从集合中查询指定数据筛选的分页信息 - /// - /// 动态实体类型 - /// 要返回动态实体类型 - /// 数据源 - /// 查询条件表达式 - /// 分页参数 - /// 数据筛选表达式 - /// - public static async Task> ToPageAsync(this IQueryable source, Expression> predicate, IPagedRequest request, Expression> selector) - { - request.NotNull(nameof(request)); - selector.NotNull(nameof(selector)); - var result = await source.WhereAsync(request.PageIndex, request.PageSize, predicate, request.OrderConditions); - var list = await result.data.Select(selector).ToArrayAsync(); - var total = result.totalNumber; - return new PageResult(list, total); - } - - - - - - - /// - /// 从集合中查询指定数据筛选的分页信息 - /// - /// 动态实体类型 - /// 要返回动态实体类型 - /// 数据源 - /// 查询条件表达式 - /// 分页参数 - /// 数据筛选表达式 - /// - public static async Task> ToPageAsync(this IQueryable source, IPagedRequest request) - { - request.NotNull(nameof(request)); - - var result = await source.WhereAsync(request.PageIndex, request.PageSize, null, request.OrderConditions); - var list = await result.data.ToArrayAsync(); - var total = result.totalNumber; - return new PageResult(list, total); - } - - /// - /// 从集合中查询指定输出DTO的分页信息 - /// - /// 动态实体类型 - /// 输出DTO数据类型 - /// 数据源 - /// 查询条件表达式 - /// 分页参数 - /// - public static async Task> ToPageAsync(this IQueryable source, Expression> predicate, PageParameters pageParameters) - where TOutputDto : IOutputDto - { - pageParameters.NotNull(nameof(pageParameters)); - var result = await source.WhereAsync(pageParameters.PageIndex, pageParameters.PageSize, predicate, pageParameters.OrderConditions); - var list = await result.data.ToOutput().ToArrayAsync(); - var total = result.totalNumber; - return new PageResult(list, total); - } - - - - - - ///// - ///// 从集合中查询指定输出DTO的分页信息 - ///// - ///// 动态实体类型 - ///// 输出DTO数据类型 - ///// 数据源 - ///// 分页参数 - ///// - public static async Task> ToPageAsync(this IQueryable source, IPagedRequest request) - where TOutputDto : IOutputDto - { - request.NotNull(nameof(request)); - var isFiltered = request is IFilteredPagedRequest; - Expression> expression = null; - if (isFiltered) - { - var filter = (request as IFilteredPagedRequest).Filter; - expression = filter == null ? null : FilterBuilder.GetExpression(filter); - } - var result = await source.WhereAsync(request.PageIndex, request.PageSize, expression, request.OrderConditions); - var list = await result.data.ToOutput().ToArrayAsync(); - var total = result.totalNumber; - return new PageResult(list, total); - - } - - private static async Task<(IQueryable data, int totalNumber)> WhereAsync(this IQueryable source, int pageIndex, - int pageSize, Expression> predicate, OrderCondition[] orderConditions) - { - var total = !predicate.IsNull() ? await source.CountAsync(predicate) : await source.CountAsync(); - if (!predicate.IsNull()) - { - source = source.Where(predicate); - } - - source = source.OrderBy(orderConditions); - - return (!source.IsNull() ? source.Skip(pageSize * (pageIndex - 1)).Take(pageSize) : Enumerable.Empty().AsQueryable(), total); - } - - - - - /// - /// 动态查询 - /// - /// 要查询实体 - /// 数据 - /// - /// - public static IQueryable Filter(this IQueryable source, QueryFilter queryFilter) - { - - source.NotNull(nameof(source)); - queryFilter.NotNull(nameof(queryFilter)); - var expression = FilterBuilder.GetExpression(queryFilter); - return source.Where(expression); - } - - - /// - /// 从集合中查询指定数据筛选的树数据 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static async Task> ToTreeResultAsync(this IQueryable source, - Func rootwhere, - Func childswhere, Action> addchilds, TResult entity = default(TResult)) - { - - rootwhere.NotNull(nameof(rootwhere)); - childswhere.NotNull(nameof(childswhere)); - addchilds.NotNull(nameof(addchilds)); - var list = await source.ToOutput().ToListAsync(); - var treeData = list.ToTree(rootwhere, childswhere, addchilds, entity); - return new TreeResult - { - - ItemList = treeData, - }; - } - - public static string ToSql(this IQueryable query) - { - string relationalCommandCacheText = "_relationalCommandCache"; - string selectExpressionText = "_selectExpression"; - string querySqlGeneratorFactoryText = "_querySqlGeneratorFactory"; - string relationalQueryContextText = "_relationalQueryContext"; - - string cannotGetText = "Cannot get"; - - var enumerator = query.Provider.Execute(query.Expression).GetEnumerator(); - var relationalCommandCache = enumerator.Private(relationalCommandCacheText) as RelationalCommandCache; - var queryContext = enumerator.Private(relationalQueryContextText) ?? throw new InvalidOperationException($"{cannotGetText} {relationalQueryContextText}"); - var parameterValues = queryContext.ParameterValues; - - - if (relationalCommandCache != null) - { - var command = relationalCommandCache.GetRelationalCommand(parameterValues); - var parameterNames = new HashSet(command.Parameters.Select(p => p.InvariantName)); - - return $"{command.CommandText};{Environment.NewLine}"; - } - else - { - SelectExpression selectExpression = enumerator.Private(selectExpressionText) ?? throw new InvalidOperationException($"{cannotGetText} {selectExpressionText}"); - IQuerySqlGeneratorFactory factory = enumerator.Private(querySqlGeneratorFactoryText) ?? throw new InvalidOperationException($"{cannotGetText} {querySqlGeneratorFactoryText}"); - - var sqlGenerator = factory.Create(); - var command = sqlGenerator.GetCommand(selectExpression); - return $"{command.CommandText};{Environment.NewLine}"; - } - } - - private static readonly BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; - private static object Private(this object obj, string privateField) => obj?.GetType().GetField(privateField, bindingFlags)?.GetValue(obj); - private static T Private(this object obj, string privateField) => (T)obj?.GetType().GetField(privateField, bindingFlags)?.GetValue(obj); - } -} diff --git a/src/Destiny.Core.Flow/Extensions/SecurityExtension.cs b/src/Destiny.Core.Flow/Extensions/SecurityExtension.cs deleted file mode 100644 index a8d1ef4f..00000000 --- a/src/Destiny.Core.Flow/Extensions/SecurityExtension.cs +++ /dev/null @@ -1,279 +0,0 @@ -using System; -using System.Security.Cryptography; -using System.Text; - -namespace Destiny.Core.Flow.Extensions -{ - /// - /// 加密解密扩展 - /// - public static partial class Extensions - { - - #region 计算输入数据的MD5哈希值 - /// - ///获取32位md5加密 - /// - /// 待解密的字符串 - /// - public static string To32MD5(this 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.ToLower(); - } - } - - /// - ///获取16位md5加密 - /// - /// 待解密的字符串 - /// - public static string To16MD5(this 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.ToString().ToLower(); - } - } - - - /// - /// 生成MD5摘要 - /// - /// 元数据 - /// MD5摘要 - public static byte[] ToMD5(this byte[] value) => new MD5CryptoServiceProvider().ComputeHash(value); - #endregion - - #region 计算输入数据的SHA1哈希值 - /// - /// 使用加密服务提供程序(CSP)计算输入数据的SHA1哈希值 - /// - /// 要加密的字符串 - /// 经过SHA1加密后的字符串 - public static string ToSHA1(this string value) - { - SHA1 sha1 = new SHA1CryptoServiceProvider(); - byte[] bytes_sha1_in = Encoding.Default.GetBytes(value); - byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in); - return BitConverter.ToString(bytes_sha1_out); - } - #endregion - - #region 将使用BitConverter转化的字节数组重新转为字节数组 - /// - /// 将使用BitConverter转化的字节数组重新转为字节数组 - /// - /// 字符串,如:"96-F8-79-F4-18-37-D0-BF-B3-15-BE-A5-77-7F-7D-9E-59" - /// - public static byte[] StringToBit(this string bitstring) - { - string[] values = bitstring.Split('-'); - var inBytes = new byte[values.Length]; - for (var i = 0; i < values.Length; i++) - { - inBytes[i] = (byte)Convert.ToInt32(values[i], 16); - } - return inBytes; - } - #endregion - - #region 字符串的DES加密,解密 - /// - /// 对字符串进行DES加密 - /// - /// 字符串 - /// 密钥 - /// - public static string DESEncrypt(this string value, string vKey = "microsoft", string ivVal = "microsoft") - { - try - { - var des = new DESCryptoServiceProvider() - { - Key = Encoding.ASCII.GetBytes(vKey.To32MD5().Substring(0, 8)), - IV = Encoding.ASCII.GetBytes(ivVal.To32MD5().Substring(0, 8)) - }; - var inputByteArray = Encoding.Default.GetBytes(value); - var desencrypt = des.CreateEncryptor(); - byte[] result = desencrypt.TransformFinalBlock(inputByteArray, 0, inputByteArray.Length); - return BitConverter.ToString(result); - } - catch (Exception ex) - { - throw new Exception("加密错误", ex); - } - } - - /// - /// 对加密字符串进行DES解密 - /// - /// 被加密的字符串 - /// 密钥 - /// - public static string DESDecrypt(this string value, string vKey = "microsoft", string ivVal = "microsoft") - { - try - { - var des = new DESCryptoServiceProvider() - { - Key = Encoding.ASCII.GetBytes(vKey.To32MD5().Substring(0, 8)), - IV = Encoding.ASCII.GetBytes(ivVal.To32MD5().Substring(0, 8)) - }; - string[] values = value.Split('-'); - var inBytes = new byte[values.Length]; - for (var i = 0; i < values.Length; i++) - { - inBytes[i] = (byte)Convert.ToInt32(values[i], 16); - } - var desdecrypt = des.CreateDecryptor(); - byte[] outBlock = desdecrypt.TransformFinalBlock(inBytes, 0, inBytes.Length); - return Encoding.Default.GetString(outBlock); - } - catch (Exception ex) - { - throw new Exception("密码错误或其他错误", ex); - } - } - #endregion - - #region 随机生成MD5样式的密码,该密码不可逆 - /// - /// 超级警告.对字符串进行不可逆DES加密,该加密算法的结果和GUID一样,每一次都不相同.针对制作恶意加密程序可以使用,输出的密码长度为32位MD5码 - /// - /// 字符串 - /// - public static string IrreversibleEncrypt(this string value) - { - try - { - var key = Guid.NewGuid().ToString("N").ToUpper(); - var ivVal = Guid.NewGuid().ToString("N").ToUpper(); - Random rd = new Random(); - var keystart = rd.Next(key.Length - 8); - var ivstart = rd.Next(ivVal.Length - 8); - var des = new DESCryptoServiceProvider() - { - Key = Encoding.ASCII.GetBytes(key.Substring(keystart, 8)), - IV = Encoding.ASCII.GetBytes(ivVal.Substring(ivstart, 8)) - }; - var inputByteArray = Encoding.Default.GetBytes(value); - var desencrypt = des.CreateEncryptor(); - byte[] result = desencrypt.TransformFinalBlock(inputByteArray, 0, inputByteArray.Length); - return BitConverter.ToString(result).To16MD5().ToUpper(); - } - catch (Exception ex) - { - throw new Exception("加密错误", ex); - } - } - #endregion - - #region TripleDES 算法加密解密 - /// - /// 使用给定密钥字符串加密String - /// - /// 原始文字 - /// 密钥,默认:microsoft - /// 密文 - public static string TripleDESEncrypt(this string original, string key = "microsoft") => - Convert.ToBase64String(TripleDESEncrypt(Encoding.Default.GetBytes(original), Encoding.Default.GetBytes(key))); - - /// - /// 使用给定密钥字符串解密string - /// - /// 密文 - /// 密钥,默认:microsoft - /// 明文 - public static string TripleDESDecrypt(this string original, string key = "microsoft") => TripleDESDecrypt(original, Encoding.Default, key); - - /// - /// 使用给定密钥字符串解密string,返回指定编码方式明文 - /// - /// 密文 - /// 密钥,默认:microsoft - /// 字符编码方案 - /// 明文 - public static string TripleDESDecrypt(this string encrypted, Encoding encoding, string key = "microsoft") => - encoding.GetString(TripleDESDecrypt(Convert.FromBase64String(encrypted), Encoding.Default.GetBytes(key))); - - /// - /// 使用缺省密钥字符串解密 - /// - /// 密文 - /// 密钥,默认:microsoft - /// 明文 - public static byte[] TripleDESDecrypt(this byte[] encrypted, string key = "microsoft") => - TripleDESDecrypt(encrypted, Encoding.Default.GetBytes(key)); - - /// - /// 使用缺省密钥字符串加密 - /// - /// 明文 - /// 密匙,默认:microsoft - /// 密文 - public static byte[] TripleDESEncrypt(this byte[] original, string key = "microsoft") => - TripleDESEncrypt(original, Encoding.Default.GetBytes(key)); - - /// - /// 使用给定密钥加密 - /// - /// 明文 - /// 密钥 - /// 密文 - private static byte[] TripleDESEncrypt(byte[] original, byte[] key) - { - try - { - var des = new TripleDESCryptoServiceProvider - { - Key = key.ToMD5(), - Mode = CipherMode.ECB - }; - return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length); - } - catch (Exception ex) - { - throw ex; - } - } - - /// - /// 使用给定密钥解密数据 - /// - /// 密文 - /// 密钥 - /// 明文 - private static byte[] TripleDESDecrypt(byte[] encrypted, byte[] key) - { - try - { - var des = new TripleDESCryptoServiceProvider - { - Key = key.ToMD5(), - Mode = CipherMode.ECB - }; - return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length); - } - catch (Exception ex) - { - throw ex; - } - } - #endregion - } -} diff --git a/src/Destiny.Core.Flow/Extensions/ServiceCollectionExtension.cs b/src/Destiny.Core.Flow/Extensions/ServiceCollectionExtension.cs deleted file mode 100644 index 5b30a36e..00000000 --- a/src/Destiny.Core.Flow/Extensions/ServiceCollectionExtension.cs +++ /dev/null @@ -1,278 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Options; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.FileProviders; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Reflection; -using System.Text; - -namespace Destiny.Core.Flow.Extensions -{ - - public static partial class Extensions - { - - /// - /// 得到注入服务 - /// - /// - /// - /// - public static TType GetService(this IServiceCollection services) - { - - var provider = services.BuildServiceProvider(); - return provider.GetService(); - } - /// - /// 得到或添加Singleton服务 - /// - /// - /// - /// - /// - - - public static TServiceType GetOrAddSingletonService(this IServiceCollection services) - where TServiceType : class -where TImplementation : class, TServiceType - { - - - - var type = services.GetSingletonInstanceOrNull(); - if (type is null) - { - var provider = services.BuildServiceProvider(); - var serviceType = (TServiceType)provider.GetInstance(new ServiceDescriptor(typeof(TServiceType), typeof(TImplementation), ServiceLifetime.Singleton)); - return serviceType; - } - - return type; - } - - /// - /// 得到或添加Singleton服务 - /// - /// - - public static TServiceType GetOrAddSingletonService(this IServiceCollection services, Func factory) where TServiceType : class - { - - - var servciceType = services.GetSingletonInstanceOrNull(); - if (servciceType is null) - { - servciceType = factory(); - services.AddSingleton(servciceType); - } - - return servciceType; - } - - - /// - /// 得到操作设置 - /// - /// - /// - - public static AppOptionSettings GetAppSettings(this IServiceCollection services) - { - services.NotNull(nameof(services)); - return services.GetSingletonInstanceOrNull>()?.Value; - } - - public static IConfiguration GetConfiguration(this IServiceCollection services) - { - - return services.GetSingletonInstanceOrNull(); - } - - - - public static T GetSingletonInstanceOrNull(this IServiceCollection services) - { - var servictType = services - .FirstOrDefault(d => d.ServiceType == typeof(T) && d.Lifetime == ServiceLifetime.Singleton); - if (servictType?.ImplementationInstance != null) - { - return (T)servictType.ImplementationInstance; - } - - if (servictType?.ImplementationFactory != null) - { - return (T)servictType.ImplementationFactory.Invoke(null); - } - - return default(T); - } - - public static T GetSingletonInstance(this IServiceCollection services) - { - var service = services.GetSingletonInstanceOrNull(); - if (service == null) - { - throw new InvalidOperationException("找不到singleton服务: " + typeof(T).AssemblyQualifiedName); - } - - return service; - } - - public static IServiceProvider BuildServiceProviderFromFactory([NotNull] this IServiceCollection services) - { - - - foreach (var service in services) - { - var factoryInterface = service.ImplementationInstance?.GetType() - .GetTypeInfo() - .GetInterfaces() - .FirstOrDefault(i => i.GetTypeInfo().IsGenericType && - i.GetGenericTypeDefinition() == typeof(IServiceProviderFactory<>)); - - if (factoryInterface == null) - { - continue; - } - - var containerBuilderType = factoryInterface.GenericTypeArguments[0]; - return (IServiceProvider)typeof(Extensions) - .GetTypeInfo() - .GetMethods() - .Single(m => m.Name == nameof(BuildServiceProviderFromFactory) && m.IsGenericMethod) - .MakeGenericMethod(containerBuilderType) - .Invoke(null, new object[] { services, null }); - } - - return services.BuildServiceProvider(); - } - - - public static IServiceProvider ConfigureProvider(this IServiceCollection services, Action configure) - { - configure(services); - - return services.BuildServiceProviderFromFactory(); - } - - - - - - /// - /// 得到文件容器 - /// - /// 服务接口 - /// 文件名+后缀名 - /// 文件不存提示信息 - /// 返回文件中的文件 - public static string GetFileText(this IServiceCollection services, string fileName, string fileNotExistsMsg) - { - fileName.NotNullOrEmpty(nameof(fileName)); - var fileProvider = services.GetSingletonInstanceOrNull(); - - if (fileProvider == null) - { - - throw new AppException("IFileProvider接口不存在"); - } - - - var fileInfo = fileProvider.GetFileInfo(fileName); - if (!fileInfo.Exists) - { - if (!fileNotExistsMsg.IsNullOrEmpty()) - { - throw new AppException(fileNotExistsMsg); - } - - } - var text = ReadAllText(fileInfo); - if (text.IsNullOrEmpty()) - { - throw new AppException("文件内容不存在"); - } - return text; - } - - /// - /// 根据配置得到文件内容 - /// - /// 服务接口 - /// - /// 分区键 - /// 文件不存提示信息 - /// 返回文件中的文件 - public static string GetFileByConfiguration(this IServiceCollection services, string sectionKey, string fileNotExistsMsg) - { - - - sectionKey.NotNullOrEmpty(nameof(sectionKey)); - var configuration = services.GetService(); - var value = configuration?.GetSection(sectionKey)?.Value; - return services.GetFileText(value, fileNotExistsMsg); - - } - - /// - /// 读取全部文本 - /// - /// 文件信息接口 - /// - private static string ReadAllText(IFileInfo fileInfo) - { - byte[] buffer; - using var stream = fileInfo.CreateReadStream(); - buffer = new byte[stream.Length]; - stream.Read(buffer, 0, buffer.Length); - return Encoding.Default.GetString(buffer).Trim(); - } - - /// - /// 添加文件提供器 - /// - /// - /// - public static IServiceCollection AddFileProvider(this IServiceCollection services) - { - - var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath; //获取项目路径 - return services.AddSingleton(new PhysicalFileProvider(basePath)); - - } - - - /// - /// 添加延迟工厂 - /// - /// - /// - public static IServiceCollection AddLazyFactory(this IServiceCollection services) - { - return services.AddTransient(typeof(Lazy<>), typeof(LazyFactory<>)); - } - - - /// - /// 得到实例类型集合 - /// - /// - /// - /// - public static IEnumerable GetImplementationTypes(this IServiceCollection services) - { - - return services.Where(o => o.ServiceType == typeof(TServiceType) && o.Lifetime == ServiceLifetime.Singleton).Select(o=>o.ImplementationType); - } - - - - } -} diff --git a/src/Destiny.Core.Flow/Extensions/ServiceCollectionObjectsExtensions.cs b/src/Destiny.Core.Flow/Extensions/ServiceCollectionObjectsExtensions.cs deleted file mode 100644 index a254a798..00000000 --- a/src/Destiny.Core.Flow/Extensions/ServiceCollectionObjectsExtensions.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Exceptions; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Linq; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - public static ObjectAccessor TryAddObjectAccessor(this IServiceCollection services) - { - if (services.Any(s => s.ServiceType == typeof(ObjectAccessor))) - { - return services.GetSingletonInstance>(); - } - - return services.AddObjectAccessor(); - } - - public static ObjectAccessor AddObjectAccessor(this IServiceCollection services) - { - return services.AddObjectAccessor(new ObjectAccessor()); - } - - public static ObjectAccessor AddObjectAccessor(this IServiceCollection services, T obj) - { - return services.AddObjectAccessor(new ObjectAccessor(obj)); - } - - public static ObjectAccessor AddObjectAccessor(this IServiceCollection services, ObjectAccessor accessor) - { - if (services.Any(s => s.ServiceType == typeof(ObjectAccessor))) - { - throw new AppException("在类型“{typeof(T).AssemblyQualifiedName)}”之前注册了对象: "); - } - - //Add to the beginning for fast retrieve - services.Insert(0, ServiceDescriptor.Singleton(typeof(ObjectAccessor), accessor)); - services.Insert(0, ServiceDescriptor.Singleton(typeof(IObjectAccessor), accessor)); - - return accessor; - } - - public static T GetObjectOrNull(this IServiceCollection services) - where T : class - { - return services.GetSingletonInstanceOrNull>()?.Value; - } - - public static T GetObject(this IServiceCollection services) - where T : class - { - return services.GetObjectOrNull() ?? throw new AppException($"找不到的对象 {typeof(T).AssemblyQualifiedName} 服务。请确保您以前使用过AddObjectAccessor!"); - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/ServiceProviderExtensions.cs b/src/Destiny.Core.Flow/Extensions/ServiceProviderExtensions.cs deleted file mode 100644 index 7d9980a2..00000000 --- a/src/Destiny.Core.Flow/Extensions/ServiceProviderExtensions.cs +++ /dev/null @@ -1,234 +0,0 @@ -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Options; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.FileProviders; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; - -using System; -using System.Text; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Extensions -{ - public static partial class Extensions - { - - /// - /// 获取指定类型的日志对象 - /// - /// 非静态强类型 - /// 日志对象 - public static ILogger GetLogger(this IServiceProvider provider) - { - ILoggerFactory factory = provider.GetService(); - return factory.CreateLogger(); - } - /// - /// - /// - /// - /// - /// - /// - public static ILogger GetLogger(this IServiceProvider provider, Type type) - { - ILoggerFactory factory = provider.GetService(); - return factory.CreateLogger(type); - } - - - public static AppOptionSettings GetAppSettings(this IServiceProvider provider) - { - provider.NotNull(nameof(provider)); - return provider.GetService>()?.Value; - } - public static object GetInstance(this IServiceProvider provider, ServiceDescriptor descriptor) - { - if (descriptor.ImplementationInstance != null) - { - return descriptor.ImplementationInstance; - } - - if (descriptor.ImplementationType != null) - { - return provider.GetServiceOrCreateInstance(descriptor.ImplementationType); - } - - return descriptor.ImplementationFactory(provider); - } - - public static object GetServiceOrCreateInstance(this IServiceProvider provider, Type type) - { - return ActivatorUtilities.GetServiceOrCreateInstance(provider, type); - } - - public static object CreateInstance(this IServiceProvider provider, Type type, params object[] arguments) - { - return ActivatorUtilities.CreateInstance(provider, type, arguments); - } - - public static void GetService(this IServiceProvider provider, Action action) - { - action.NotNull(nameof(action)); - var t = provider.GetService(); - action(t); - } - - - /// - ///创建一个IServiceScope,其中包含一个IServiceProvider,用于从新创建的作用域解析依赖项,然后运行关联的回调。 - /// - public static void CreateScoped(this IServiceProvider provider, Action callback) - { - using var scope = provider.CreateScope(); - var service = scope.ServiceProvider.GetRequiredService(); - - callback(service, scope.ServiceProvider.GetRequiredService()); - if (service is IDisposable disposable) - { - disposable.Dispose(); - } - } - - /// - /// 创建一个IServiceScope,其中包含一个IServiceProvider,用于从新创建的作用域解析依赖项,然后运行关联的回调。 - /// - public static void CreateScoped(this IServiceProvider provider, Action callback) - { - using var scope = provider.CreateScope(); - var service = scope.ServiceProvider.GetRequiredService(); - callback(service); - if (service is IDisposable disposable) - { - disposable.Dispose(); - } - } - - /// - /// 创建一个IServiceScope,其中包含一个IServiceProvider,用于从新创建的作用域解析依赖项,然后运行关联的回调。 - /// - public static T CreateScoped(this IServiceProvider provider, Func callback) - { - using var scope = provider.CreateScope(); - var service = scope.ServiceProvider.GetRequiredService(); - return callback(service); - } - - public static void CreateScoped(this IServiceProvider provider, Action callback) - { - using var scope = provider.CreateScope(); - callback(scope.ServiceProvider); - } - - /// - /// 创建一个IServiceScope,其中包含一个IServiceProvider,用于从新创建的作用域解析依赖项,然后运行关联的回调。 - /// - public static async Task CreateScopedAsync(this IServiceProvider provider, Func callback) - { - using var scope = provider.GetRequiredService().CreateScope(); - var service = scope.ServiceProvider.GetRequiredService(); - - await callback(service, scope.ServiceProvider.GetRequiredService()); - if (service is IDisposable disposable) - { - disposable.Dispose(); - } - } - - /// - /// 创建一个IServiceScope,其中包含一个IServiceProvider,用于从新创建的作用域解析依赖项,然后运行关联的回调。 - /// - public static async Task CreateScopedAsync(this IServiceProvider provider, Func callback) - { - using var scope = provider.GetRequiredService().CreateScope(); - var service = scope.ServiceProvider.GetRequiredService(); - await callback(service); - if (service is IDisposable disposable) - { - disposable.Dispose(); - } - } - - /// - ///创建一个IServiceScope,其中包含一个IServiceProvider,用于从新创建的作用域解析依赖项,然后运行关联的回调。 - /// - public static async Task CreateScopedAsync(this IServiceProvider provider, Func> callback) - { - using var scope = provider.GetRequiredService().CreateScope(); - var service = scope.ServiceProvider.GetRequiredService(); - return await callback(service); - } - - public static async Task CreateScopedAsync(this IServiceProvider provider, Func> callback) - { - using var scope = provider.CreateScope(); - return await callback(scope.ServiceProvider); - } - - public static async Task CreateScopedAsync(this IServiceProvider provider, Func callback) - { - using var scope = provider.CreateScope(); - await callback(scope.ServiceProvider); - } - - - - /// - /// 根据配置得到文件内容 - /// - /// 服务接口 - /// - /// 分区键 - /// 文件不存提示信息 - /// 返回文件中的文件 - public static string GetFileByConfiguration(this IServiceProvider provider, string sectionKey, string fileNotExistsMsg) - { - - - sectionKey.NotNullOrEmpty(nameof(sectionKey)); - var configuration = provider.GetService(); - var value = configuration?.GetSection(sectionKey)?.Value; - return provider.GetFileText(value, fileNotExistsMsg); - - } - - /// - /// 得到文件容器 - /// - /// 服务接口 - /// 文件名+后缀名 - /// 文件不存提示信息 - /// 返回文件中的文件 - public static string GetFileText(this IServiceProvider provider, string fileName, string fileNotExistsMsg) - { - fileName.NotNullOrEmpty(nameof(fileName)); - var fileProvider = provider.GetService(); - fileProvider.NotNull(nameof(fileProvider)); - - - - var fileInfo = fileProvider.GetFileInfo(fileName); - - if (!fileInfo.Exists) - { - - if (!fileNotExistsMsg.IsNullOrEmpty()) - { - throw new AppException(fileNotExistsMsg); - } - - } - var text = ReadAllText(fileInfo); - if (text.IsNullOrEmpty()) - { - throw new AppException("文件内容不存在"); - } - return text; - } - - - - } -} diff --git a/src/Destiny.Core.Flow/Extensions/StringExtensions.cs b/src/Destiny.Core.Flow/Extensions/StringExtensions.cs deleted file mode 100644 index 1d7e304a..00000000 --- a/src/Destiny.Core.Flow/Extensions/StringExtensions.cs +++ /dev/null @@ -1,232 +0,0 @@ -using System; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; - -namespace Destiny.Core.Flow.Extensions -{ - /// - /// 字符串扩展 - /// - public static partial class Extensions - { - /// - /// 以指定字符串作为分隔符将指定字符串分隔成数组 - /// - /// 要分割的字符串 - /// 字符串类型的分隔符 - /// 是否移除数据中元素为空字符串的项 - /// 分割后的数据 - public static string[] Split(this string value, string strSplit, bool removeEmptyEntries = false) - { - - value.NotNullOrEmpty(nameof(value)); - strSplit.NotNullOrEmpty(nameof(strSplit)); - return value.Split(new[] { strSplit }, - removeEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None); - } - /// - /// 将字符中拼接 - /// - /// - /// - /// - /// - /// - public static string StrToJoin(this string value, string left, string right, string separator = ",") - { - value.NotNullOrEmpty(nameof(value)); - left.NotNullOrEmpty(nameof(left)); - right.NotNullOrEmpty(nameof(right)); - StringBuilder sb = new StringBuilder(); - if (!value.IsNullOrEmpty()) - { - foreach (var item in value.Split(separator)) - { - sb.AppendFormat("{0}{1}{2}{3}", left, item, right, separator); - } - } - return sb.ToString().TrimEnd(separator.ToCharArray()); - } - /// - ///把字符串转成SQL中IN - /// - /// 要转换的值 - /// 左边符 - /// 右边符 - /// in里面中间分割符:"'a','b'" - /// 值分割符如:"a,b,c,d" - /// 返回组装好的值,例如"'a','b'" - public static string ToSqlIn(this string value, string left = "'", string right = "'", string inMiddleSeparator = ",", - string valueSeparator = ",") - { - value.NotNullOrEmpty(nameof(value)); - - StringBuilder sb = new StringBuilder(); - if (!value.IsNullOrEmpty()) - { - foreach (var item in value.Split(valueSeparator)) - { - sb.AppendFormat("{0}{1}{2}{3}", left, item, right, inMiddleSeparator); - } - } - else - { - return value; - } - return sb.ToString().TrimEnd(inMiddleSeparator.ToCharArray()); - } - /// - /// 是否为空或者为null或者空格 - /// - /// 要判断的值 - /// 返回true/false - public static bool IsNullOrWhiteSpace(this string value) - { - return string.IsNullOrWhiteSpace(value); - } - /// - /// 是否为空或者为null - /// - /// 要判断的值 - /// 返回true/false - public static bool IsNullOrEmpty(this string value) - { - - return string.IsNullOrEmpty(value); - } - /// - /// 判断是否数字 - /// - /// - /// - public static bool IsInt(this string value) - { - return Regex.IsMatch(value, @"^[0-9]*$"); - } - /// - /// 在指定的输入字符串中搜索指定的正则表达式的第一个匹配项 - /// - /// 要搜索匹配项的字符串 - /// 要匹配的正则表达式模式 - /// 一个对象,包含有关匹配项的信息 - public static string Match(this string value, string pattern) - { - if (value == null) - { - return null; - } - return Regex.Match(value, pattern).Value; - } - public static string FormatWith(this string format, params object[] args) - { - format.NotNull("format"); - return string.Format(CultureInfo.CurrentCulture, format, args); - } - - public static string RemovePostFix(this string str, params string[] postFixes) - { - return str.RemovePostFix(StringComparison.Ordinal, postFixes); - } - - public static string RemovePostFix(this string str, StringComparison comparisonType, params string[] postFixes) - { - if (str.IsNullOrEmpty()) - { - return null; - } - - if (postFixes.Any()) - { - return str; - } - - foreach (var postFix in postFixes) - { - if (str.EndsWith(postFix, comparisonType)) - { - return str.Left(str.Length - postFix.Length); - } - } - - return str; - } - - public static string Left(this string str, int len) - { - str.NotNull(nameof(str)); - - if (str.Length < len) - { - throw new ArgumentException("len参数不能大于给定字符串的长度!"); - } - - return str.Substring(0, len); - } - - /// - /// 单词变成单数形式 - /// - /// - /// - public static string ToMakeSingle(string name) - { - Regex plural1 = new Regex("(?[^aeiou])ies$"); - Regex plural2 = new Regex("(?[aeiou]y)s$"); - Regex plural3 = new Regex("(?[sxzh])es$"); - Regex plural4 = new Regex("(?[^sxzhyu])s$"); - - if (plural1.IsMatch(name)) - return plural1.Replace(name, "${keep}y"); - else if (plural2.IsMatch(name)) - return plural2.Replace(name, "${keep}"); - else if (plural3.IsMatch(name)) - return plural3.Replace(name, "${keep}"); - else if (plural4.IsMatch(name)) - return plural4.Replace(name, "${keep}"); - - return name; - } - - /// - /// 单词变成复数形式 - /// - /// - /// - public static string ToMakePlural(string name) - { - Regex plural1 = new Regex("(?[^aeiou])y$"); - Regex plural2 = new Regex("(?[aeiou]y)$"); - Regex plural3 = new Regex("(?[sxzh])$"); - Regex plural4 = new Regex("(?[^sxzhy])$"); - - if (plural1.IsMatch(name)) - return plural1.Replace(name, "${keep}ies"); - else if (plural2.IsMatch(name)) - return plural2.Replace(name, "${keep}s"); - else if (plural3.IsMatch(name)) - return plural3.Replace(name, "${keep}es"); - else if (plural4.IsMatch(name)) - return plural4.Replace(name, "${keep}s"); - - return name; - } - - /// - /// 将驼峰字符串的第一个字符小写 - /// - public static string LowerFirstChar(this string str) - { - if (string.IsNullOrEmpty(str) || !char.IsUpper(str[0])) - { - return str; - } - if (str.Length == 1) - { - return char.ToLower(str[0]).ToString(); - } - return char.ToLower(str[0]) + str.Substring(1, str.Length - 1); - } - } -} diff --git a/src/Destiny.Core.Flow/Extensions/TypeExtensions.cs b/src/Destiny.Core.Flow/Extensions/TypeExtensions.cs deleted file mode 100644 index 8d38f160..00000000 --- a/src/Destiny.Core.Flow/Extensions/TypeExtensions.cs +++ /dev/null @@ -1,689 +0,0 @@ -using Destiny.Core.Flow.Attributes.Base; -using Destiny.Core.Flow.Entity; -using Destiny.Core.Flow.Exceptions; -using JetBrains.Annotations; -using Microsoft.Extensions.Internal; -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - - -namespace Destiny.Core.Flow.Extensions -{ - /// - /// Type类型扩展 - /// - public static partial class Extensions - { - - - - /// - /// 判断类型是否为Nullable类型 - /// - /// 要处理的类型 - /// 是返回True,不是返回False - public static bool IsNullableType(this Type type) - { - - return ((type != null) && type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof(Nullable<>)); - } - - - /// 判断当前类型是否可由指定类型派生 - /// - public static bool IsDeriveClassFrom(this Type type, bool canAbstract = false) - { - return IsDeriveClassFrom(type, typeof(TBaseType), canAbstract); - } - - /// - /// 判断当前类型是否可由指定类型派生 - /// - public static bool IsDeriveClassFrom(this Type type, Type baseType, bool canAbstract = false) - { - type.NotNull(nameof(type)); - baseType.NotNull(nameof(baseType)); - return type.IsClass && (!canAbstract && !type.IsAbstract) && type.IsBaseOn(baseType); - } - - - /// - /// 返回当前类型是否是指定基类的派生类 - /// - /// 要判断的基类型 - /// 当前类型 - /// - public static bool IsBaseOn(this Type type) - { - - return type.IsBaseOn(typeof(BaseType)); - } - - /// - /// 返回当前类型是否是指定基类的派生类 - /// - /// 当前类型 - /// 要判断的基类型 - /// - public static bool IsBaseOn(this Type type, Type baseType) - { - if (baseType.IsGenericTypeDefinition) - { - return baseType.IsGenericAssignableFrom(type); - } - return baseType.IsAssignableFrom(type); - } - - /// - /// 判断当前泛型类型是否可由指定类型的实例填充 - /// - /// 泛型类型 - /// 指定类型 - /// - public static bool IsGenericAssignableFrom(this Type genericType, Type type) - { - genericType.NotNull(nameof(genericType)); - type.NotNull(nameof(type)); - - if (!genericType.IsGenericType) - { - throw new ArgumentException("该功能只支持泛型类型的调用,非泛型类型可使用 IsAssignableFrom 方法。"); - } - - List allOthers = new List { type }; - if (genericType.IsInterface) - { - allOthers.AddRange(type.GetInterfaces()); - } - - foreach (var other in allOthers) - { - Type cur = other; - while (cur != null) - { - if (cur.IsGenericType) - { - cur = cur.GetGenericTypeDefinition(); - } - if (cur.IsSubclassOf(genericType) || cur == genericType) - { - return true; - } - cur = cur.BaseType; - } - } - return false; - } - - /// - /// 通过类型转换器获取Nullable类型的基础类型 - /// - /// 要处理的类型对象 - /// - public static Type GetUnNullableType(this Type type) - { - - if (IsNullableType(type)) - { - NullableConverter nullableConverter = new NullableConverter(type); - return nullableConverter.UnderlyingType; - } - return type; - } - - - - - /// - /// 判断是否IEnumerable、ICollection类型 - /// - /// - /// - public static bool IsEnumerable(this Type type) - { - return type.IsArray - || type.GetInterfaces().Any(x => x == typeof(ICollection) || x == typeof(IEnumerable)); - } - - /// - /// 从类型成员获取指定Attribute特性 - /// - /// Attribute特性类型 - /// 类型类型成员 - /// 是否从继承中查找 - /// 存在返回第一个,不存在返回null - public static T GetAttribute(this MemberInfo memberInfo, bool inherit = true) where T : Attribute - { - - var attributes = memberInfo.GetCustomAttributes(typeof(T), inherit); - return attributes.FirstOrDefault() as T; - } - - - - /// - /// 从类型成员获取指定Attribute特性 - /// - /// Attribute特性类型 - /// 类型类型成员 - /// 是否从继承中查找 - /// 存在返回第一个,不存在返回null - public static Type GetAttribute(this MemberInfo memberInfo, Type type, bool inherit = true) - { - var attributes = memberInfo.GetCustomAttributes(type, inherit); - return attributes.FirstOrDefault() as Type; - } - - /// - /// 判断是否实体类型 - /// - /// - /// - public static bool IsEntityType(this Type type) - { - type.NotNull(nameof(type)); - return typeof(IEntity<>).IsGenericAssignableFrom(type) && !type.IsAbstract && !type.IsInterface; - } - - - - public static string ToDescription(this MemberInfo member) - { - - DescriptionAttribute desc = member.GetCustomAttribute(); - if (!desc.IsNull()) - { - return desc.Description; - } - - //显示名 - DisplayNameAttribute display = member.GetCustomAttribute(); - if (!display.IsNull()) - { - return display.DisplayName; - } - return member.Name; - - } - - /// - /// 得到特性下描述 - /// - /// 动态特性 - /// - /// - public static string ToDescription(this MemberInfo member) - where TAttribute : AttributeBase - { - - var attributeBase = (AttributeBase)member.GetCustomAttribute(); - if (!attributeBase.IsNull()) - { - return attributeBase.Description(); - } - return member.Name; - - } - - - - - - /// - /// 基础类型 - /// - private static readonly Type[] _basicTypes = - { - typeof(bool), - - typeof(sbyte), - typeof(byte), - typeof(int), - typeof(uint), - typeof(short), - typeof(ushort), - typeof(long), - typeof(ulong), - typeof(float), - typeof(double), - typeof(decimal), - - typeof(Guid), - - typeof(DateTime),// IsPrimitive:False - typeof(TimeSpan),// IsPrimitive:False - typeof(DateTimeOffset), - - typeof(char), - typeof(string),// IsPrimitive:False - - //typeof(object),// IsPrimitive:False - }; - - /// - /// get TypeCode for specific type - /// - /// type - /// - public static TypeCode GetTypeCode(this Type type) => Type.GetTypeCode(type); - - /// - /// 是否是 ValueTuple - /// - /// type - /// - public static bool IsValueTuple([NotNull] this Type type) - => type.IsValueType && type.FullName?.StartsWith("System.ValueTuple`", StringComparison.Ordinal) == true; - - /// - /// GetDescription - /// - /// type - /// - public static string GetDescription([NotNull] this Type type) => - type.GetCustomAttribute()?.Description ?? string.Empty; - - /// - /// 判断是否基元类型,如果是可空类型会先获取里面的类型,如 int? 也是基元类型 - /// The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single. - /// - /// type - /// - public static bool IsPrimitiveType([NotNull] this Type type) - => (Nullable.GetUnderlyingType(type) ?? type).IsPrimitive; - - public static bool IsPrimitiveType() => typeof(T).IsPrimitiveType(); - - public static bool IsBasicType([NotNull] this Type type) => _basicTypes.Contains(type) || type.IsEnum; - - public static bool IsBasicType() => typeof(T).IsBasicType(); - - public static bool IsBasicType(this T value) => value.IsBasicType(); - - /// - /// Finds best constructor, least parameter - /// - /// type - /// - /// Matching constructor or default one - [CanBeNull] - public static ConstructorInfo GetConstructor(this Type type, params Type[] parameterTypes) - { - if (parameterTypes == null || parameterTypes.Length == 0) - return GetEmptyConstructor(type); - - var constructors = type.GetConstructors(); - - var ctors = constructors - .OrderBy(c => c.IsPublic ? 0 : (c.IsPrivate ? 2 : 1)) - .ThenBy(c => c.GetParameters().Length) - .ToArray(); - - foreach (var ctor in ctors) - { - var parameters = ctor.GetParameters(); - if (parameters.All(p => parameterTypes.Contains(p.ParameterType))) - { - return ctor; - } - } - - return null; - } - - [CanBeNull] - public static ConstructorInfo GetEmptyConstructor(this Type type) - { - var constructors = type.GetConstructors(); - - var ctor = constructors.OrderBy(c => c.IsPublic ? 0 : (c.IsPrivate ? 2 : 1)) - .ThenBy(c => c.GetParameters().Length).FirstOrDefault(); - - return ctor?.GetParameters().Length == 0 ? ctor : null; - } - - /// - /// Determines whether this type is assignable to . - /// - /// The type to test assignability to. - /// The type to test. - /// True if this type is assignable to references of type - /// ; otherwise, False. - public static bool IsAssignableTo(this Type @this) - { - if (@this == null) - { - throw new ArgumentNullException(nameof(@this)); - } - - return typeof(T).IsAssignableFrom(@this); - } - - /// - /// Finds a constructor with the matching type parameters. - /// - /// The type being tested. - /// The types of the contractor to find. - /// The is a match is found; otherwise, null. - [CanBeNull] - public static ConstructorInfo GetMatchingConstructor(this Type type, Type[] constructorParameterTypes) - { - if (constructorParameterTypes == null || constructorParameterTypes.Length == 0) - return GetEmptyConstructor(type); - - return type.GetConstructors().FirstOrDefault(c => c.GetParameters().Select(p => p.ParameterType).SequenceEqual(constructorParameterTypes)); - } - - /// - /// Get ImplementedInterfaces - /// - /// type - /// 当前类型实现的接口的集合。 - public static IEnumerable GetImplementedInterfaces([NotNull] this Type type) - { - return type.GetTypeInfo().ImplementedInterfaces; - } - - public static bool IsNonAbstractClass(this Type type, bool publicOnly) - { - var typeInfo = type.GetTypeInfo(); - - if (typeInfo.IsSpecialName) - { - return false; - } - - if (typeInfo.IsClass && !typeInfo.IsAbstract) - { - if (typeInfo.IsDefined(typeof(CompilerGeneratedAttribute), inherit: true)) - { - return false; - } - - if (publicOnly) - { - return typeInfo.IsPublic || typeInfo.IsNestedPublic; - } - - return true; - } - - return false; - } - - public static IEnumerable GetBaseTypes(this Type type) - { - var typeInfo = type.GetTypeInfo(); - - foreach (var implementedInterface in typeInfo.ImplementedInterfaces) - { - yield return implementedInterface; - } - - var baseType = typeInfo.BaseType; - - while (baseType != null) - { - var baseTypeInfo = baseType.GetTypeInfo(); - - yield return baseType; - - baseType = baseTypeInfo.BaseType; - } - } - - public static bool IsInNamespace(this Type type, string @namespace) - { - var typeNamespace = type.Namespace ?? string.Empty; - - if (@namespace.Length > typeNamespace.Length) - { - return false; - } - - var typeSubNamespace = typeNamespace.Substring(0, @namespace.Length); - - if (typeSubNamespace.Equals(@namespace, StringComparison.Ordinal)) - { - if (typeNamespace.Length == @namespace.Length) - { - //exactly the same - return true; - } - - //is a subnamespace? - return typeNamespace[@namespace.Length] == '.'; - } - - return false; - } - - public static bool IsInExactNamespace(this Type type, string @namespace) - { - return string.Equals(type.Namespace, @namespace, StringComparison.Ordinal); - } - - public static bool HasAttribute(this Type type, Type attributeType) - { - return type.GetTypeInfo().IsDefined(attributeType, inherit: true); - } - - public static bool HasAttribute(this Type type, Func predicate) where T : Attribute - { - return type.GetTypeInfo().GetCustomAttributes(inherit: true).Any(predicate); - } - - public static bool IsAssignableTo(this Type type, Type otherType) - { - var typeInfo = type.GetTypeInfo(); - var otherTypeInfo = otherType.GetTypeInfo(); - - if (otherTypeInfo.IsGenericTypeDefinition) - { - return typeInfo.IsAssignableToGenericTypeDefinition(otherTypeInfo); - } - - return otherTypeInfo.IsAssignableFrom(typeInfo); - } - - private static bool IsAssignableToGenericTypeDefinition(this TypeInfo typeInfo, TypeInfo genericTypeInfo) - { - var interfaceTypes = typeInfo.ImplementedInterfaces.Select(t => t.GetTypeInfo()); - - foreach (var interfaceType in interfaceTypes) - { - if (interfaceType.IsGenericType) - { - var typeDefinitionTypeInfo = interfaceType - .GetGenericTypeDefinition() - .GetTypeInfo(); - - if (typeDefinitionTypeInfo.Equals(genericTypeInfo)) - { - return true; - } - } - } - - if (typeInfo.IsGenericType) - { - var typeDefinitionTypeInfo = typeInfo - .GetGenericTypeDefinition() - .GetTypeInfo(); - - if (typeDefinitionTypeInfo.Equals(genericTypeInfo)) - { - return true; - } - } - - var baseTypeInfo = typeInfo.BaseType?.GetTypeInfo(); - - if (baseTypeInfo is null) - { - return false; - } - - return baseTypeInfo.IsAssignableToGenericTypeDefinition(genericTypeInfo); - } - - - private static IEnumerable GetImplementedInterfacesToMap(TypeInfo typeInfo) - { - if (!typeInfo.IsGenericType) - { - return typeInfo.ImplementedInterfaces; - } - - if (!typeInfo.IsGenericTypeDefinition) - { - return typeInfo.ImplementedInterfaces; - } - - return FilterMatchingGenericInterfaces(typeInfo); - } - - private static IEnumerable FilterMatchingGenericInterfaces(TypeInfo typeInfo) - { - var genericTypeParameters = typeInfo.GenericTypeParameters; - - foreach (var current in typeInfo.ImplementedInterfaces) - { - var currentTypeInfo = current.GetTypeInfo(); - - if (currentTypeInfo.IsGenericType && currentTypeInfo.ContainsGenericParameters - && GenericParametersMatch(genericTypeParameters, currentTypeInfo.GenericTypeArguments)) - { - yield return currentTypeInfo.GetGenericTypeDefinition(); - } - } - } - - private static bool GenericParametersMatch(IReadOnlyList parameters, IReadOnlyList interfaceArguments) - { - if (parameters.Count != interfaceArguments.Count) - { - return false; - } - - for (var i = 0; i < parameters.Count; i++) - { - if (parameters[i] != interfaceArguments[i]) - { - return false; - } - } - - return true; - } - - public static string ToFriendlyName(this Type type) - { - return TypeNameHelper.GetTypeDisplayName(type, includeGenericParameterNames: true); - } - - public static bool IsOpenGeneric(this Type type) - { - return type.GetTypeInfo().IsGenericTypeDefinition; - } - - public static bool HasMatchingGenericArity(this Type interfaceType, TypeInfo typeInfo) - { - if (typeInfo.IsGenericType) - { - var interfaceTypeInfo = interfaceType.GetTypeInfo(); - - if (interfaceTypeInfo.IsGenericType) - { - var argumentCount = interfaceType.GenericTypeArguments.Length; - var parameterCount = typeInfo.GenericTypeParameters.Length; - - return argumentCount == parameterCount; - } - - return false; - } - - return true; - } - - public static Type GetRegistrationType(this Type interfaceType, TypeInfo typeInfo) - { - if (typeInfo.IsGenericTypeDefinition) - { - var interfaceTypeInfo = interfaceType.GetTypeInfo(); - - if (interfaceTypeInfo.IsGenericType) - { - return interfaceType.GetGenericTypeDefinition(); - } - } - - return interfaceType; - } - - /// - /// 是原始的扩展包括空 - /// - /// - /// - /// - public static bool IsPrimitiveExtendedIncludingNullable(this Type type, bool includeEnums = false) - { - if (IsPrimitiveExtended(type, includeEnums)) return true; - - if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) - return IsPrimitiveExtended(type.GenericTypeArguments[0], includeEnums); - - return false; - } - - private static bool IsPrimitiveExtended(Type type, bool includeEnums) - { - if (type.GetTypeInfo().IsPrimitive) return true; - - if (includeEnums && type.GetTypeInfo().IsEnum) return true; - - return type == typeof(string) || - type == typeof(decimal) || - type == typeof(DateTime) || - type == typeof(DateTimeOffset) || - type == typeof(TimeSpan) || - type == typeof(Guid); - } - - - public static Expression GetKeySelector(this Type type, string keyName) - { - - string key = $"{type.FullName}.{keyName}"; - //if (Cache.ContainsKey(key)) - //{ - // return Cache[key]; - //} - ParameterExpression param = Expression.Parameter(type); - string[] propertyNames = keyName.Split("."); - Expression propertyAccess = param; - - foreach (var propertyName in propertyNames) - { - PropertyInfo property = type.GetProperty(propertyName); - if (property.IsNull()) - { - throw new AppException($"查找类似 指定对象中不存在名称为“{propertyName}”的属性"); - } - type = property.PropertyType; - propertyAccess = Expression.Property(propertyAccess, propertyName); - } - - return propertyAccess; - } - - } -} diff --git a/src/Destiny.Core.Flow/Filter/Abstract/IFilterReauest.cs b/src/Destiny.Core.Flow/Filter/Abstract/IFilterReauest.cs deleted file mode 100644 index 81ea57f0..00000000 --- a/src/Destiny.Core.Flow/Filter/Abstract/IFilterReauest.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Filter.Abstract -{ - - /// - /// 查询排序请求 - /// - - public interface IQueryWith0rderReauest : IFilteredRequest, IOrderRequest - { - - } -} diff --git a/src/Destiny.Core.Flow/Filter/Abstract/IFilteredPagedRequest.cs b/src/Destiny.Core.Flow/Filter/Abstract/IFilteredPagedRequest.cs deleted file mode 100644 index 4ac56b8d..00000000 --- a/src/Destiny.Core.Flow/Filter/Abstract/IFilteredPagedRequest.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Destiny.Core.Flow.Filter.Abstract -{ - /// - /// 过滤查询分页请求 - /// - public interface IFilteredPagedRequest : IPagedRequest - { - - /// - /// 过滤查询 - /// - QueryFilter Filter { get; set; } - } - - - /// - /// 过滤查询请求 - /// - public interface IFilteredRequest - { - - /// - /// 过滤查询 - /// - QueryFilter Filter { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Filter/Abstract/IOrderRequest.cs b/src/Destiny.Core.Flow/Filter/Abstract/IOrderRequest.cs deleted file mode 100644 index 2da927ed..00000000 --- a/src/Destiny.Core.Flow/Filter/Abstract/IOrderRequest.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Filter.Abstract -{ - /// - /// 排序接口 - /// - public interface IOrderRequest - { - /// - /// 排序条件集合 - /// - OrderCondition[] OrderConditions { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Filter/Abstract/IPagedRequest.cs b/src/Destiny.Core.Flow/Filter/Abstract/IPagedRequest.cs deleted file mode 100644 index 66b319ed..00000000 --- a/src/Destiny.Core.Flow/Filter/Abstract/IPagedRequest.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace Destiny.Core.Flow.Filter.Abstract -{ - /// - /// 分页请求口 - /// - public interface IPagedRequest: IOrderRequest - { - - /// - /// 当前页数 - /// - int PageIndex { get; set; } - - /// - /// 分页大小 - /// - int PageSize { get; set; } - - - } -} diff --git a/src/Destiny.Core.Flow/Filter/Abstract/IPagedResult.cs b/src/Destiny.Core.Flow/Filter/Abstract/IPagedResult.cs deleted file mode 100644 index d3371fc7..00000000 --- a/src/Destiny.Core.Flow/Filter/Abstract/IPagedResult.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Ui; - -namespace Destiny.Core.Flow.Filter.Abstract -{ - public interface IPagedResult : IResultBase, IListResult, IHasResultType - { - - - int Total { get; } - } -} diff --git a/src/Destiny.Core.Flow/Filter/CollectionPropertySorter.cs b/src/Destiny.Core.Flow/Filter/CollectionPropertySorter.cs deleted file mode 100644 index 62c4c72f..00000000 --- a/src/Destiny.Core.Flow/Filter/CollectionPropertySorter.cs +++ /dev/null @@ -1,77 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Extensions; -using System; -using System.Collections.Concurrent; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; - -namespace Destiny.Core.Flow.Filter -{ - public static class CollectionPropertySorter - { - private static readonly ConcurrentDictionary Cache = new ConcurrentDictionary(); - - /// - /// 按指定的属性名称对序列进行排序 - /// - /// IQueryable{T}序列 - /// 属性名称 - /// 排序方向 - /// - public static IOrderedQueryable OrderBy(IQueryable source, string propertyName, SortDirection sortDirection) - { - propertyName.NotNullOrEmpty("propertyName"); - dynamic keySelector = GetKeySelector(propertyName); - return sortDirection == SortDirection.Ascending - ? Queryable.OrderBy(source, keySelector) - : Queryable.OrderByDescending(source, keySelector); - } - - - /// - /// 按指定的属性名称对序列进行排序 - /// - /// IOrderedQueryable{T}序列 - /// 属性名称 - /// 排序方向 - /// - public static IOrderedQueryable ThenBy(IOrderedQueryable source, string propertyName, SortDirection sortDirection) - { - propertyName.NotNullOrEmpty("propertyName"); - dynamic keySelector = GetKeySelector(propertyName); - return sortDirection == SortDirection.Ascending - ? Queryable.ThenBy(source, keySelector) - : Queryable.ThenByDescending(source, keySelector); - } - - - - private static LambdaExpression GetKeySelector(string keyName) - { - Type type = typeof(T); - string key = $"{type.FullName}.{keyName}"; - if (Cache.ContainsKey(key)) - { - return Cache[key]; - } - ParameterExpression param = Expression.Parameter(type); - string[] propertyNames = keyName.Split("."); - Expression propertyAccess = param; - - foreach (var propertyName in propertyNames) - { - PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance); - if (property.IsNull()) - { - throw new Exception($"查找类似 指定对象中不存在名称为“{propertyName}”的属性"); - } - type = property.PropertyType; - propertyAccess = Expression.Property(propertyAccess, property); - } - LambdaExpression keySelector = Expression.Lambda(propertyAccess, param); - Cache[key] = keySelector; - return keySelector; - } - } -} diff --git a/src/Destiny.Core.Flow/Filter/FilterCodeAttribute.cs b/src/Destiny.Core.Flow/Filter/FilterCodeAttribute.cs deleted file mode 100644 index f63f203b..00000000 --- a/src/Destiny.Core.Flow/Filter/FilterCodeAttribute.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Destiny.Core.Flow.Attributes.Base; -using System; - -namespace Destiny.Core.Flow.Filter -{ - [AttributeUsage(AttributeTargets.Field)] - public class FilterCodeAttribute : AttributeBase - { - public FilterCodeAttribute(string code) - { - Code = code; - - - } - public string Code { get; set; } - - public override string Description() - { - - return this.Code; - } - } -} diff --git a/src/Destiny.Core.Flow/Filter/FilterCondition.cs b/src/Destiny.Core.Flow/Filter/FilterCondition.cs deleted file mode 100644 index 36f6d5f7..00000000 --- a/src/Destiny.Core.Flow/Filter/FilterCondition.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Destiny.Core.Flow.Enums; - -namespace Destiny.Core.Flow.Filter -{ - public class FilterCondition - { - - public FilterCondition() - { - - } - - public FilterCondition(string field, object value) : this(field, value, FilterOperator.Equal) - { - - } - public FilterCondition(string field, object value, FilterOperator @operator) - { - this.Field = field; - this.Value = value; - this.Operator = @operator; - } - - /// - /// 字段名称 - /// - public string Field { get; set; } - /// - /// 值 - /// - public object Value { get; set; } - - /// - /// 过滤操作器 - /// - public FilterOperator Operator { get; set; } = FilterOperator.Equal; - } -} diff --git a/src/Destiny.Core.Flow/Filter/IResultData.cs b/src/Destiny.Core.Flow/Filter/IResultData.cs deleted file mode 100644 index e80f3079..00000000 --- a/src/Destiny.Core.Flow/Filter/IResultData.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Destiny.Core.Flow.Filter -{ - public interface IResultData - { - TData Data { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Filter/OrderCondition.cs b/src/Destiny.Core.Flow/Filter/OrderCondition.cs deleted file mode 100644 index d37c235b..00000000 --- a/src/Destiny.Core.Flow/Filter/OrderCondition.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Extensions; -using System; -using System.Linq.Expressions; - -namespace Destiny.Core.Flow.Filter -{ - public class OrderCondition - { - // - /// 初始化一个类型的新实例 - /// - public OrderCondition() : this(null) - { } - - /// - /// 构造一个指定字段名称的升序排序的排序条件 - /// - /// 字段名称 - public OrderCondition(string sortField) - : this(sortField, SortDirection.Ascending) - { } - - /// - /// 构造一个排序字段名称和排序方式的排序条件 - /// - /// 字段名称 - /// 排序方式 - public OrderCondition(string sortField, SortDirection sortDirection) - { - SortField = sortField; - SortDirection = sortDirection; - } - - /// - /// 获取或设置 排序字段名称 - /// - public string SortField { get; set; } - - /// - /// 获取或设置 排序方向 - /// - public SortDirection SortDirection { get; set; } - } - public class OrderCondition : OrderCondition - { - - /// - /// 使用排序字段 初始化一个类型的新实例 - /// - public OrderCondition(Expression> keySelector) - : this(keySelector, SortDirection.Ascending) - { } - - /// - /// 使用排序字段与排序方式 初始化一个类型的新实例 - /// - public OrderCondition(Expression> keySelector, SortDirection sortDirection) - : base(GetPropertyName(keySelector), sortDirection) - { } - - /// - /// 从泛型委托获取属性名 - /// - private static string GetPropertyName(Expression> keySelector) - { - - return keySelector.GetPropertyName(); - } - } - -} diff --git a/src/Destiny.Core.Flow/Filter/PageParameters.cs b/src/Destiny.Core.Flow/Filter/PageParameters.cs deleted file mode 100644 index d4471e09..00000000 --- a/src/Destiny.Core.Flow/Filter/PageParameters.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Destiny.Core.Flow.Filter.Abstract; - -namespace Destiny.Core.Flow.Filter -{ - /// - /// 分页所需的参数 - /// - public class PageParameters : IPagedRequest, IFilteredPagedRequest, IOrderRequest - { - - - - - /// - /// 分页索引 - /// - - public virtual int PageIndex { get; set; } - - /// - /// 分页大小 - /// - public virtual int PageSize { get; set; } - - /// - /// 排序条件集合 - /// - public OrderCondition[] OrderConditions { get; set; } - - /// - /// 查询过滤 - /// - public QueryFilter Filter { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Filter/PageRequest.cs b/src/Destiny.Core.Flow/Filter/PageRequest.cs deleted file mode 100644 index 0e6e75e2..00000000 --- a/src/Destiny.Core.Flow/Filter/PageRequest.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Destiny.Core.Flow.Filter -{ - public class PageRequest : PageParameters - { - - public PageRequest() - { - PageIndex = 1; - PageSize = 10; - OrderConditions = new OrderCondition[] { }; - Filter = new QueryFilter(); - } - } -} diff --git a/src/Destiny.Core.Flow/Filter/PageResult.cs b/src/Destiny.Core.Flow/Filter/PageResult.cs deleted file mode 100644 index 075ffb31..00000000 --- a/src/Destiny.Core.Flow/Filter/PageResult.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Filter.Abstract; -using Destiny.Core.Flow.Ui; -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Filter -{ - /// - /// 分页数据 - /// - /// 动态类型 - public class PageResult : ResultBase, IPagedResult, IHasResultType - { - - public PageResult() : this(new T[0], 0, "查询成功", true) - { - - } - public PageResult(IReadOnlyList itemList, int total, string message = "查询成功", bool success = true) - { - ItemList = itemList; - Total = total; - Success = success; - this.Message = message; - Type = success ? AjaxResultType.Success : AjaxResultType.Error; - } - - - /// - /// 总数 - /// - - public int Total { get; set; } - - public IReadOnlyList ItemList { get; set; } - public AjaxResultType Type { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Filter/PagedRequestModel.cs b/src/Destiny.Core.Flow/Filter/PagedRequestModel.cs deleted file mode 100644 index 78abca91..00000000 --- a/src/Destiny.Core.Flow/Filter/PagedRequestModel.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Destiny.Core.Flow.Filter.Abstract; - -namespace Destiny.Core.Flow.Filter -{ - public class PagedRequestModel : IFilteredPagedRequest - { - - public PagedRequestModel() - { - - OrderConditions = new OrderCondition[] { }; - Filter = new QueryFilter(); - } - public int PageIndex { get; set; } = 1; - public int PageSize { get; set; } = 10; - public OrderCondition[] OrderConditions { get; set; } - public QueryFilter Filter { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Filter/QueryFilter.cs b/src/Destiny.Core.Flow/Filter/QueryFilter.cs deleted file mode 100644 index 71a20f7e..00000000 --- a/src/Destiny.Core.Flow/Filter/QueryFilter.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.ExpressionUtil; -using Destiny.Core.Flow.Extensions; -using System; -using System.Collections.Generic; -using System.Linq.Expressions; - -namespace Destiny.Core.Flow.Filter -{ - /// - /// 查询过滤器 - /// - public class QueryFilter - { - public QueryFilter() - { - - } - public QueryFilter(FilterConnect filterConnect, List conditions) - { - this.FilterConnect = filterConnect; - this.Conditions = conditions; - } - /// - /// 查询条件and或者Or - /// - public FilterConnect FilterConnect { get; set; } = FilterConnect.And; - - public List Filters = new List(); - public List Conditions { get; set; } = new List(); - - - /// - /// 添加条件 - /// - /// 字段 - /// 值 - /// 操作条件 - - public QueryFilter AddCondition(string field,object value, FilterOperator @operator=FilterOperator.Equal) { - - field.NotNullOrEmpty(nameof(field)); - @operator.NotNull(nameof(@operator)); - this.Conditions.Add(new FilterCondition(field, value, @operator)); - return this; - } - } -} diff --git a/src/Destiny.Core.Flow/Filter/QueryParameters.cs b/src/Destiny.Core.Flow/Filter/QueryParameters.cs deleted file mode 100644 index cb186b05..00000000 --- a/src/Destiny.Core.Flow/Filter/QueryParameters.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Destiny.Core.Flow.Filter.Abstract; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Filter -{ - /// - /// 页面查询参数 - /// - public class QueryParameters : IFilteredRequest - { - public QueryFilter Filter { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Filter/ResultBaseOfModel.cs b/src/Destiny.Core.Flow/Filter/ResultBaseOfModel.cs deleted file mode 100644 index cfe427fd..00000000 --- a/src/Destiny.Core.Flow/Filter/ResultBaseOfModel.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Destiny.Core.Flow.Ui; - -namespace Destiny.Core.Flow.Filter -{ - public abstract class ResultBase : ResultBase, IResultData - { - public virtual TData Data { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Helpers/ArrayHelper.cs b/src/Destiny.Core.Flow/Helpers/ArrayHelper.cs deleted file mode 100644 index 403874bc..00000000 --- a/src/Destiny.Core.Flow/Helpers/ArrayHelper.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Helpers -{ - public static class ArrayHelper - { - public static T[] Empty() => -#if NET45 - - EmptyArray.Value -#else - Array.Empty() -#endif - ; - -#if NET45 - private static class EmptyArray - { - public static readonly T[] Value = new T[0]; - } -#endif - } -} diff --git a/src/Destiny.Core.Flow/Helpers/DelegateHelper.cs b/src/Destiny.Core.Flow/Helpers/DelegateHelper.cs deleted file mode 100644 index ed9db9c8..00000000 --- a/src/Destiny.Core.Flow/Helpers/DelegateHelper.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Helps -{ - /// - /// 委托帮助类 - /// - public class DelegateHelper - { - /// - /// 异步执行方法 - /// - /// 首先执行的方法 - /// 接下来执行的方法 - public static void RunAsync(Action firstFunc, Action next) - { - Task firstTask = new Task(() => - { - firstFunc(); - }); - - firstTask.Start(); - firstTask.ContinueWith(x => next()); - } - - /// - /// 异步执行方法 - /// - /// 首先执行的方法 - /// 接下来执行的方法 - public static void RunAsync(Func firstFunc, Action next) - { - Task firstTask = new Task(() => - { - return firstFunc(); - }); - - firstTask.Start(); - firstTask.ContinueWith(x => next(x.Result)); - } - - } -} diff --git a/src/Destiny.Core.Flow/Helpers/JsonHelper.cs b/src/Destiny.Core.Flow/Helpers/JsonHelper.cs deleted file mode 100644 index 441fee1a..00000000 --- a/src/Destiny.Core.Flow/Helpers/JsonHelper.cs +++ /dev/null @@ -1,324 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; - - -namespace Destiny.Core.Flow.Helpers -{ - /// - /// JSON帮助类 - /// - public static partial class JsonHelper - { - #region Private fields - - private static readonly JsonSerializerSettings JsonSettings; - - private const string EmptyJson = "[]"; - #endregion - - #region Constructor - - static JsonHelper() - - { - - var datetimeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; - - JsonSettings = new JsonSerializerSettings - { - - MissingMemberHandling = MissingMemberHandling.Ignore, - NullValueHandling = NullValueHandling.Ignore, - ReferenceLoopHandling = ReferenceLoopHandling.Ignore - }; - JsonSettings.Converters.Add(datetimeConverter); - } - #endregion - - #region Public Methods - - /// - /// 应用Formatting.None和指定的JsonSerializerSettings设置,序列化对象到JSON格式的字符串 - /// - /// 任意一个对象 - /// 在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 - /// 标准的JSON格式的字符串 - public static string ToJson(this object obj, JsonSerializerSettings jsonSettings) - { - return ToJson(obj, Formatting.None, jsonSettings); - } - - /// - /// 应用指定的Formatting枚举值None和指定的JsonSerializerSettings设置,序列化对象到JSON格式的字符串 - /// - /// 任意一个对象 - /// 指定 Newtonsoft.Json.JsonTextWriter 的格式设置选项 - /// 在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 - /// 标准的JSON格式的字符串 - public static string ToJson(object obj, Formatting format, JsonSerializerSettings jsonSettings) - { - try - { - return obj == null ? EmptyJson : JsonConvert.SerializeObject(obj, format, jsonSettings ?? JsonSettings); - } - catch (Exception) - { - //TODO LOG - return EmptyJson; - } - } - - /// - /// 应用Formatting.None和指定的JsonSerializerSettings设置,反序列化JSON数据为dynamic对象 - /// 如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个dynamic对象。 - /// 转换失败,或发生其它异常,则返回dynamic对象的默认值 - /// - /// 需要反序列化的JSON字符串 - /// 在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 - /// dynamic对象 - public static dynamic FromJson(this string json, JsonSerializerSettings jsonSettings) - { - return FromJson(json, Formatting.None, jsonSettings); - } - - /// - /// 应用指定的Formatting枚举值None和指定的JsonSerializerSettings设置,反序列化JSON数据为dynamic对象 - /// 如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个dynamic对象。 - /// 转换失败,或发生其它异常,则返回dynamic对象的默认值 - /// - /// 需要反序列化的JSON字符串 - /// 指定 Newtonsoft.Json.JsonTextWriter 的格式设置选项 - /// 在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 - /// dynamic对象 - public static dynamic FromJson(this string json, Formatting format, JsonSerializerSettings jsonSettings) - { - return FromJson(json, format, jsonSettings); - } - - /// - /// 应用Formatting.None和指定的JsonSerializerSettings设置,反序列化JSON数据到指定的.NET类型对象 - /// 如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个T对象。 - /// 转换失败,或发生其它异常,则返回T对象的默认值 - /// - /// 需要反序列化的JSON字符串 - /// 在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 - /// 反序列化对象的类型 - /// - public static T FromJson(string json, JsonSerializerSettings jsonSettings) - { - return FromJson(json, Formatting.None, jsonSettings); - } - - /// - /// 应用指定的Formatting枚举值None和指定的JsonSerializerSettings设置,反序列化JSON数据到指定的.NET类型对象 - /// 如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个T对象。 - /// 转换失败,或发生其它异常,则返回T对象的默认值 - /// - /// 需要反序列化的JSON字符串 - /// 指定 Newtonsoft.Json.JsonTextWriter 的格式设置选项 - /// 在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 - /// 反序列化对象的类型 - /// - public static T FromJson(string json, Formatting format, JsonSerializerSettings jsonSettings) - { - T result; - - if (jsonSettings == null) - { - jsonSettings = JsonSettings; - } - - try - { - - - result = string.IsNullOrWhiteSpace(json) ? default(T) : JsonConvert.DeserializeObject(json, jsonSettings); - } - catch (JsonSerializationException) //在发生该异常后,再以集合的方式重试一次. - { - //LOG - try - { - var array = JsonConvert.DeserializeObject>(json, jsonSettings); - result = array.FirstOrDefault(); - } - catch (Exception) - { - //LOG - result = default(T); - } - } - catch (Exception) - { - //LOG - result = default(T); - } - return result; - } - #endregion - - #region Public Extend Methods - - /// - /// 反序列化JSON数据为dynamic对象 - /// 如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个dynamic对象。 - /// 转换失败,或发生其它异常,则返回dynamic对象的默认值 - /// - /// 需要反序列化的JSON字符串 - /// dynamic对象 - public static dynamic FromJson(this string json) - { - return FromJson(json, Formatting.None, JsonSettings); - } - - /// - /// 反序列化JSON数据到指定的.NET类型对象 - /// 如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个T对象。 - /// 转换失败,或发生其它异常,则返回T对象的默认值 - /// - /// 需要反序列化的JSON字符串 - /// 反序列化对象的类型 - /// - public static T FromJson(this string json) - { - return FromJson(json, Formatting.None, JsonSettings); - } - - - - - /// - /// 应用默认的Formatting枚举值None和默认的JsonSerializerSettings设置,序列化对象到JSON格式的字符串 - /// - /// 任意一个对象 - /// 标准的JSON格式的字符串 - public static string ToJson(this object obj) - { - return ToJson(obj, Formatting.None, JsonSettings); - } - - - - public static string ToJson(this IEnumerable source, Func predicate, bool isFilterNull = true) - { - return DelegateToJson(source, enumerable => enumerable.Where(predicate), isFilterNull); - } - - public static string ToJson(this IEnumerable source, Func predicate, bool isFilterNull = true) - { - return DelegateToJson(source, enumerable => enumerable.Where(predicate), isFilterNull); - } - - public static string ToJson(this IEnumerable source, Func selector, bool isFilterNull = true) - { - return DelegateToJson(source, enumerable => enumerable.Where(t => t != null).Select(selector), isFilterNull); - } - - public static string ToJson(this IEnumerable source, Func selector, bool isFilterNull = true) - { - return DelegateToJson(source, enumerable => enumerable.Where(t => t != null).Select(selector), isFilterNull); - } - - public static string ToJson(this IEnumerable source, Func predicate, Func selector, bool isFilterNull = true) - { - return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); - } - - public static string ToJson(this IEnumerable source, Func predicate, Func selector, bool isFilterNull = true) - { - return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); - } - - public static string ToJson(this IEnumerable source, Func predicate, Func selector, bool isFilterNull = true) - { - return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); - } - - public static string ToJson(this IEnumerable source, Func predicate, Func selector, bool isFilterNull = true) - { - return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); - } - #endregion - - #region Private Methods - - /// - /// 委托处理需要序列化为JSON格式的对象,返回标准的JSON格式的字符串。 - /// 默认过滤null对象,如果需要在上层调用时,自己进行条件过滤null对象, - /// 则设置isFilterNull为false,不建议isFilterNull设置为false。 - /// - /// - /// - /// 需要转换为JSON格式字符串的对象 - /// 集合/数组条件筛选方法委托,返回筛选后的集合/数组 - /// 是否过滤IEnumerable source中的null对象,默认为true - /// 标准的JSON格式的字符串 - private static string DelegateToJson(IEnumerable source, Func> func, bool isFilterNull = true) - { - return DelegateToJson(source, enumerable => func(enumerable).ToJson(), isFilterNull); - } - - /// - /// 转成字符串 - /// - /// - /// - /// - public static object ToObject(this JObject jObject, string key) - { - - return jObject.To(key); - } - - /// - /// 转成对应类型 - /// - /// - /// - /// - public static T To(this JObject jObject, string key) - { - jObject.NotNull(nameof(jObject)); - key.NotNullOrEmpty(nameof(key)); - return jObject.Value(key); - } - /// - /// 委托处理需要序列化为JSON格式的对象,返回标准的JSON格式的字符串。 - /// 默认过滤null对象,如果需要在上层调用时,自己进行条件过滤null对象, - /// 则设置isFilterNull为false,不建议isFilterNull设置为false。 - /// - /// - /// 需要转换为JSON格式字符串的对象 - /// JSON处理方法委托,返回JSON格式的字符串 - /// 是否过滤IEnumerable source中的null对象,默认为true - /// 标准的JSON格式的字符串 - private static string DelegateToJson(IEnumerable source, Func func, bool isFilterNull = true) - { - if (source == null) - { - return EmptyJson; - } - - TSource[] enumerable; - if (isFilterNull) - { - //过滤null - enumerable = source.Where(t => t != null).ToArray(); - } - else - { - //不过滤null,但上层需要注意内里面有null对象时,可能会导致Where或Select引发异常。 - enumerable = source as TSource[] ?? source.ToArray(); - } - - return enumerable.Any() ? func(enumerable) : EmptyJson; - } - - #endregion - } -} diff --git a/src/Destiny.Core.Flow/Helpers/ReflectHelper.cs b/src/Destiny.Core.Flow/Helpers/ReflectHelper.cs deleted file mode 100644 index 10b54a15..00000000 --- a/src/Destiny.Core.Flow/Helpers/ReflectHelper.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Reflection; - -namespace Destiny.Core.Flow.Helpers -{ - public static class ReflectHelper - { - public static Assembly[] GetAssemblies() - { - Assembly[] assemblies = null; -#if NET45 - if (System.Web.Hosting.HostingEnvironment.IsHosted) - { - assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies() - .Cast().ToArray(); - } -#endif - - if (null == assemblies || assemblies.Length == 0) - { - assemblies = AppDomain.CurrentDomain.GetAssemblies(); - } - - return assemblies ?? ArrayHelper.Empty(); - } - } -} diff --git a/src/Destiny.Core.Flow/Helpers/TypeNameHelper.cs b/src/Destiny.Core.Flow/Helpers/TypeNameHelper.cs deleted file mode 100644 index 1aa10b33..00000000 --- a/src/Destiny.Core.Flow/Helpers/TypeNameHelper.cs +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright(c) .NET Foundation and Contributors -// -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not use -// this file except in compliance with the License. You may obtain a copy of the -// License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. -// -// From https://github.com/aspnet/Common/blob/62018e351c9bed107075d0139b551fb086f9693d/shared/Microsoft.Extensions.TypeNameHelper.Sources/TypeNameHelper.cs - -// ReSharper disable All - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Text; - -namespace Microsoft.Extensions.Internal -{ - internal class TypeNameHelper - { - private static readonly Dictionary _builtInTypeNames = new Dictionary - { - { typeof(void), "void" }, - { typeof(bool), "bool" }, - { typeof(byte), "byte" }, - { typeof(char), "char" }, - { typeof(decimal), "decimal" }, - { typeof(double), "double" }, - { typeof(float), "float" }, - { typeof(int), "int" }, - { typeof(long), "long" }, - { typeof(object), "object" }, - { typeof(sbyte), "sbyte" }, - { typeof(short), "short" }, - { typeof(string), "string" }, - { typeof(uint), "uint" }, - { typeof(ulong), "ulong" }, - { typeof(ushort), "ushort" } - }; - - /// - /// Pretty print a type name. - /// - /// The . - /// true to print a fully qualified name. - /// true to include generic parameter names. - /// The pretty printed type name. - public static string GetTypeDisplayName(Type type, bool fullName = true, bool includeGenericParameterNames = false) - { - var builder = new StringBuilder(); - ProcessType(builder, type, new DisplayNameOptions(fullName, includeGenericParameterNames)); - return builder.ToString(); - } - - private static void ProcessType(StringBuilder builder, Type type, DisplayNameOptions options) - { - var typeInfo = type.GetTypeInfo(); - - if (typeInfo.IsGenericType) - { - var genericArguments = typeInfo.GenericTypeArguments; - ProcessGenericType(builder, type, genericArguments, genericArguments.Length, options); - } - else if (type.IsArray) - { - ProcessArrayType(builder, type, options); - } - else if (_builtInTypeNames.TryGetValue(type, out var builtInName)) - { - builder.Append(builtInName); - } - else if (type.IsGenericParameter) - { - if (options.IncludeGenericParameterNames) - { - builder.Append(type.Name); - } - } - else - { - builder.Append(options.FullName ? type.FullName : type.Name); - } - } - - private static void ProcessArrayType(StringBuilder builder, Type type, DisplayNameOptions options) - { - var innerType = type; - while (innerType.IsArray) - { - innerType = innerType.GetElementType(); - } - - ProcessType(builder, innerType, options); - - while (type.IsArray) - { - builder.Append('['); - builder.Append(',', type.GetArrayRank() - 1); - builder.Append(']'); - type = type.GetElementType(); - } - } - - private static void ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, int length, DisplayNameOptions options) - { - var offset = 0; - if (type.IsNested) - { - offset = type.DeclaringType.GetTypeInfo().GenericTypeArguments.Length; - } - - if (options.FullName) - { - if (type.IsNested) - { - ProcessGenericType(builder, type.DeclaringType, genericArguments, offset, options); - builder.Append('+'); - } - else if (!string.IsNullOrEmpty(type.Namespace)) - { - builder.Append(type.Namespace); - builder.Append('.'); - } - } - - var genericPartIndex = type.Name.IndexOf('`'); - if (genericPartIndex <= 0) - { - builder.Append(type.Name); - return; - } - - builder.Append(type.Name, 0, genericPartIndex); - - builder.Append('<'); - for (var i = offset; i < length; i++) - { - ProcessType(builder, genericArguments[i], options); - if (i + 1 == length) - { - continue; - } - - builder.Append(','); - if (options.IncludeGenericParameterNames || !genericArguments[i + 1].IsGenericParameter) - { - builder.Append(' '); - } - } - builder.Append('>'); - } - - private struct DisplayNameOptions - { - public DisplayNameOptions(bool fullName, bool includeGenericParameterNames) - { - FullName = fullName; - IncludeGenericParameterNames = includeGenericParameterNames; - } - - public bool FullName { get; } - - public bool IncludeGenericParameterNames { get; } - } - } -} diff --git a/src/Destiny.Core.Flow/IdentityServer4/AllowedSigningAlgorithmsConverter.cs b/src/Destiny.Core.Flow/IdentityServer4/AllowedSigningAlgorithmsConverter.cs deleted file mode 100644 index feab693a..00000000 --- a/src/Destiny.Core.Flow/IdentityServer4/AllowedSigningAlgorithmsConverter.cs +++ /dev/null @@ -1,38 +0,0 @@ -using AutoMapper; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Destiny.Core.Flow -{ - public class AllowedSigningAlgorithmsConverter : - IValueConverter, string>, - IValueConverter> - { - public static AllowedSigningAlgorithmsConverter Converter = new AllowedSigningAlgorithmsConverter(); - - public string Convert(ICollection sourceMember, ResolutionContext context) - { - if (sourceMember == null || !sourceMember.Any()) - { - return null; - } - return string.Join(',', sourceMember); - } - - public ICollection Convert(string sourceMember, ResolutionContext context) - { - var list = new HashSet(); - if (!String.IsNullOrWhiteSpace(sourceMember)) - { - sourceMember = sourceMember.Trim(); - foreach (var item in sourceMember.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Distinct()) - { - list.Add(item); - } - } - return list; - } - } - -} diff --git a/src/Destiny.Core.Flow/IdentityServer4/GrantType.cs b/src/Destiny.Core.Flow/IdentityServer4/GrantType.cs deleted file mode 100644 index fef60257..00000000 --- a/src/Destiny.Core.Flow/IdentityServer4/GrantType.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow -{ - public static class GrantType - { - public const string Implicit = "implicit"; - - public const string Hybrid = "hybrid"; - - public const string AuthorizationCode = "authorization_code"; - - public const string ClientCredentials = "client_credentials"; - - public const string ResourceOwnerPassword = "password"; - - public const string DeviceFlow = "urn:ietf:params:oauth:grant-type:device_code"; - } -} diff --git a/src/Destiny.Core.Flow/IdentityServer4/GrantTypes.cs b/src/Destiny.Core.Flow/IdentityServer4/GrantTypes.cs deleted file mode 100644 index 56fc87e3..00000000 --- a/src/Destiny.Core.Flow/IdentityServer4/GrantTypes.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. -// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. - - -using System.Collections.Generic; - -#pragma warning disable 1591 - -namespace Destiny.Core.Flow -{ - public class GrantTypes - { - public static ICollection Implicit => - new[] { GrantType.Implicit }; - - public static ICollection ImplicitAndClientCredentials => - new[] { GrantType.Implicit, GrantType.ClientCredentials }; - - public static ICollection Code => - new[] { GrantType.AuthorizationCode }; - - public static ICollection CodeAndClientCredentials => - new[] { GrantType.AuthorizationCode, GrantType.ClientCredentials }; - - public static ICollection Hybrid => - new[] { GrantType.Hybrid }; - - public static ICollection HybridAndClientCredentials => - new[] { GrantType.Hybrid, GrantType.ClientCredentials }; - - public static ICollection ClientCredentials => - new[] { GrantType.ClientCredentials }; - - public static ICollection ResourceOwnerPassword => - new[] { GrantType.ResourceOwnerPassword }; - - public static ICollection ResourceOwnerPasswordAndClientCredentials => - new[] { GrantType.ResourceOwnerPassword, GrantType.ClientCredentials }; - - public static ICollection DeviceFlow => - new[] { GrantType.DeviceFlow }; - } -} \ No newline at end of file diff --git a/src/Destiny.Core.Flow/IdentityServer4/JwtClaimTypes.cs b/src/Destiny.Core.Flow/IdentityServer4/JwtClaimTypes.cs deleted file mode 100644 index a647e1c8..00000000 --- a/src/Destiny.Core.Flow/IdentityServer4/JwtClaimTypes.cs +++ /dev/null @@ -1,382 +0,0 @@ - - -using System.Collections.Generic; -using System.Linq; - -namespace Destiny.Core.Flow -{ - // - // 摘要: - // Commonly used claim types - public static class JwtClaimTypes - { - public class JwtTypes - { - // - // 摘要: - // OAuth 2.0 access token - public const string AccessToken = "at+jwt"; - - // - // 摘要: - // JWT secured authorization request - public const string AuthorizationRequest = "oauth-authz-req+jwt"; - } - - // - // 摘要: - // Unique Identifier for the End-User at the Issuer. - public const string Subject = "sub"; - - // - // 摘要: - // End-User's full name in displayable form including all name parts, possibly including - // titles and suffixes, ordered according to the End-User's locale and preferences. - public const string Name = "name"; - - // - // 摘要: - // Given name(s) or first name(s) of the End-User. Note that in some cultures, people - // can have multiple given names; all can be present, with the names being separated - // by space characters. - public const string GivenName = "given_name"; - - // - // 摘要: - // Surname(s) or last name(s) of the End-User. Note that in some cultures, people - // can have multiple family names or no family name; all can be present, with the - // names being separated by space characters. - public const string FamilyName = "family_name"; - - // - // 摘要: - // Middle name(s) of the End-User. Note that in some cultures, people can have multiple - // middle names; all can be present, with the names being separated by space characters. - // Also note that in some cultures, middle names are not used. - public const string MiddleName = "middle_name"; - - // - // 摘要: - // Casual name of the End-User that may or may not be the same as the given_name. - // For instance, a nickname value of Mike might be returned alongside a given_name - // value of Michael. - public const string NickName = "nickname"; - - // - // 摘要: - // Shorthand name by which the End-User wishes to be referred to at the RP, such - // as janedoe or j.doe. This value MAY be any valid JSON string including special - // characters such as @, /, or whitespace. The relying party MUST NOT rely upon - // this value being unique - // - // 言论: - // The RP MUST NOT rely upon this value being unique, as discussed in http://openid.net/specs/openid-connect-basic-1_0-32.html#ClaimStability - public const string PreferredUserName = "preferred_username"; - - // - // 摘要: - // URL of the End-User's profile page. The contents of this Web page SHOULD be about - // the End-User. - public const string Profile = "profile"; - - // - // 摘要: - // URL of the End-User's profile picture. This URL MUST refer to an image file (for - // example, a PNG, JPEG, or GIF image file), rather than to a Web page containing - // an image. - // - // 言论: - // Note that this URL SHOULD specifically reference a profile photo of the End-User - // suitable for displaying when describing the End-User, rather than an arbitrary - // photo taken by the End-User. - public const string Picture = "picture"; - - // - // 摘要: - // URL of the End-User's Web page or blog. This Web page SHOULD contain information - // published by the End-User or an organization that the End-User is affiliated - // with. - public const string WebSite = "website"; - - // - // 摘要: - // End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 [RFC5322] - // addr-spec syntax. The relying party MUST NOT rely upon this value being unique - public const string Email = "email"; - - // - // 摘要: - // "true" if the End-User's e-mail address has been verified; otherwise "false". - // - // 言论: - // When this Claim Value is "true", this means that the OP took affirmative steps - // to ensure that this e-mail address was controlled by the End-User at the time - // the verification was performed. The means by which an e-mail address is verified - // is context-specific, and dependent upon the trust framework or contractual agreements - // within which the parties are operating. - public const string EmailVerified = "email_verified"; - - // - // 摘要: - // End-User's gender. Values defined by this specification are "female" and "male". - // Other values MAY be used when neither of the defined values are applicable. - public const string Gender = "gender"; - - // - // 摘要: - // End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD - // format. The year MAY be 0000, indicating that it is omitted. To represent only - // the year, YYYY format is allowed. Note that depending on the underlying platform's - // date related function, providing just year can result in varying month and day, - // so the implementers need to take this factor into account to correctly process - // the dates. - public const string BirthDate = "birthdate"; - - // - // 摘要: - // String from the time zone database (http://www.twinsun.com/tz/tz-link.htm) representing - // the End-User's time zone. For example, Europe/Paris or America/Los_Angeles. - public const string ZoneInfo = "zoneinfo"; - - // - // 摘要: - // End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically - // an ISO 639-1 Alpha-2 [ISO639‑1] language code in lowercase and an ISO 3166-1 - // Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, - // en-US or fr-CA. As a compatibility note, some implementations have used an underscore - // as the separator rather than a dash, for example, en_US; Relying Parties MAY - // choose to accept this locale syntax as well. - public const string Locale = "locale"; - - // - // 摘要: - // End-User's preferred telephone number. E.164 (https://www.itu.int/rec/T-REC-E.164/e) - // is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or - // +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED - // that the extension be represented using the RFC 3966 [RFC3966] extension syntax, - // for example, +1 (604) 555-1234;ext=5678. - public const string PhoneNumber = "phone_number"; - - // - // 摘要: - // True if the End-User's phone number has been verified; otherwise false. When - // this Claim Value is true, this means that the OP took affirmative steps to ensure - // that this phone number was controlled by the End-User at the time the verification - // was performed. - // - // 言论: - // The means by which a phone number is verified is context-specific, and dependent - // upon the trust framework or contractual agreements within which the parties are - // operating. When true, the phone_number Claim MUST be in E.164 format and any - // extensions MUST be represented in RFC 3966 format. - public const string PhoneNumberVerified = "phone_number_verified"; - - // - // 摘要: - // End-User's preferred postal address. The value of the address member is a JSON - // structure containing some or all of the members defined in http://openid.net/specs/openid-connect-basic-1_0-32.html#AddressClaim - public const string Address = "address"; - - // - // 摘要: - // Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 - // client_id of the Relying Party as an audience value. It MAY also contain identifiers - // for other audiences. In the general case, the aud value is an array of case sensitive - // strings. In the common special case when there is one audience, the aud value - // MAY be a single case sensitive string. - public const string Audience = "aud"; - - // - // 摘要: - // Issuer Identifier for the Issuer of the response. The iss value is a case sensitive - // URL using the https scheme that contains scheme, host, and optionally, port number - // and path components and no query or fragment components. - public const string Issuer = "iss"; - - // - // 摘要: - // The time before which the JWT MUST NOT be accepted for processing, specified - // as the number of seconds from 1970-01-01T0:0:0Z - public const string NotBefore = "nbf"; - - // - // 摘要: - // The exp (expiration time) claim identifies the expiration time on or after which - // the token MUST NOT be accepted for processing, specified as the number of seconds - // from 1970-01-01T0:0:0Z - public const string Expiration = "exp"; - - // - // 摘要: - // Time the End-User's information was last updated. Its value is a JSON number - // representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC - // until the date/time. - public const string UpdatedAt = "updated_at"; - - // - // 摘要: - // The iat (issued at) claim identifies the time at which the JWT was issued, , - // specified as the number of seconds from 1970-01-01T0:0:0Z - public const string IssuedAt = "iat"; - - // - // 摘要: - // Authentication Methods References. JSON array of strings that are identifiers - // for authentication methods used in the authentication. - public const string AuthenticationMethod = "amr"; - - // - // 摘要: - // Session identifier. This represents a Session of an OP at an RP to a User Agent - // or device for a logged-in End-User. Its contents are unique to the OP and opaque - // to the RP. - public const string SessionId = "sid"; - - // - // 摘要: - // Authentication Context Class Reference. String specifying an Authentication Context - // Class Reference value that identifies the Authentication Context Class that the - // authentication performed satisfied. The value "0" indicates the End-User authentication - // did not meet the requirements of ISO/IEC 29115 level 1. Authentication using - // a long-lived browser cookie, for instance, is one example where the use of "level - // 0" is appropriate. Authentications with level 0 SHOULD NOT be used to authorize - // access to any resource of any monetary value. (This corresponds to the OpenID - // 2.0 PAPE nist_auth_level 0.) An absolute URI or an RFC 6711 registered name SHOULD - // be used as the acr value; registered names MUST NOT be used with a different - // meaning than that which is registered. Parties using this claim will need to - // agree upon the meanings of the values used, which may be context-specific. The - // acr value is a case sensitive string. - public const string AuthenticationContextClassReference = "acr"; - - // - // 摘要: - // Time when the End-User authentication occurred. Its value is a JSON number representing - // the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. - // When a max_age request is made or when auth_time is requested as an Essential - // Claim, then this Claim is REQUIRED; otherwise, its inclusion is OPTIONAL. - public const string AuthenticationTime = "auth_time"; - - // - // 摘要: - // The party to which the ID Token was issued. If present, it MUST contain the OAuth - // 2.0 Client ID of this party. This Claim is only needed when the ID Token has - // a single audience value and that audience is different than the authorized party. - // It MAY be included even when the authorized party is the same as the sole audience. - // The azp value is a case sensitive string containing a StringOrURI value. - public const string AuthorizedParty = "azp"; - - // - // 摘要: - // Access Token hash value. Its value is the base64url encoding of the left-most - // half of the hash of the octets of the ASCII representation of the access_token - // value, where the hash algorithm used is the hash algorithm used in the alg Header - // Parameter of the ID Token's JOSE Header. For instance, if the alg is RS256, hash - // the access_token value with SHA-256, then take the left-most 128 bits and base64url - // encode them. The at_hash value is a case sensitive string. - public const string AccessTokenHash = "at_hash"; - - // - // 摘要: - // Code hash value. Its value is the base64url encoding of the left-most half of - // the hash of the octets of the ASCII representation of the code value, where the - // hash algorithm used is the hash algorithm used in the alg Header Parameter of - // the ID Token's JOSE Header. For instance, if the alg is HS512, hash the code - // value with SHA-512, then take the left-most 256 bits and base64url encode them. - // The c_hash value is a case sensitive string. - public const string AuthorizationCodeHash = "c_hash"; - - // - // 摘要: - // State hash value. Its value is the base64url encoding of the left-most half of - // the hash of the octets of the ASCII representation of the state value, where - // the hash algorithm used is the hash algorithm used in the alg Header Parameter - // of the ID Token's JOSE Header. For instance, if the alg is HS512, hash the code - // value with SHA-512, then take the left-most 256 bits and base64url encode them. - // The c_hash value is a case sensitive string. - public const string StateHash = "s_hash"; - - // - // 摘要: - // String value used to associate a Client session with an ID Token, and to mitigate - // replay attacks. The value is passed through unmodified from the Authentication - // Request to the ID Token. If present in the ID Token, Clients MUST verify that - // the nonce Claim Value is equal to the value of the nonce parameter sent in the - // Authentication Request. If present in the Authentication Request, Authorization - // Servers MUST include a nonce Claim in the ID Token with the Claim Value being - // the nonce value sent in the Authentication Request. Authorization Servers SHOULD - // perform no other processing on nonce values used. The nonce value is a case sensitive - // string. - public const string Nonce = "nonce"; - - // - // 摘要: - // JWT ID. A unique identifier for the token, which can be used to prevent reuse - // of the token. These tokens MUST only be used once, unless conditions for reuse - // were negotiated between the parties; any such negotiation is beyond the scope - // of this specification. - public const string JwtId = "jti"; - - // - // 摘要: - // Defines a set of event statements that each may add additional claims to fully - // describe a single logical event that has occurred. - public const string Events = "events"; - - // - // 摘要: - // OAuth 2.0 Client Identifier valid at the Authorization Server. - public const string ClientId = "client_id"; - - // - // 摘要: - // OpenID Connect requests MUST contain the "openid" scope value. If the openid - // scope value is not present, the behavior is entirely unspecified. Other scope - // values MAY be present. Scope values used that are not understood by an implementation - // SHOULD be ignored. - public const string Scope = "scope"; - - // - // 摘要: - // The "act" (actor) claim provides a means within a JWT to express that delegation - // has occurred and identify the acting party to whom authority has been delegated.The - // "act" claim value is a JSON object and members in the JSON object are claims - // that identify the actor. The claims that make up the "act" claim identify and - // possibly provide additional information about the actor. - public const string Actor = "act"; - - // - // 摘要: - // The "may_act" claim makes a statement that one party is authorized to become - // the actor and act on behalf of another party. The claim value is a JSON object - // and members in the JSON object are claims that identify the party that is asserted - // as being eligible to act for the party identified by the JWT containing the claim. - public const string MayAct = "may_act"; - - // - // 摘要: - // an identifier - public const string Id = "id"; - - // - // 摘要: - // The identity provider - public const string IdentityProvider = "idp"; - - // - // 摘要: - // The role - public const string Role = "role"; - - // - // 摘要: - // The reference token identifier - public const string ReferenceTokenId = "reference_token_id"; - - // - // 摘要: - // The confirmation - public const string Confirmation = "cnf"; - - - } -} diff --git a/src/Destiny.Core.Flow/Mapping/AutoMapDirection.cs b/src/Destiny.Core.Flow/Mapping/AutoMapDirection.cs deleted file mode 100644 index 50f656bb..00000000 --- a/src/Destiny.Core.Flow/Mapping/AutoMapDirection.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Destiny.Core.Flow.Mapping -{ - public enum AutoMapDirection - { - From, - To - } -} diff --git a/src/Destiny.Core.Flow/Mapping/AutoMapFromAttribute.cs b/src/Destiny.Core.Flow/Mapping/AutoMapFromAttribute.cs deleted file mode 100644 index c6478ef1..00000000 --- a/src/Destiny.Core.Flow/Mapping/AutoMapFromAttribute.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Mapping -{ - [AttributeUsage(AttributeTargets.Class)] - public class AutoMapFromAttribute : AutoMappingAttribute - { - public override AutoMapDirection Direciton - { - get { return AutoMapDirection.From; } - } - public AutoMapFromAttribute(params Type[] targetTypes) - : base(targetTypes) - { - - } - } -} diff --git a/src/Destiny.Core.Flow/Mapping/AutoMapToAttribute.cs b/src/Destiny.Core.Flow/Mapping/AutoMapToAttribute.cs deleted file mode 100644 index 6361c330..00000000 --- a/src/Destiny.Core.Flow/Mapping/AutoMapToAttribute.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Mapping -{ - [AttributeUsage(AttributeTargets.Class)] - public class AutoMapToAttribute : AutoMappingAttribute - { - public override AutoMapDirection Direciton - { - get { return AutoMapDirection.To; } - } - public AutoMapToAttribute(params Type[] targetTypes) - : base(targetTypes) - { - - } - } -} diff --git a/src/Destiny.Core.Flow/Mapping/AutoMappingAttribute.cs b/src/Destiny.Core.Flow/Mapping/AutoMappingAttribute.cs deleted file mode 100644 index 5f21fa68..00000000 --- a/src/Destiny.Core.Flow/Mapping/AutoMappingAttribute.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using System; - - -namespace Destiny.Core.Flow.Mapping -{ - /// - /// 为什么要取这个名字因为跟AutoMapper重复 - /// - [AttributeUsage(AttributeTargets.Class)] - public class AutoMappingAttribute : Attribute - { - - public Type[] TargetTypes { get; private set; } - public virtual AutoMapDirection Direciton - { - get { return AutoMapDirection.From | AutoMapDirection.To; } - } - - public AutoMappingAttribute(params Type[] targetTypes) - { - targetTypes.NotNull(nameof(targetTypes)); - TargetTypes = targetTypes; - } - - } -} diff --git a/src/Destiny.Core.Flow/Modules/AppModule.cs b/src/Destiny.Core.Flow/Modules/AppModule.cs deleted file mode 100644 index 157d4558..00000000 --- a/src/Destiny.Core.Flow/Modules/AppModule.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -namespace Destiny.Core.Flow.Modules -{ - public class AppModule : IAppModule - { - public bool Enable { get; set; } = true; - - public virtual void ApplicationInitialization(ApplicationContext context) - { - - } - - public virtual void ConfigureServices(ConfigureServicesContext context) - { - - } - - public Type[] GetDependedTypes(Type moduleType = null) - { - if (moduleType == null) - { - moduleType = GetType(); - } - - var dependedTypes = moduleType.GetCustomAttributes().OfType().ToArray(); - if (dependedTypes.Length == 0) - { - return new Type[0]; - } - List dependList = new List(); - foreach (var dependedType in dependedTypes) - { - var dependeds = dependedType.GetDependedTypes(); - if (dependeds.Length == 0) - { - continue; - } - dependList.AddRange(dependeds); - - foreach (Type type in dependeds) - { - dependList.AddRange(GetDependedTypes(type)); - } - - } - return dependList.Distinct().ToArray(); - } - - - - - public static bool IsAppModule(Type type) - { - var typeInfo = type.GetTypeInfo(); - return typeInfo.IsClass && - !typeInfo.IsAbstract && - !typeInfo.IsGenericType && - typeof(IAppModule).GetTypeInfo().IsAssignableFrom(type); - } - } -} diff --git a/src/Destiny.Core.Flow/Modules/AppModuleExtensions.cs b/src/Destiny.Core.Flow/Modules/AppModuleExtensions.cs deleted file mode 100644 index 3fe8a3fa..00000000 --- a/src/Destiny.Core.Flow/Modules/AppModuleExtensions.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Extensions; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; -using System; - -namespace Destiny.Core.Flow.Modules -{ - public static class AppModuleExtensions - { - - public static IServiceCollection AddApplication(this IServiceCollection services) where T : IAppModule - { - - - services.AddApplication(typeof(T)); - return services; - - } - - private static IServiceCollection AddApplication(this IServiceCollection services, Type type) - { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - var obj = new ObjectAccessor(); - services.AddObjectAccessor(obj); - - - IStartupModuleRunner runner = new StartupModuleRunner(type, services); - runner.ConfigureServices(services); - - return services; - - } - - public static IApplicationBuilder InitializeApplication(this IApplicationBuilder builder) - { - builder.ApplicationServices.GetRequiredService>().Value = builder; - var runner = builder.ApplicationServices.GetRequiredService(); - runner.Initialize(builder.ApplicationServices); - return builder; - } - - } -} diff --git a/src/Destiny.Core.Flow/Modules/ApplicationContext.cs b/src/Destiny.Core.Flow/Modules/ApplicationContext.cs deleted file mode 100644 index 4a8b4ddf..00000000 --- a/src/Destiny.Core.Flow/Modules/ApplicationContext.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Extensions; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using System; - -namespace Destiny.Core.Flow.Modules -{ - /// - /// 应用上下文 - /// - public class ApplicationContext : IServiceProviderAccessor - { - public IServiceProvider ServiceProvider { get; set; } - - public ApplicationContext(IServiceProvider serviceProvider) - { - serviceProvider.NotNull(nameof(serviceProvider)); - ServiceProvider = serviceProvider; - } - public IConfiguration GetConfiguration() - { - return ServiceProvider.GetService(); - } - } -} diff --git a/src/Destiny.Core.Flow/Modules/ApplicationInitializationExtensions.cs b/src/Destiny.Core.Flow/Modules/ApplicationInitializationExtensions.cs deleted file mode 100644 index 3dd61271..00000000 --- a/src/Destiny.Core.Flow/Modules/ApplicationInitializationExtensions.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; - -namespace Destiny.Core.Flow.Modules -{ - public static class ApplicationInitializationExtensions - - { - - public static IApplicationBuilder GetApplicationBuilder(this ApplicationContext applicationContext) - { - return applicationContext.ServiceProvider.GetRequiredService>().Value; - } - - - - - - - - } -} diff --git a/src/Destiny.Core.Flow/Modules/ConfigureServicesContext.cs b/src/Destiny.Core.Flow/Modules/ConfigureServicesContext.cs deleted file mode 100644 index fbbfa03c..00000000 --- a/src/Destiny.Core.Flow/Modules/ConfigureServicesContext.cs +++ /dev/null @@ -1,60 +0,0 @@ - -using Destiny.Core.Flow.Extensions; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - - -namespace Destiny.Core.Flow.Modules -{ - /// - /// 配置服务上下文 - /// - public class ConfigureServicesContext - { - public ConfigureServicesContext(IServiceCollection services) - { - Services = services; - - } - public IServiceCollection Services { get; } - - - public IConfiguration GetConfiguration() - { - - var implemenInstance = Services.GetSingletonInstanceOrNull(); - return implemenInstance; - } - - - public TValue GetConfiguration(string key) - { - - return GetConfigurationSection(key).Get(); - } - public IConfigurationSection GetConfigurationSection(string key) - { - key.NotNullOrEmpty(nameof(key)); - return this.GetConfiguration()?.GetSection(key); - } - - - /// - /// 得到配置文件 - /// - /// - /// - /// - public TOptionSettings GetOptionSettings(string key) where TOptionSettings : class - { - var configuration = this.GetConfiguration(); - var settings = configuration.GetSection(key).Get(); - if (settings != null) - { - return settings; - } - - return Services.GetObject(); - } - } -} diff --git a/src/Destiny.Core.Flow/Modules/ConfigureServicesContextExtenstions.cs b/src/Destiny.Core.Flow/Modules/ConfigureServicesContextExtenstions.cs deleted file mode 100644 index f1629f4b..00000000 --- a/src/Destiny.Core.Flow/Modules/ConfigureServicesContextExtenstions.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Options; - -namespace Destiny.Core.Flow.Modules -{ - public static class ConfigureServicesContextExtenstions - { - - public static AppOptionSettings GetAppSettings(this ConfigureServicesContext services) - { - return services.Services.GetObject(); - } - } -} diff --git a/src/Destiny.Core.Flow/Modules/DependsOnAttribute.cs b/src/Destiny.Core.Flow/Modules/DependsOnAttribute.cs deleted file mode 100644 index 7407516e..00000000 --- a/src/Destiny.Core.Flow/Modules/DependsOnAttribute.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Modules -{ - [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] - /// - /// 依赖器 - /// - public class DependsOnAttribute : Attribute, IDependedTypesProvider - { - /// - /// 依赖类型集合 - /// - private Type[] DependedTypes { get; } - - public DependsOnAttribute(params Type[] dependedTypes) - { - DependedTypes = dependedTypes ?? new Type[0]; - } - /// - /// 得到依赖类型集合 - /// - /// - public virtual Type[] GetDependedTypes() - { - return DependedTypes; - } - - } -} diff --git a/src/Destiny.Core.Flow/Modules/IAppModule.cs b/src/Destiny.Core.Flow/Modules/IAppModule.cs deleted file mode 100644 index f8a9d5cc..00000000 --- a/src/Destiny.Core.Flow/Modules/IAppModule.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Modules -{ - /// - /// 模块接口 - /// - public interface IAppModule : IApplicationInitialization - { - void ConfigureServices(ConfigureServicesContext context); - - - - - - /// - //得到依赖集合 - /// - /// - /// - Type[] GetDependedTypes(Type moduleType = null); - - - bool Enable { get; set; } - - - } -} diff --git a/src/Destiny.Core.Flow/Modules/IApplicationInitialization.cs b/src/Destiny.Core.Flow/Modules/IApplicationInitialization.cs deleted file mode 100644 index 70cccfbd..00000000 --- a/src/Destiny.Core.Flow/Modules/IApplicationInitialization.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Destiny.Core.Flow.Modules -{ - /// - /// 应用初始化 - /// - public interface IApplicationInitialization - { - void ApplicationInitialization(ApplicationContext context); - } -} diff --git a/src/Destiny.Core.Flow/Modules/IDependedTypesProvider.cs b/src/Destiny.Core.Flow/Modules/IDependedTypesProvider.cs deleted file mode 100644 index c107a69f..00000000 --- a/src/Destiny.Core.Flow/Modules/IDependedTypesProvider.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Modules -{ - /// - /// 依赖类型提供者 - /// - public interface IDependedTypesProvider - { - /// - /// 得到依赖类型集合 - /// - /// - Type[] GetDependedTypes(); - } -} diff --git a/src/Destiny.Core.Flow/Modules/IModuleApplication.cs b/src/Destiny.Core.Flow/Modules/IModuleApplication.cs deleted file mode 100644 index 945026c3..00000000 --- a/src/Destiny.Core.Flow/Modules/IModuleApplication.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Modules -{ - public interface IModuleApplication : IDisposable - { - - Type StartupModuleType { get; } - - IServiceCollection Services { get; } - - IServiceProvider ServiceProvider { get; } - - IReadOnlyList Modules { get; } - } -} diff --git a/src/Destiny.Core.Flow/Modules/IStartupModuleRunner.cs b/src/Destiny.Core.Flow/Modules/IStartupModuleRunner.cs deleted file mode 100644 index 15e8bd92..00000000 --- a/src/Destiny.Core.Flow/Modules/IStartupModuleRunner.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; - -namespace Destiny.Core.Flow.Modules -{ - public interface IStartupModuleRunner : IModuleApplication - { - void ConfigureServices(IServiceCollection services); - - - void Initialize(IServiceProvider service); - - } -} - diff --git a/src/Destiny.Core.Flow/Modules/ModuleApplicationBase.cs b/src/Destiny.Core.Flow/Modules/ModuleApplicationBase.cs deleted file mode 100644 index 9e9c76c8..00000000 --- a/src/Destiny.Core.Flow/Modules/ModuleApplicationBase.cs +++ /dev/null @@ -1,105 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Reflection; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; - -namespace Destiny.Core.Flow.Modules -{ - public abstract class ModuleApplicationBase : IModuleApplication - { - public Type StartupModuleType { get; set; } - - public IServiceCollection Services { get; set; } - - public IServiceProvider ServiceProvider { get; set; } - public IReadOnlyList Modules { get; } - private List _source = new List(); - - public ModuleApplicationBase(Type startupModuleType, IServiceCollection services) - { - StartupModuleType = startupModuleType; - Services = services; - services.TryAddSingleton(); - services.TryAddSingleton(); - services.AddSingleton(this); - services.TryAddObjectAccessor(); - _source = this.GetAllModule(services); - - Modules = LoadModules(); - } - /// - /// 获取所有模块 - /// - /// - /// - private List GetAllModule(IServiceCollection services) - { - var typeFinder = services.GetOrAddSingletonService(); - var typs = typeFinder.Find(o => AppModule.IsAppModule(o)); - - var modules = typs.Select(o => CreateModule(services, o)).Distinct(); - return modules.ToList(); - } - - protected virtual void SetServiceProvider(IServiceProvider serviceProvider) - { - ServiceProvider = serviceProvider; - ServiceProvider.GetRequiredService>().Value = ServiceProvider; - } - /// - /// 获取需要加载的模块 - /// - /// - private IReadOnlyList LoadModules() - { - List modules = new List(); - - var module = _source.FirstOrDefault(o => o.GetType() == StartupModuleType); - if (module == null) - { - throw new AppException($"类型为“{StartupModuleType.FullName}”的模块实例无法找到"); - } - - - modules.Add(module); - - var dependeds = module.GetDependedTypes(); - foreach (var dependType in dependeds.Where(o => AppModule.IsAppModule(o))) - { - var dependModule = _source.ToList().Find(m => m.GetType() == dependType); - if (dependModule == null) - { - throw new AppException($"加载模块{module.GetType().FullName}时无法找到依赖模块{dependType.FullName}"); - } - - modules.AddIfNotContains(dependModule); - - } - return modules; - - } - /// - /// 注册模块 - /// - /// - /// - /// - private IAppModule CreateModule(IServiceCollection services, Type moduleType) - { - - var module = (IAppModule)Expression.Lambda(Expression.New(moduleType)).Compile().DynamicInvoke(); - services.AddSingleton(moduleType, module); - return module; - } - public virtual void Dispose() - { - - } - } -} diff --git a/src/Destiny.Core.Flow/Modules/StartupModuleRunner.cs b/src/Destiny.Core.Flow/Modules/StartupModuleRunner.cs deleted file mode 100644 index c5961433..00000000 --- a/src/Destiny.Core.Flow/Modules/StartupModuleRunner.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Microsoft.Extensions.DependencyInjection; -using System; - -namespace Destiny.Core.Flow.Modules -{ - public class StartupModuleRunner : ModuleApplicationBase, IStartupModuleRunner - { - public StartupModuleRunner(Type startupModuleType, IServiceCollection services) - : base(startupModuleType, services) - { - - services.AddSingleton(this); - - } - /// - /// 程序启动时加载模块中的配置 - /// - /// - public void ConfigureServices(IServiceCollection services) - { - IocManage.Instance.SetServiceCollection(services); - var ctx = new ConfigureServicesContext(services); - services.AddSingleton(ctx); - foreach (var cfg in Modules) - { - services.AddSingleton(cfg); - cfg.ConfigureServices(ctx); - } - } - /// - /// 加载应用程序 - /// - /// - public void Initialize(IServiceProvider service) - { - IocManage.Instance.SetApplicationServiceProvider(service); - SetServiceProvider(service); - using var scope = ServiceProvider.CreateScope(); - //using var scope = service.CreateScope(); - var ctx = new ApplicationContext(scope.ServiceProvider); - foreach (var cfg in Modules) - { - cfg.ApplicationInitialization(ctx); - } - } - - public override void Dispose() - { - base.Dispose(); - - if (ServiceProvider is IDisposable disposableServiceProvider) - { - disposableServiceProvider.Dispose(); - } - } - } -} diff --git a/src/Destiny.Core.Flow/Network/NetworkHelper.cs b/src/Destiny.Core.Flow/Network/NetworkHelper.cs deleted file mode 100644 index 26242175..00000000 --- a/src/Destiny.Core.Flow/Network/NetworkHelper.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Net; -using System.Net.NetworkInformation; -using System.Net.Sockets; - -namespace Destiny.Core.Flow.Network -{ - public class NetworkHelper - { - public static string LocalIPAddress - { - get - { - UnicastIPAddressInformation mostSuitableIp = null; - var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); - - foreach (var network in networkInterfaces) - { - if (network.OperationalStatus != OperationalStatus.Up) - continue; - var properties = network.GetIPProperties(); - if (properties.GatewayAddresses.Count == 0) - continue; - - foreach (var address in properties.UnicastAddresses) - { - if (address.Address.AddressFamily != AddressFamily.InterNetwork) - continue; - if (IPAddress.IsLoopback(address.Address)) - continue; - return address.Address.ToString(); - } - } - - return mostSuitableIp != null - ? mostSuitableIp.Address.ToString() - : ""; - } - } - } -} diff --git a/src/Destiny.Core.Flow/Options/AppOptionSettings.cs b/src/Destiny.Core.Flow/Options/AppOptionSettings.cs deleted file mode 100644 index 3ed421ca..00000000 --- a/src/Destiny.Core.Flow/Options/AppOptionSettings.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Destiny.Core.Flow.Options -{ - public class AppOptionSettings - { - - public AppOptionSettings() - { - DbContexts = new Dictionary(); - } - - - - - /// - /// Jwt操作类 - /// - public JwtOptions Jwt { get; set; } - - public CorsOptions Cors { get; set; } - - public AuthOptions Auth { get; set; } - - /// - /// 是否自动添加功能 - /// - public bool IsAutoAddFunction { get; set; } - - /// - /// 是否启用审计 - /// - public bool AuditEnabled { get; set; } - - /// - /// 数据操作 - /// - public Dictionary DbContexts { get; set; } - - - - - } -} diff --git a/src/Destiny.Core.Flow/Options/AuthOptions.cs b/src/Destiny.Core.Flow/Options/AuthOptions.cs deleted file mode 100644 index 87bb968c..00000000 --- a/src/Destiny.Core.Flow/Options/AuthOptions.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Destiny.Core.Flow.Options -{ - public class AuthOptions - { - /// - /// - /// - public string Authority { get; set; } - /// - /// - /// - public string Audience { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Options/CorsOptions.cs b/src/Destiny.Core.Flow/Options/CorsOptions.cs deleted file mode 100644 index 8d667d85..00000000 --- a/src/Destiny.Core.Flow/Options/CorsOptions.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace Destiny.Core.Flow.Options -{ - /// - /// Cors操作 - /// - public class CorsOptions - { - - /// - /// 策略名 - /// - public string PolicyName { get; set; } - - /// - /// Cors地址 - /// - public string Url { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Options/DestinyContextOptions.cs b/src/Destiny.Core.Flow/Options/DestinyContextOptions.cs deleted file mode 100644 index bda248b3..00000000 --- a/src/Destiny.Core.Flow/Options/DestinyContextOptions.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Destiny.Core.Flow.Entity; -using System; - -namespace Destiny.Core.Flow.Options -{ - /// - /// 数据库配置 - /// - - public class DestinyContextOptions - { - - - /// - /// 数据类型 - /// - public DatabaseType DatabaseType { get;set;} - - /// - /// 数据库链接 - /// - public string ConnectionString { get; set; } - - /// - /// 下上文类型名字 - /// - public string DbContextTypeName { get; set; } - - /// - /// 上下文类型 - /// - public Type DbContextType => Type.GetType(DbContextTypeName); - - /// - /// 迁移Assembly名字 - /// - public string MigrationsAssemblyName { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Options/JwtOptions.cs b/src/Destiny.Core.Flow/Options/JwtOptions.cs deleted file mode 100644 index 3e19d2a4..00000000 --- a/src/Destiny.Core.Flow/Options/JwtOptions.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace Destiny.Core.Flow.Options -{ - public class JwtOptions - { - /// - /// 密钥 - /// - public string SecretKey { get; set; } - - /// - /// 发行人 - /// - public string Issuer { get; set; } - - /// - /// 订阅人 - /// - public string Audience { get; set; } - - /// - /// 过期分种数 - /// - public double ExpireMins { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Permission/IAuthorityVerification.cs b/src/Destiny.Core.Flow/Permission/IAuthorityVerification.cs deleted file mode 100644 index 4fb3229c..00000000 --- a/src/Destiny.Core.Flow/Permission/IAuthorityVerification.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using Destiny.Core.Flow.Ui; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Permission -{ - /// - /// 权限验证接口 - /// - public interface IAuthorityVerification : IScopedDependency - { - /// - /// 判断用户是否有权限 - /// - /// - /// - Task IsPermission(string url); - } -} diff --git a/src/Destiny.Core.Flow/Permission/NoAuthorityVerificationAttribute.cs b/src/Destiny.Core.Flow/Permission/NoAuthorityVerificationAttribute.cs deleted file mode 100644 index 6d91f901..00000000 --- a/src/Destiny.Core.Flow/Permission/NoAuthorityVerificationAttribute.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Permission -{ - /// - /// 在API配置此特性代表不需要验证接口权限 - /// - [AttributeUsage(AttributeTargets.Method)] - public class NoAuthorityVerificationAttribute : Attribute - { - - } -} diff --git a/src/Destiny.Core.Flow/Reflection/AssemblyFinder.cs b/src/Destiny.Core.Flow/Reflection/AssemblyFinder.cs deleted file mode 100644 index 770f728a..00000000 --- a/src/Destiny.Core.Flow/Reflection/AssemblyFinder.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Reflection; - -namespace Destiny.Core.Flow.Reflection -{ - public class AssemblyFinder : FinderBase, IAssemblyFinder - { - protected override Assembly[] FindAllItems() - { - return AssemblyHelper.FindAllItems(); - } - } -} diff --git a/src/Destiny.Core.Flow/Reflection/AssemblyHelper.cs b/src/Destiny.Core.Flow/Reflection/AssemblyHelper.cs deleted file mode 100644 index f829848e..00000000 --- a/src/Destiny.Core.Flow/Reflection/AssemblyHelper.cs +++ /dev/null @@ -1,85 +0,0 @@ -using Microsoft.Extensions.DependencyModel; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.Loader; - -namespace Destiny.Core.Flow.Reflection -{ - public static class AssemblyHelper - { - - /// - /// 获取项目程序集,排除所有的系统程序集(Microsoft.***、System.***等)、Nuget下载包 - /// - /// - private static IList GetAllAssemblies() - { - - string[] filters = - { - "mscorlib", - "netstandard", - "dotnet", - "api-ms-win-core", - "runtime.", - "System", - "Microsoft", - "Window", - }; - List list = new List(); - var deps = DependencyContext.Default; - //排除所有的系统程序集、Nuget下载包 - var libs = deps.CompileLibraries.Where(lib => !lib.Serviceable && lib.Type != "package" && !filters.Any(lib.Name.StartsWith)); - - try - { - foreach (var lib in libs) - { - var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name)); - list.Add(assembly); - } - } - catch (Exception ex) - { - - throw ex; - } - - return list; - } - - public static Assembly[] FindAllItems() - { - return GetAllAssemblies().ToArray(); - } - /// - /// 根据程序集名字得到程序集 - /// - /// - /// - - public static IEnumerable GetAssembliesByName(params string[] assemblyNames) - { - var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath; //获取项目路径 - return assemblyNames.Select(o => AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(basePath, $"{o}.dll"))); - } - - //public static List LoadAssemblies(string folderPath, SearchOption searchOption) - //{ - // return GetAssemblyFiles(folderPath, searchOption) - // .Select(AssemblyLoadContext.Default.LoadFromAssemblyPath) - // .ToList(); - //} - - //public static IEnumerable GetAssemblyFiles(string folderPath, SearchOption searchOption) - //{ - // return Directory - // .EnumerateFiles(folderPath, "*.*", searchOption) - // .Where(s => s.EndsWith(".dll") || s.EndsWith(".exe")); - //} - - } -} diff --git a/src/Destiny.Core.Flow/Reflection/FinderBase.cs b/src/Destiny.Core.Flow/Reflection/FinderBase.cs deleted file mode 100644 index 4f7f8f3d..00000000 --- a/src/Destiny.Core.Flow/Reflection/FinderBase.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Linq; - -namespace Destiny.Core.Flow.Reflection -{ - public abstract class FinderBase : IFinder - { - private readonly object _syncObj = new object(); - public TItem[] Find(Func predicate) - { - return this.FindAll().Where(predicate).ToArray(); - } - - public TItem[] FindAll() - { - lock (_syncObj) - { - return this.FindAllItems(); - } - } - - protected abstract TItem[] FindAllItems(); - - - } -} diff --git a/src/Destiny.Core.Flow/Reflection/IAssemblyFinder.cs b/src/Destiny.Core.Flow/Reflection/IAssemblyFinder.cs deleted file mode 100644 index af94e5cc..00000000 --- a/src/Destiny.Core.Flow/Reflection/IAssemblyFinder.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Reflection; - -namespace Destiny.Core.Flow.Reflection -{ - public interface IAssemblyFinder : IFinder - { - - } -} diff --git a/src/Destiny.Core.Flow/Reflection/IFinder.cs b/src/Destiny.Core.Flow/Reflection/IFinder.cs deleted file mode 100644 index 6e9efe3c..00000000 --- a/src/Destiny.Core.Flow/Reflection/IFinder.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using System; - -namespace Destiny.Core.Flow.Reflection -{ - [IgnoreDependency] - public interface IFinder - { - TItem[] Find(Func predicate); - - - TItem[] FindAll(); - } -} diff --git a/src/Destiny.Core.Flow/Reflection/ITypeFinder.cs b/src/Destiny.Core.Flow/Reflection/ITypeFinder.cs deleted file mode 100644 index 284e3254..00000000 --- a/src/Destiny.Core.Flow/Reflection/ITypeFinder.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Reflection -{ - - public interface ITypeFinder - { - Type[] Find(Func predicate); - - Type[] FindAll(); - } -} diff --git a/src/Destiny.Core.Flow/Reflection/TypeFinder.cs b/src/Destiny.Core.Flow/Reflection/TypeFinder.cs deleted file mode 100644 index 6c1b7a6e..00000000 --- a/src/Destiny.Core.Flow/Reflection/TypeFinder.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Linq; - -namespace Destiny.Core.Flow.Reflection -{ - - public class TypeFinder : FinderBase, ITypeFinder - { - - private readonly IAssemblyFinder _assemblyFinder = null; - private readonly object _syncObj = new object(); - public TypeFinder(IAssemblyFinder assemblyFinder) - { - _assemblyFinder = assemblyFinder; - } - - protected override Type[] FindAllItems() - { - return _assemblyFinder.FindAll().SelectMany(o => o.GetTypes()).ToArray(); - } - } -} diff --git a/src/Destiny.Core.Flow/Security/Identity/ClaimTypes.cs b/src/Destiny.Core.Flow/Security/Identity/ClaimTypes.cs deleted file mode 100644 index 8c911d68..00000000 --- a/src/Destiny.Core.Flow/Security/Identity/ClaimTypes.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Destiny.Core.Flow.Security.Identity -{ - public static class DestinyCoreFlowClaimTypes - { - - public const string IsAdmin = "isAdmin"; - public const string UserName = "name"; - public const string RoleName = "rolename"; - public const string RoleId = "roleid"; - public const string NickName = "nikename"; - } -} diff --git a/src/Destiny.Core.Flow/Security/Identity/IdentityProfile.cs b/src/Destiny.Core.Flow/Security/Identity/IdentityProfile.cs deleted file mode 100644 index 8a3b7a38..00000000 --- a/src/Destiny.Core.Flow/Security/Identity/IdentityProfile.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Security.Identity -{ - public class IdentityProfile - { - public string UserName { get; set; } - - public string UserId { get; set; } - - public bool IsSystem { get; set; } - - public bool IsAdmin { get;set; } - - public string[] RoleIds { get; set; } - - - public string NickName { get; set; } - - - - - - - - } -} diff --git a/src/Destiny.Core.Flow/Security/Jwt/IJwtBearerService.cs b/src/Destiny.Core.Flow/Security/Jwt/IJwtBearerService.cs deleted file mode 100644 index 97f255df..00000000 --- a/src/Destiny.Core.Flow/Security/Jwt/IJwtBearerService.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Destiny.Core.Flow.Dependency; -using System; - -namespace Destiny.Core.Flow.Security.Jwt -{ - /// - /// JwtBearer服务 - /// - public interface IJwtBearerService: IScopedDependency - { - JwtResult CreateToken(Guid userId, string userName); - } -} diff --git a/src/Destiny.Core.Flow/Security/Jwt/JwtBearerService.cs b/src/Destiny.Core.Flow/Security/Jwt/JwtBearerService.cs deleted file mode 100644 index 64d6f3fd..00000000 --- a/src/Destiny.Core.Flow/Security/Jwt/JwtBearerService.cs +++ /dev/null @@ -1,80 +0,0 @@ -using Destiny.Core.Flow.Exceptions; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Options; -using Microsoft.IdentityModel.Tokens; -using System; -using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; -using System.Text; - -namespace Destiny.Core.Flow.Security.Jwt -{ - public class JwtBearerService : IJwtBearerService - { - private readonly IServiceProvider _provider = null; - private readonly JwtOptions _jwtOptions = null; - private readonly JwtSecurityTokenHandler _tokenHandler = new JwtSecurityTokenHandler(); - public JwtBearerService(IServiceProvider provider) - { - _provider = provider; - _jwtOptions = provider.GetAppSettings()?.Jwt; - } - - /// - /// 创建令牌 - /// - /// - /// - /// - public JwtResult CreateToken(Guid userId, string userName) - { - - Claim[] claims = - { - new Claim(ClaimTypes.NameIdentifier, userId.ToString()), - new Claim(ClaimTypes.Name, userName), - }; - var (token, accessExpires) = this.BuildJwtToken(claims, _jwtOptions); - - return new JwtResult() - { - AccessToken = token, - AccessExpires = accessExpires.UnixTicks().AsTo(), - claims = claims, - }; - } - - public (string, DateTime) BuildJwtToken(Claim[] claims, JwtOptions options) - { - - options.NotNull(nameof(options)); - claims.NotNull(nameof(claims)); - if (options.SecretKey.IsNullOrEmpty()) - { - throw new AppException("密钥不能为空!!"); - } - DateTime now = DateTime.UtcNow; - SecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.SecretKey)); - SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature); - double minutes = options.ExpireMins <= 0 ? 5 : options.ExpireMins; - - DateTime expires = now.AddMinutes(minutes); - - - SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor - { - Subject = new ClaimsIdentity(claims), - Audience = options.Audience ?? "Destiny", - Issuer = options.Issuer ?? "Destiny", - SigningCredentials = credentials, - NotBefore = now, - IssuedAt = now, - Expires = expires - }; - - - SecurityToken token = _tokenHandler.CreateToken(descriptor); - return (_tokenHandler.WriteToken(token), expires); - } - } -} diff --git a/src/Destiny.Core.Flow/Security/Jwt/JwtResult.cs b/src/Destiny.Core.Flow/Security/Jwt/JwtResult.cs deleted file mode 100644 index a1958de8..00000000 --- a/src/Destiny.Core.Flow/Security/Jwt/JwtResult.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Security.Claims; - -namespace Destiny.Core.Flow.Security.Jwt -{ - /// - /// JWT结果 - /// - public class JwtResult - { - - public string AccessToken { get; set; } - - - public long AccessExpires { get; set; } - - public Claim[] claims { get; set; } = new Claim[] { }; - - } -} diff --git a/src/Destiny.Core.Flow/Threading/AsyncEx.cs b/src/Destiny.Core.Flow/Threading/AsyncEx.cs deleted file mode 100644 index 0098ee18..00000000 --- a/src/Destiny.Core.Flow/Threading/AsyncEx.cs +++ /dev/null @@ -1,202 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Extensions -{ - /// - /// Task扩展 - /// - public static partial class Extensions - { - - /// - /// 处理Task异常(这种设计可能违反了非局部性原则) - /// - /// - /// - /// - /// - /// - public static Task Catch(this Task task, Func onError) where TError : Exception - { - var tcs = new TaskCompletionSource(); //TaskCompletionSource的实例返回一个Task类型以保持异步模型中的一致性 - task.ContinueWith(innerTask => - { - if (innerTask.IsFaulted && innerTask?.Exception?.InnerException is TError) - { - tcs.SetResult(onError((TError)innerTask.Exception.InnerException)); - } - else if (innerTask.IsCanceled) - { - tcs.SetCanceled(); - } - else if (innerTask.IsFaulted) - { - tcs.SetException(innerTask?.Exception?.InnerException ?? throw new InvalidOperationException()); - } - else - { - tcs.SetResult(innerTask.Result); - } - }); - return tcs.Task; - } - - /// - /// 异步循环 - /// - /// - /// 源 - /// 最大并行度值 - /// 主体 - /// - public static Task ForEachAsync(this IEnumerable source, int maxDegreeOfParallelism, Func body) - { - return Task.WhenAll( - from partition in Partitioner.Create(source).GetPartitions(maxDegreeOfParallelism) - select Task.Run(async () => - { - using (partition) - { - while (partition.MoveNext()) - await body(partition.Current); - } - })); - } - - /// - /// 异步循环 - /// - /// - /// - /// - /// - public static Task ForEachAsync(this IEnumerable source, Func body) - { - return source.ForEachAsync(Environment.ProcessorCount, body); - } - - public static Task Select(this Task task, Func projection) - { - var r = new TaskCompletionSource(); - task.ContinueWith(self => - { - if (self.IsFaulted) - { - r.SetException(self.Exception.InnerExceptions); - } - else if (self.IsCanceled) - { - r.SetCanceled(); - } - else - { - r.SetResult(projection(self.Result)); - } - }); - return r.Task; - } - - public static Task SelectMany(this Task first, Func> next) - { - var tcs = new TaskCompletionSource(); - first.ContinueWith(delegate - { - if (first.IsFaulted) - { - tcs.TrySetException(first.Exception.InnerExceptions); - } - else if (first.IsCanceled) - { - tcs.TrySetCanceled(); - } - else - { - try - { - var t = next(first.Result); - if (t == null) { - tcs.TrySetCanceled(); - } - else - t.ContinueWith(delegate - { - if (t.IsFaulted) - { - tcs.TrySetException(t.Exception.InnerExceptions); - } - else if (t.IsCanceled) - { - tcs.TrySetCanceled(); - } - else - { - tcs.TrySetResult(t.Result); - } - }, TaskContinuationOptions.ExecuteSynchronously); - } - catch (Exception exc) - { - tcs.TrySetException(exc); - } - } - }, TaskContinuationOptions.ExecuteSynchronously); - return tcs.Task; - } - - /// - /// 完成时处理 - /// - /// - /// - /// - public static IEnumerable> ProcessAsComplete(this IEnumerable> inputTasks) - { - // Copy the input so we know it’ll be stable, and we don’t evaluate it twice - var inputTaskList = inputTasks.ToList(); - // Could use Enumerable.Range here, if we wanted… - var completionSourceList = new List>(inputTaskList.Count); - for (var i = 0; i < inputTaskList.Count; i++) completionSourceList.Add(new TaskCompletionSource()); - - // At any one time, this is "the index of the box we’ve just filled". - // It would be nice to make it nextIndex and start with 0, but Interlocked.Increment - // returns the incremented value… - var prevIndex = -1; - - // We don’t have to create this outside the loop, but it makes it clearer - // that the continuation is the same for all tasks. - Action> continuation = completedTask => - { - var index = Interlocked.Increment(ref prevIndex); - var source = completionSourceList[index]; - switch (completedTask.Status) - { - case TaskStatus.Canceled: - source.TrySetCanceled(); - break; - case TaskStatus.Faulted: - source.TrySetException(completedTask.Exception.InnerExceptions); - break; - case TaskStatus.RanToCompletion: - source.TrySetResult(completedTask.Result); - break; - default: - throw new ArgumentException("Task was not completed"); - } - }; - - foreach (var inputTask in inputTaskList) - inputTask.ContinueWith(continuation, - CancellationToken.None, - TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); - - return completionSourceList.Select(source => source.Task); - } - } -} diff --git a/src/Destiny.Core.Flow/Threading/BackgroundTasks/BackgroundTaskQueue.cs b/src/Destiny.Core.Flow/Threading/BackgroundTasks/BackgroundTaskQueue.cs deleted file mode 100644 index 1d997f1d..00000000 --- a/src/Destiny.Core.Flow/Threading/BackgroundTasks/BackgroundTaskQueue.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Threading.BackgroundTasks -{ - internal sealed class BackgroundTaskQueue : IBackgroundTaskQueue - { - private readonly ConcurrentQueue> _workItems = - new ConcurrentQueue>(); - - private readonly SemaphoreSlim _signal = new SemaphoreSlim(0); - - public void QueueBackgroundWorkItem( - Func workItem) - { - if (workItem == null) - { - throw new ArgumentNullException(nameof(workItem)); - } - - _workItems.Enqueue(workItem); - _signal.Release(); - } - - public async Task> DequeueAsync( - CancellationToken cancellationToken) - { - await _signal.WaitAsync(cancellationToken); - _workItems.TryDequeue(out var workItem); - - return workItem; - } - } -} diff --git a/src/Destiny.Core.Flow/Threading/BackgroundTasks/IBackgroundTaskQueue.cs b/src/Destiny.Core.Flow/Threading/BackgroundTasks/IBackgroundTaskQueue.cs deleted file mode 100644 index 309a0138..00000000 --- a/src/Destiny.Core.Flow/Threading/BackgroundTasks/IBackgroundTaskQueue.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Threading.BackgroundTasks -{ - public interface IBackgroundTaskQueue - { - void QueueBackgroundWorkItem(Func workItem); - - Task> DequeueAsync( - CancellationToken cancellationToken); - } -} diff --git a/src/Destiny.Core.Flow/Threading/ObjectPoolAsync.cs b/src/Destiny.Core.Flow/Threading/ObjectPoolAsync.cs deleted file mode 100644 index 63efaae5..00000000 --- a/src/Destiny.Core.Flow/Threading/ObjectPoolAsync.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; - -namespace Destiny.Core.Flow.Threading -{ - /// - /// 使用TDF实现异步对象池 - /// - /// - public sealed class ObjectPoolAsync : IDisposable - { - //缓冲块 - private readonly BufferBlock buffer; - //工厂 - private readonly Func factory; - //超时 - private readonly int msecTimeout; - //当前大小 - private int currentSize; - - /// - /// - /// - /// 初始计数 - /// 工厂 - /// 传播应取消操作的通知 - /// 超时 - public ObjectPoolAsync(int initialCount, Func factory, CancellationToken? cts = null, int msecTimeout = 0) - { - this.msecTimeout = msecTimeout; - - var ctsToken = cts ?? new CancellationToken(); - ctsToken.Register(Dispose); - - //创建缓冲块 - buffer = new BufferBlock( - new DataflowBlockOptions { CancellationToken = ctsToken } //使用BufferBlock异步协调类型T的底层集合 - ); - this.factory = () => - { - Interlocked.Increment(ref currentSize); - return factory(); //使用工厂委托生成类型为T的新实例 - }; - for (var i = 0; i < initialCount; i++) - { - buffer.Post(this.factory()); //在对象池的初始化过种中,往缓冲区中镇充类型T的实例,以便从一开始就有对象可以使用 - } - } - - - /// - /// 大小 - /// - public int Size => currentSize; - - /// - /// 释放 - /// - public void Dispose() => buffer.Complete(); - - - /// - /// 可以将一个条目异步放入池中 - /// - /// - /// 当消费者完成后,会将对象类型T发送回对象池以进行循环利用 - public Task PutAsync(T item) => buffer.SendAsync(item); - - /// - /// 可以从池中异步获取一个条目 - /// - /// - /// 消费者发送出请求时,对象池将发送类型T对象 - public Task GetAsync(int timeout = 0) - { - var tcs = new TaskCompletionSource(); - buffer.ReceiveAsync(TimeSpan.FromMilliseconds(msecTimeout)) //异步接收 - .ContinueWith(task => - { - if (task.IsFaulted) - { - if (task.Exception.InnerException is TimeoutException) - { - tcs.SetResult(factory()); - } - else - { - tcs.SetException(task.Exception); - } - } - else if (task.IsCanceled) - { - tcs.SetCanceled(); - } - else - { - tcs.SetResult(task.Result); - } - }); - return tcs.Task; - } - } -} diff --git a/src/Destiny.Core.Flow/Threading/TaskResult.cs b/src/Destiny.Core.Flow/Threading/TaskResult.cs deleted file mode 100644 index 9e46fef0..00000000 --- a/src/Destiny.Core.Flow/Threading/TaskResult.cs +++ /dev/null @@ -1,207 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Threading -{ - - public struct TaskResult - { - public T Ok { get; } - public Exception Error { get; } - - public bool IsFailed => Error != null; - public bool IsOk => !IsFailed; - - public TaskResult(T ok) - { - Ok = ok; - Error = default; - } - - public TaskResult(Exception error) - { - Error = error; - Ok = default; - } - - public R Match(Func okMap, Func failureMap) - { - return IsOk ? okMap(Ok) : failureMap(Error); - } - - public void Match(Action okAction, Action errorAction) - { - if (IsOk) okAction(Ok); - else errorAction(Error); - } - - public static implicit operator TaskResult(T ok) - { - return new TaskResult(ok); - } - - public static implicit operator TaskResult(Exception error) - { - return new TaskResult(error); - } - - public static implicit operator TaskResult(TaskResult.Ok ok) - { - return new TaskResult(ok.Value); - } - - public static implicit operator TaskResult(TaskResult.Failure error) - { - return new TaskResult(error.Error); - } - } - - public static class TaskResult - { - public struct Ok - { - internal L Value { get; } - - internal Ok(L value) - { - Value = value; - } - } - - public struct Failure - { - internal Exception Error { get; } - - internal Failure(Exception error) - { - Error = error; - } - } - } - - - public static class ResultExtensions - { - public static TaskResult.Ok Ok(T value) - { - return new TaskResult.Ok(value); - } - - public static TaskResult.Failure Failure(Exception error) - { - return new TaskResult.Failure(error); - } - - public static async Task> TryCatch(Func> func) - { - try - { - return await func(); - } - catch (Exception ex) - { - return ex; - } - } - - public static Task> TryCatch(Func func) - { - return TryCatch(() => Task.FromResult(func())); - } - - public static async Task> SelectMany(this Task> resultTask, - Func>> func) - { - var result = await resultTask.ConfigureAwait(false); - if (result.IsFailed) - return result.Error; - return await func(result.Ok); - } - - public static async Task> Select(this Task> resultTask, Func> func) - { - var result = await resultTask.ConfigureAwait(false); - if (result.IsFailed) - return result.Error; - return await func(result.Ok).ConfigureAwait(false); - } - - public static async Task> Match(this Task> resultTask, Func> actionOk, - Func> actionError) - { - var result = await resultTask.ConfigureAwait(false); - if (result.IsFailed) - return await actionError(result.Error); - return await actionOk(result.Ok); - } - - - - public static async Task> OnSuccess(this Task> resultTask, Func> func) - { - var result = await resultTask.ConfigureAwait(false); - - if (result.IsFailed) - return result.Error; - return await func(result.Ok).ConfigureAwait(false); - } - - public static async Task> OnFailure(this Task> resultTask, Func func) - { - var result = await resultTask.ConfigureAwait(false); - - if (result.IsFailed) - await func().ConfigureAwait(false); - return result; - } - - public static async Task> Bind(this Task> resultTask, Func>> func) - { - var result = await resultTask.ConfigureAwait(false); - - if (result.IsFailed) - return result.Error; - return await func(result.Ok).ConfigureAwait(false); - } - - public static async Task> Map(this Task> resultTask, Func> func) - { - var result = await resultTask.ConfigureAwait(false); - - if (result.IsFailed) - return result.Error; - - return await TryCatch(() => func(result.Ok)); - } - - public static async Task> Match(this Task> resultTask, Func actionOk, - Func actionError) - { - var result = await resultTask.ConfigureAwait(false); - - if (result.IsFailed) - return actionError(result.Error); - return actionOk(result.Ok); - } - - public static async Task> Ensure(this Task> resultTask, Func> predicate, - string errorMessage) - { - var result = await resultTask.ConfigureAwait(false); - - if (result.IsFailed || !await predicate(result.Ok).ConfigureAwait(false)) return result.Error; - return result.Ok; - } - - public static async Task> Tap(this Task> resultTask, Func action) - { - var result = await resultTask.ConfigureAwait(false); - - if (result.IsOk) - await action(result.Ok).ConfigureAwait(false); - return result; - } - } -} diff --git a/src/Destiny.Core.Flow/Threading/ThreadSafeRandom.cs b/src/Destiny.Core.Flow/Threading/ThreadSafeRandom.cs deleted file mode 100644 index 5e705d1c..00000000 --- a/src/Destiny.Core.Flow/Threading/ThreadSafeRandom.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; - -namespace Destiny.Core.Flow.Threading -{ - /// - /// 线程安全随机数生成器 - /// - public class ThreadSafeRandom : Random - { - /// - /// 使用ThreadLocal类来创建一个线程安全的随机数生成器 - /// - private readonly ThreadLocal random = - new ThreadLocal(() => new Random(MakeRandomSeed())); - - public override int Next() - { - return random.Value.Next(); - } - - public override int Next(int maxValue) - { - return random.Value.Next(maxValue); - } - - public override int Next(int minValue, int maxValue) - { - return random.Value.Next(minValue, maxValue); - } - - public override double NextDouble() - { - return random.Value.NextDouble(); - } - - public override void NextBytes(byte[] buffer) - { - random.Value.NextBytes(buffer); - } - - //创建不依赖于系统时钟的种子。 - //每次调用都会创建一个唯一的值 - - private static int MakeRandomSeed() - { - return Guid.NewGuid().ToString().GetHashCode(); - } - } -} diff --git a/src/Destiny.Core.Flow/Ui/Abstracts/IHasResultType.cs b/src/Destiny.Core.Flow/Ui/Abstracts/IHasResultType.cs deleted file mode 100644 index f0d9c8a2..00000000 --- a/src/Destiny.Core.Flow/Ui/Abstracts/IHasResultType.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace Destiny.Core.Flow.Ui -{ - /// - /// 结果类型枚举 - /// - /// - public interface IHasResultType where IType : Enum - { - IType Type { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Ui/Abstracts/IListResult.cs b/src/Destiny.Core.Flow/Ui/Abstracts/IListResult.cs deleted file mode 100644 index 4edc3fb5..00000000 --- a/src/Destiny.Core.Flow/Ui/Abstracts/IListResult.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Ui -{ - public interface IListResult : IResultBase - { - IReadOnlyList ItemList { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Ui/Abstracts/ITreeResult.cs b/src/Destiny.Core.Flow/Ui/Abstracts/ITreeResult.cs deleted file mode 100644 index e0f89f86..00000000 --- a/src/Destiny.Core.Flow/Ui/Abstracts/ITreeResult.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Ui.Abstracts -{ - /// - /// 接口树型结果 - /// - /// - public interface ITreeResult : IResultBase, IListResult - { - - - - } - - - public interface ITreeResult : IResultBase, IListResult - { - IReadOnlyList SelectedList { get; set; } - - } - - - -} diff --git a/src/Destiny.Core.Flow/Ui/AuthorizationResult.cs b/src/Destiny.Core.Flow/Ui/AuthorizationResult.cs deleted file mode 100644 index 2d16622d..00000000 --- a/src/Destiny.Core.Flow/Ui/AuthorizationResult.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Extensions; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Destiny.Core.Flow.Ui -{ - public class AuthorizationResult : ResultBase, IHasResultType - { - - /// - /// 是否成功 - /// - public override bool Success => Type == AuthResultType.Success; - - /// - /// 类型 - /// - public AuthResultType Type { get; set; } - - - public static AuthorizationResult Unauthorized() - { - - return new AuthorizationResult() { - Message = AuthResultType.Unauthorized.ToDescription(), - Type= AuthResultType.Unauthorized - }; - } - } -} diff --git a/src/Destiny.Core.Flow/Ui/MessageDefinitionType.cs b/src/Destiny.Core.Flow/Ui/MessageDefinitionType.cs deleted file mode 100644 index a62b9e6b..00000000 --- a/src/Destiny.Core.Flow/Ui/MessageDefinitionType.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Destiny.Core.Flow.Ui -{ - /// - /// 返回消息定义 - /// - public static class MessageDefinitionType - { - public const string LoadSucces = "加载成功"; - public const string DataSuccess = "得到数据成功"; - public const string Unauthorized = "未经授权"; - public const string Uncertified = "当前用户权限不足"; - - - } -} diff --git a/src/Destiny.Core.Flow/Ui/OperationResponse.cs b/src/Destiny.Core.Flow/Ui/OperationResponse.cs deleted file mode 100644 index 592301c6..00000000 --- a/src/Destiny.Core.Flow/Ui/OperationResponse.cs +++ /dev/null @@ -1,98 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Filter; - -namespace Destiny.Core.Flow.Ui -{ - /// - /// 有重复代码想办法解决。。 - /// - public class OperationResponse : ResultBase, IHasResultType - { - - public OperationResponse() : this(OperationResponseType.Success) - { - - - } - public OperationResponse(OperationResponseType type = OperationResponseType.Success) : this("", null, type) - { - - - } - public OperationResponse(string message, OperationResponseType type) : this(message, null, type) - { - - - } - public OperationResponse(string message, object data, OperationResponseType type) - { - Message = message; - Type = type; - Data = data; - - } - - - - - - public virtual OperationResponseType Type { get; set; } - - - public override bool Success => Type == OperationResponseType.Success; - /// - /// 成功 - /// - public static OperationResponse Ok() - { - return Ok(string.Empty, null); - } - /// - /// 成功 - /// - /// 提示消息 - public static OperationResponse Ok(string message) - { - return Ok(message, null); - } - - /// - /// 成功 - /// - /// 返回成功数据 - /// - public static OperationResponse Ok(object data) - { - return Ok(string.Empty, data); - } - - /// - /// 成功 - /// - /// 提示消息 - /// 返回成功数据 - /// - public static OperationResponse Ok(string message, object data) - { - - return new OperationResponse(message, data, OperationResponseType.Success); - } - - - - public static OperationResponse Error(string message) - { - return Error(message, null); - } - public static OperationResponse Error(object data) - { - return Error(string.Empty, data); - } - public static OperationResponse Error(string message, object data) - { - - return new OperationResponse(message, data, OperationResponseType.Error); - } - - } -} diff --git a/src/Destiny.Core.Flow/Ui/OperationResponseExtensions.cs b/src/Destiny.Core.Flow/Ui/OperationResponseExtensions.cs deleted file mode 100644 index 64b9e541..00000000 --- a/src/Destiny.Core.Flow/Ui/OperationResponseExtensions.cs +++ /dev/null @@ -1,117 +0,0 @@ -using Destiny.Core.Flow.Enums; - -namespace Destiny.Core.Flow.Ui -{ - public static class OperationResponseExtensions - { - - /// - /// 成功 - /// - public static OperationResponse Ok(this OperationResponse operation) - { - return operation.Ok(string.Empty, default(TData)); - } - /// - /// 成功 - /// - /// 提示消息 - public static OperationResponse Ok(this OperationResponse operation, string message) - { - return operation.Ok(message, default(TData)); - } - - /// - /// 成功 - /// - /// 返回成功数据 - /// - public static OperationResponse Ok(this OperationResponse operation, TData data) - { - return operation.Ok(string.Empty, data); - } - - /// - /// 成功 - /// - /// 提示消息 - /// 返回成功数据 - /// - public static OperationResponse Ok(this OperationResponse operation, string message, TData data) - { - - return new OperationResponse(message, data, OperationResponseType.Success); - } - - - - public static OperationResponse Error(this OperationResponse operation, string message) - { - return operation.Error(message, default(TData)); - } - public static OperationResponse Error(this OperationResponse operation, TData data) - { - return operation.Error(string.Empty, data); - } - public static OperationResponse Error(this OperationResponse operation, string message, TData data) - { - - return new OperationResponse(message, data, OperationResponseType.Error); - } - - - /// - /// 成功 - /// - public static OperationResponse Ok(this OperationResponse response) - { - return response.Ok(string.Empty, null); - } - /// - /// 成功 - /// - /// 提示消息 - public static OperationResponse Ok(this OperationResponse response, string message) - { - return response.Ok(message, null); - } - - /// - /// 成功 - /// - /// 返回成功数据 - /// - public static OperationResponse Ok(this OperationResponse response, object data) - { - return response.Ok(string.Empty, data); - } - - /// - /// 成功 - /// - /// 提示消息 - /// 返回成功数据 - /// - public static OperationResponse Ok(this OperationResponse response, string message, object data) - { - - return new OperationResponse(message, data, OperationResponseType.Success); - } - - - - public static OperationResponse Error(this OperationResponse response, string message) - { - return response.Error(message, null); - } - public static OperationResponse Error(this OperationResponse response, object data) - { - return response.Error(string.Empty, data); - } - public static OperationResponse Error(this OperationResponse response, string message, object data) - { - - return new OperationResponse(message, data, OperationResponseType.Error); - } - } -} diff --git a/src/Destiny.Core.Flow/Ui/OperationResponseOfModel.cs b/src/Destiny.Core.Flow/Ui/OperationResponseOfModel.cs deleted file mode 100644 index c97476bd..00000000 --- a/src/Destiny.Core.Flow/Ui/OperationResponseOfModel.cs +++ /dev/null @@ -1,109 +0,0 @@ -using Destiny.Core.Flow.Enums; -using Destiny.Core.Flow.Filter; - -namespace Destiny.Core.Flow.Ui -{ - /// - /// 有重复代码想办法解决。。 - /// - public class OperationResponse : ResultBase, IHasResultType - { - - public OperationResponse() : this(OperationResponseType.Success) - { - - - } - public OperationResponse(OperationResponseType type = OperationResponseType.Success) : this("", default(TData), type) - { - - - } - public OperationResponse(string message, OperationResponseType type) : this(message, default(TData), type) - { - - - } - public OperationResponse(string message, TData data, OperationResponseType type) - { - Message = message; - Type = type; - Data = data; - - } - - - - - - public virtual OperationResponseType Type { get; set; } - - - public override bool Success => Type == OperationResponseType.Success; - - - - /// - /// 成功 - /// - public static OperationResponse Ok() - { - return Ok(string.Empty, default(TData)); - } - /// - /// 成功 - /// - /// 提示消息 - public static OperationResponse Ok(string message) - { - return Ok(message, default(TData)); - } - - /// - /// 成功 - /// - /// 返回成功数据 - /// - public static OperationResponse Ok(TData data) - { - return Ok(string.Empty, data); - } - - /// - /// 成功 - /// - /// 提示消息 - /// 返回成功数据 - /// - public static OperationResponse Ok(string message, TData data) - { - - return new OperationResponse(message, data, OperationResponseType.Success); - } - - - - public static OperationResponse Error(string message) - { - return Error(message, default(TData)); - } - public static OperationResponse Error(TData data) - { - return Error(string.Empty, data); - } - public static OperationResponse Error(string message, TData data) - { - - return new OperationResponse(message, data, OperationResponseType.Error); - } - - - - - public bool Exp() - { - return Type == OperationResponseType.Exp; - } - - } -} diff --git a/src/Destiny.Core.Flow/Ui/ResultBase.cs b/src/Destiny.Core.Flow/Ui/ResultBase.cs deleted file mode 100644 index 5efb9f81..00000000 --- a/src/Destiny.Core.Flow/Ui/ResultBase.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace Destiny.Core.Flow.Ui -{ - /// - /// 所有结果返回基类 - /// - public abstract class ResultBase : IResultBase - { - - /// - /// 是否成功 - /// - - - public virtual bool Success { get; set; } - - /// - /// 消息 - /// - public virtual string Message { get; set; } - - - } - - - public interface IResultBase - { - bool Success { get; set; } - - - string Message { get; set; } - } -} diff --git a/src/Destiny.Core.Flow/Ui/TreeResult.cs b/src/Destiny.Core.Flow/Ui/TreeResult.cs deleted file mode 100644 index df772dd9..00000000 --- a/src/Destiny.Core.Flow/Ui/TreeResult.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Destiny.Core.Flow.Ui.Abstracts; -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Ui -{ - /// - /// 树返回 - /// - public class TreeResult : ResultBase, ITreeResult - { - public TreeResult() : this(new TData[0], "成功返回数据", true) - { - - } - public TreeResult(IReadOnlyList itemList, string message = "成功返回数据", bool success = true) - { - ItemList = itemList; - Message = message; - Success = success; - } - - public IReadOnlyList ItemList { get; set; } - - } - - - public class TreeResult : TreeResult, ITreeResult - { - - - public TreeResult() : this(new TData[0], "成功返回数据", true) - { - - } - public TreeResult(IReadOnlyList itemList, string message = "成功返回数据", bool success = true) - { - ItemList = itemList; - Message = message; - Success = success; - } - - public TreeResult(IReadOnlyList itemList, IReadOnlyList selectedList, string message = "成功返回数据", bool success = true) - { - ItemList = itemList; - Message = message; - Success = success; - SelectedList = selectedList; - } - - public IReadOnlyList SelectedList { get; set; } - - } -} diff --git a/src/Destiny.Core.Flow/Validation/Extensions.cs b/src/Destiny.Core.Flow/Validation/Extensions.cs deleted file mode 100644 index 3f8a9e2e..00000000 --- a/src/Destiny.Core.Flow/Validation/Extensions.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Destiny.Core.Flow.Validation.Interceptor; -using Microsoft.Extensions.DependencyInjection; - -namespace Destiny.Core.Flow.Validation -{ - public static partial class Extensions - { - - public static IServiceCollection WithModelValidation(this IServiceCollection services) - { - services.AddTransient(); - services.AddTransient(); - return services; - } - } -} diff --git a/src/Destiny.Core.Flow/Validation/IModelValidator.cs b/src/Destiny.Core.Flow/Validation/IModelValidator.cs deleted file mode 100644 index 9b2a8c9f..00000000 --- a/src/Destiny.Core.Flow/Validation/IModelValidator.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Validation -{ - - public interface IModelValidator : IModelValidator - { - - IEnumerable Validate(TModel model); - } - /// - /// 模型验证器 - /// - public interface IModelValidator - { - /// - /// 同步验证指定的实例 - /// 包含验证逻辑和业务规则验证 - /// - /// 要验证的模型 - /// - - /// - IEnumerable Validate(object model); - - bool CanValidateInstancesOfType(Type type); - } -} diff --git a/src/Destiny.Core.Flow/Validation/Interceptor/IMethodParameterValidator.cs b/src/Destiny.Core.Flow/Validation/Interceptor/IMethodParameterValidator.cs deleted file mode 100644 index 8fcaebc9..00000000 --- a/src/Destiny.Core.Flow/Validation/Interceptor/IMethodParameterValidator.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Collections.Generic; - -namespace Destiny.Core.Flow.Validation.Interceptor -{ - public interface IMethodParameterValidator - { - IEnumerable Validate(object parameter); - } -} diff --git a/src/Destiny.Core.Flow/Validation/Interceptor/MethodInvocationValidator.cs b/src/Destiny.Core.Flow/Validation/Interceptor/MethodInvocationValidator.cs deleted file mode 100644 index ce4e378a..00000000 --- a/src/Destiny.Core.Flow/Validation/Interceptor/MethodInvocationValidator.cs +++ /dev/null @@ -1,140 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Reflection; - -namespace Destiny.Core.Flow.Validation.Interceptor -{ - public class MethodInvocationValidator - { - private const int MaxRecursiveParameterValidationDepth = 8; - - private readonly IEnumerable _validators; - private readonly IList _failures; - - public MethodInvocationValidator( - - IEnumerable validators) - { - - _validators = validators ?? throw new ArgumentNullException(nameof(validators)); - - _failures = new List(); - } - - public IEnumerable Validate(MethodInfo method, object[] parameterValues) - { - method.NotNull(nameof(method)); - method.NotNull(nameof(parameterValues)); - - - - var parameters = method.GetParameters(); - - if (parameters.Length != parameterValues.Length) - { - throw new Exception("方法参数计数与参数计数不匹配!"); - } - - for (var i = 0; i < parameters.Length; i++) - { - ValidateMethodParameter(parameters[i], parameterValues[i]); - } - - return _failures; - } - - private void ValidateMethodParameter(ParameterInfo parameterInfo, object parameterValue) - { - if (parameterValue == null) - { - if (!parameterInfo.IsOptional && - !parameterInfo.IsOut && - !parameterInfo.ParameterType.IsPrimitiveExtendedIncludingNullable(true)) - { - _failures.Add(new ValidationFailure(parameterInfo.Name, parameterInfo.Name + " 为空!")); - } - - return; - } - - ValidateObjectRecursively(parameterValue, 1); - } - - private void ValidateObjectRecursively(object validatingObject, int depth) - { - if (depth > MaxRecursiveParameterValidationDepth) - { - return; - } - - if (validatingObject == null) - { - return; - } - - - - if (validatingObject.GetType().IsPrimitiveExtendedIncludingNullable()) - { - return; - } - - SetValidationErrors(validatingObject); - - // 验证可枚举项 - if (IsEnumerable(validatingObject)) - { - foreach (var item in (IEnumerable)validatingObject) - { - ValidateObjectRecursively(item, depth + 1); - } - } - - if (!ShouldMakeDeepValidation(validatingObject)) return; - - var properties = TypeDescriptor.GetProperties(validatingObject).Cast(); - foreach (var property in properties) - { - - - ValidateObjectRecursively(property.GetValue(validatingObject), depth + 1); - } - } - - private void SetValidationErrors(object parameter) - { - foreach (var validator in _validators) - { - var failures = validator.Validate(parameter); - _failures.AddRange(failures); - } - } - private static bool ShouldMakeDeepValidation(object validatingObject) - { - // 不递归验证可枚举对象 - if (validatingObject is IEnumerable) - { - return false; - } - - var validatingObjectType = validatingObject.GetType(); - - // 不递归验证基元对象 - return !validatingObjectType.IsPrimitiveExtendedIncludingNullable(); - } - - - private static bool IsEnumerable(object validatingObject) - { - return - validatingObject is IEnumerable && - !(validatingObject is IQueryable) && - !validatingObject.GetType().IsPrimitiveExtendedIncludingNullable(); - } - - } -} diff --git a/src/Destiny.Core.Flow/Validation/Interceptor/ModelValidationMethodParameterValidator.cs b/src/Destiny.Core.Flow/Validation/Interceptor/ModelValidationMethodParameterValidator.cs deleted file mode 100644 index da4fc072..00000000 --- a/src/Destiny.Core.Flow/Validation/Interceptor/ModelValidationMethodParameterValidator.cs +++ /dev/null @@ -1,34 +0,0 @@ - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Destiny.Core.Flow.Validation.Interceptor -{ - internal sealed class ModelValidationMethodParameterValidator : IMethodParameterValidator - { - private readonly IServiceProvider _provider; - - public ModelValidationMethodParameterValidator(IServiceProvider provider) - { - _provider = provider ?? throw new ArgumentNullException(nameof(provider)); - } - - public IEnumerable Validate(object parameter) - { - if (parameter == null) - { - return Enumerable.Empty(); - } - - var validatorType = typeof(IModelValidator<>).MakeGenericType(parameter.GetType()); - - if (!(_provider.GetService(validatorType) is IModelValidator validator)) - return Enumerable.Empty(); - - var failures = validator.Validate(parameter); - - return failures; - } - } -} diff --git a/src/Destiny.Core.Flow/Validation/Interceptor/ValidationInterceptorAttribute.cs b/src/Destiny.Core.Flow/Validation/Interceptor/ValidationInterceptorAttribute.cs deleted file mode 100644 index 03e2ba50..00000000 --- a/src/Destiny.Core.Flow/Validation/Interceptor/ValidationInterceptorAttribute.cs +++ /dev/null @@ -1,73 +0,0 @@ -using AspectCore.DynamicProxy; -using Destiny.Core.Flow.Extensions; -using Destiny.Core.Flow.Ui; -using Destiny.Core.Flow.Validation.Interceptor; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Threading.Tasks; - -namespace Destiny.Core.Flow.Validation -{ - public sealed class ValidationInterceptorAttribute : AbstractInterceptorAttribute - { - public override async Task Invoke(AspectContext context, AspectDelegate next) - { - var validator = (MethodInvocationValidator)context.ServiceProvider.GetService(typeof(MethodInvocationValidator)); - - MethodInfo method; - try - { - - method = context.ImplementationMethod; - } - catch - { - method = context.ServiceMethod; - } - var failures = validator.Validate(method, context.Parameters); - - var result = failures.ToResult(); - if (result.Success) - { - await next(context); - return; - } - - if (context.IsAsync()) - { - if (context.ImplementationMethod.ReturnType == typeof(Task)) - { - ThrowValidationException(result); - //throw new Exception(result.Data.Select(o=>o.Message).ToJoin()); - } - else - { - var returnType = context.ImplementationMethod.ReturnType.GenericTypeArguments[0]; - if (typeof(IResultBase).IsAssignableFrom(returnType)) - { - context.ReturnValue = Task.FromResult(new OperationResponse() - { - - Message = result.Message.IsNullOrEmpty() ? result.Data.Select(o => o.Message).ToJoin() : result.Message, - Type = Enums.OperationResponseType.Error - }); - - } - else - { - ThrowValidationException(result); - } - //ThrowValidationException(result); - } - } - - } - - private static void ThrowValidationException(OperationResponse> result) - { - - throw new ValidationException(result.Message, result.Data); - } - } -} diff --git a/src/Destiny.Core.Flow/Validation/ModelValidationResultExtensions.cs b/src/Destiny.Core.Flow/Validation/ModelValidationResultExtensions.cs deleted file mode 100644 index b10e6234..00000000 --- a/src/Destiny.Core.Flow/Validation/ModelValidationResultExtensions.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Destiny.Core.Flow.Ui; -using System.Collections.Generic; -using System.Linq; - -namespace Destiny.Core.Flow.Validation -{ - public static class ModelValidationResultExtensions - { - public static OperationResponse> ToResult(this IEnumerable failures) - { - - failures = failures as ValidationFailure[] ?? failures.ToArray(); - return !failures.Any() ? new OperationResponse>() : new OperationResponse>(Enums.OperationResponseType.Error) { Data = failures }; - } - } -} diff --git a/src/Destiny.Core.Flow/Validation/ModelValidator.cs b/src/Destiny.Core.Flow/Validation/ModelValidator.cs deleted file mode 100644 index 646752fe..00000000 --- a/src/Destiny.Core.Flow/Validation/ModelValidator.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Destiny.Core.Flow.Extensions; -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace Destiny.Core.Flow.Validation -{ - public abstract class ModelValidator : IModelValidator - { - IEnumerable IModelValidator.Validate(object model) - { - - model.NotNull(nameof(model)); - if (!((IModelValidator)this).CanValidateInstancesOfType(model.GetType())) - { - throw new InvalidOperationException( - $"无法验证类型的实例 '{model.GetType().GetTypeInfo().Name}'. 此验证器只能验证类型为 '{typeof(TModel).Name}'."); - } - - return Validate((TModel)model); - } - - bool IModelValidator.CanValidateInstancesOfType(Type type) - { - return typeof(TModel).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()); - } - - public abstract IEnumerable Validate(TModel model); - } -} diff --git a/src/Destiny.Core.Flow/Validation/ValidationException.cs b/src/Destiny.Core.Flow/Validation/ValidationException.cs deleted file mode 100644 index 89a0f051..00000000 --- a/src/Destiny.Core.Flow/Validation/ValidationException.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Destiny.Core.Flow.Exceptions; -using System; -using System.Collections.Generic; -using System.Linq; -namespace Destiny.Core.Flow.Validation -{ - [Serializable] - public class ValidationException : AppException - { - public IReadOnlyList Failures { get; } - - public ValidationException(string message) : this(message, Enumerable.Empty()) - { - } - - public ValidationException(string message, IEnumerable failures) : base(message) - { - Failures = failures.ToList(); - } - } -} diff --git a/src/Destiny.Core.Flow/Validation/ValidationFailure.cs b/src/Destiny.Core.Flow/Validation/ValidationFailure.cs deleted file mode 100644 index d3b642d6..00000000 --- a/src/Destiny.Core.Flow/Validation/ValidationFailure.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace Destiny.Core.Flow.Validation -{ - public class ValidationFailure - { - public ValidationFailure(string memberName, string message) - { - MemberName = memberName ?? string.Empty; - Message = message ?? string.Empty; - } - - public string MemberName { get; } - public string Message { get; } - - public override string ToString() - { - return $"[{MemberName}: {Message}]"; - } - } -} diff --git a/Destiny.Core.Tests/CodeGeneratorTests.cs b/test/Destiny.Core.Tests/CodeGeneratorTests.cs similarity index 100% rename from Destiny.Core.Tests/CodeGeneratorTests.cs rename to test/Destiny.Core.Tests/CodeGeneratorTests.cs diff --git a/Destiny.Core.Tests/Destiny.Core.Tests.csproj b/test/Destiny.Core.Tests/Destiny.Core.Tests.csproj similarity index 76% rename from Destiny.Core.Tests/Destiny.Core.Tests.csproj rename to test/Destiny.Core.Tests/Destiny.Core.Tests.csproj index cd53bb23..4cb8a7d6 100644 --- a/Destiny.Core.Tests/Destiny.Core.Tests.csproj +++ b/test/Destiny.Core.Tests/Destiny.Core.Tests.csproj @@ -30,6 +30,11 @@ + + + + + @@ -47,13 +52,8 @@ - - - - - + - diff --git a/Destiny.Core.Tests/MemoryTests.cs b/test/Destiny.Core.Tests/MemoryTests.cs similarity index 100% rename from Destiny.Core.Tests/MemoryTests.cs rename to test/Destiny.Core.Tests/MemoryTests.cs diff --git a/Destiny.Core.Tests/MongoDBTests.cs b/test/Destiny.Core.Tests/MongoDBTests.cs similarity index 95% rename from Destiny.Core.Tests/MongoDBTests.cs rename to test/Destiny.Core.Tests/MongoDBTests.cs index 54c360f2..65114618 100644 --- a/Destiny.Core.Tests/MongoDBTests.cs +++ b/test/Destiny.Core.Tests/MongoDBTests.cs @@ -1,4 +1,5 @@ using Destiny.Core.Flow; +using Destiny.Core.Flow.API.Controllers; using Destiny.Core.Flow.Entity; using Destiny.Core.Flow.ExpressionUtil; using Destiny.Core.Flow.Extensions; @@ -29,6 +30,7 @@ public class MongoDBTests : IntegratedTest { private readonly IMongoDBRepository _mongoDBRepository = null; + private readonly AuditEntryController _auditEntryController; public MongoDBTests() { _mongoDBRepository = ServiceProvider.GetService>(); @@ -38,17 +40,15 @@ public MongoDBTests() // cm.MapProperty(o => o.Name); // cm.ToCollection("Test001"); //}); + _auditEntryController = ServiceProvider.GetRequiredService(); } - - [Fact] - public async Task InsertEntityAsync_Test() { - + var request = await _auditEntryController.GetAuditEntryPageAsync(new PageRequest()); for (int i = 0; i < 100; i++) { TestDB test = new TestDB(); @@ -62,10 +62,6 @@ public async Task InsertEntityAsync_Test() var count = await _mongoDBRepository.Entities.CountAsync(); Assert.True(count > 0); } - - - - [Fact] public async Task GetPageAsync_Test() { @@ -96,9 +92,6 @@ public async Task GetPageAsync_Test() Assert.True(page1.ItemList.Count == 10); } - - - [Fact] public async Task UpdateAsync_Test() { @@ -122,7 +115,6 @@ public async Task UpdateAsync_Test() } } } - public class PagedRequest : IPagedRequest { @@ -136,7 +128,6 @@ public PagedRequest() public int PageSize { get; set; } public OrderCondition[] OrderConditions { get; set; } } - public class MongoDBModelule : MongoDBModuleBase { @@ -166,8 +157,8 @@ public class MongoDBModelule : MongoDBModuleBase protected override void AddDbContext(IServiceCollection services) { var builder = new ConfigurationBuilder(); + services.AddScoped(); var configuration = builder.AddJsonFile("appsettings.json").Build(); - var dbpath = configuration["Destiny:DbContext:MongoDBConnectionString"]; var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath; //获取项目路径 var dbcontext = Path.Combine(basePath, dbpath); @@ -176,9 +167,6 @@ protected override void AddDbContext(IServiceCollection services) throw new Exception("未找到存放数据库链接的文件"); } var connection = File.ReadAllText(dbcontext).Trim(); - - - services.AddMongoDbContext(options => { options.ConnectionString = connection; @@ -186,25 +174,14 @@ protected override void AddDbContext(IServiceCollection services) } } - - public class TestMongoDbContext : MongoDbContextBase { - public TestMongoDbContext(MongoDbContextOptions options) : base(options) { } - - } - - - - - [MongoDBTable("TestDB")]// - public class TestDB : MongoEntity, IFullAuditedEntity { @@ -243,15 +220,12 @@ public class TestDB : MongoEntity, IFullAuditedEntity } - - public class TestDto { public ObjectId Id { get; set; } public string Name { get; set; } } - public static partial class Extensions { @@ -271,7 +245,6 @@ public static string GetBsonClassCollection(Type type) } } - public class Test001 { diff --git a/Destiny.Core.Tests/StartupModulesTest.cs b/test/Destiny.Core.Tests/StartupModulesTest.cs similarity index 100% rename from Destiny.Core.Tests/StartupModulesTest.cs rename to test/Destiny.Core.Tests/StartupModulesTest.cs diff --git a/Destiny.Core.Tests/appsettings.json b/test/Destiny.Core.Tests/appsettings.json similarity index 100% rename from Destiny.Core.Tests/appsettings.json rename to test/Destiny.Core.Tests/appsettings.json