From 848cffedb144a16c674891cde6232eec61dd2bfa Mon Sep 17 00:00:00 2001 From: Thang Chung Date: Sat, 11 Aug 2018 16:03:01 +0700 Subject: [PATCH] clean up #9 --- coolstore.sln | 58 ----- src/framework/VND.Fw.Domain/CoreException.cs | 33 --- src/framework/VND.Fw.Domain/Criterion.cs | 76 ------- src/framework/VND.Fw.Domain/EntityBase.cs | 97 -------- src/framework/VND.Fw.Domain/IDomainEvent.cs | 10 - src/framework/VND.Fw.Domain/IIdentity.cs | 9 - .../VND.Fw.Domain/IRepositoryAsync.cs | 27 --- .../VND.Fw.Domain/IUnitOfWorkAsync.cs | 16 -- src/framework/VND.Fw.Domain/IdentityBase.cs | 44 ---- src/framework/VND.Fw.Domain/PaginatedItem.cs | 27 --- .../VND.Fw.Domain/VND.Fw.Domain.csproj | 17 -- .../VND.Fw.Domain/ValueObjectBase.cs | 25 -- .../EventAggregatorExtensions.cs | 20 -- .../IEventHandler.cs | 53 ----- .../PresenterExtensions.cs | 19 -- ...Infrastructure.AspNetCore.CleanArch.csproj | 18 -- .../Configurator.cs | 26 --- .../AuthNConfigureApplication.cs | 20 -- .../BasePathConfigureApplication.cs | 27 --- .../CorsConfigureApplication.cs | 13 -- .../ForwardedHeadersConfigureApplication.cs | 20 -- .../HealthCheckConfigureApplication.cs | 15 -- .../LoggerConfigureApplication.cs | 23 -- .../MvcConfigureApplication.cs | 13 -- .../OpenApiConfigureApplication.cs | 55 ----- .../ProblemDetailsConfigureApplication.cs | 77 ------- .../ApiVersionConfigureService.cs | 70 ------ .../AuthNConfigureService.cs | 57 ----- .../CleanArchConfigureService.cs | 28 --- .../ConfigureServices/CorsConfigureService.cs | 21 -- .../DatabaseConfigureService.cs | 45 ---- .../FowardedHeadersConfigureService.cs | 26 --- .../ConfigureServices/HttpConfigureService.cs | 23 -- .../ConfigureServices/MvcConfigureService.cs | 17 -- .../OpenApiConfigureService.cs | 103 --------- .../ProblemDetailsConfigureService.cs | 19 -- .../MiniServiceExtensions.cs | 44 ---- .../Options/PersistenceOption.cs | 8 - .../ServiceCollectionExtensions.cs | 23 -- .../ServiceParams.cs | 8 - .../ServiceProviderExtensions.cs | 18 -- ...frastructure.AspNetCore.Miniservice.csproj | 40 ---- .../AuthorizeCheckOperationFilter.cs | 30 --- .../DefaultValuesOperationFilter.cs | 42 ---- .../OpenApiOptions.cs | 13 -- .../SecurityRequirementsOperationFilter.cs | 33 --- ...w.Infrastructure.AspNetCore.OpenApi.csproj | 21 -- .../index.html | 100 -------- .../AuthAttribute.cs | 14 -- .../ControllerBase.cs | 84 ------- .../Extensions/ApiExtensions.cs | 95 -------- .../Extensions/CriterionExtensions.cs | 36 --- .../Extensions/HostUriExtensions.cs | 50 ---- .../Extensions/HttpRequestExtensions.cs | 30 --- .../Extensions/HttpResponseExtensions.cs | 30 --- .../Extensions/ServiceCollectionExtensions.cs | 38 ---- .../LinkItem.cs | 16 -- .../Middlewares/ErrorHandlerMiddleware.cs | 55 ----- .../Middlewares/LogHandlerMiddleware.cs | 30 --- .../ModelBase.cs | 26 --- .../ProxyService.cs | 12 - .../RestClient.cs | 127 ----------- .../VND.FW.Infrastructure.AspNetCore.csproj | 45 ---- .../Validation/ValidationError.cs | 8 - .../Validation/ValidationProblemDetails.cs | 10 - .../ValidationProblemDetailsResult.cs | 55 ----- .../Options/MsSqlDbOptions.cs | 11 - .../ServiceCollectionExtensions.cs | 23 -- ...qlServerDatabaseConnectionStringFactory.cs | 37 --- ...SqlServerDbContextOptionsBuilderFactory.cs | 27 --- ....Fw.Infrastructure.EfCore.SqlServer.csproj | 17 -- .../Db/ApplicationDbContext.cs | 73 ------ .../Db/ICustomModelBuilder.cs | 9 - .../Db/IDatabaseConnectionStringFactory.cs | 7 - .../Db/IExtendDbContextOptionsBuilder.cs | 12 - .../Extensions/DbContextExtensions.cs | 23 -- .../Extensions/EfRepositoryExtensions.cs | 148 ------------ .../Extensions/OrderByExtension.cs | 45 ---- .../QueryRepositoryFactoryExtensions.cs | 14 -- .../Extensions/ServiceCollectionExtensions.cs | 80 ------- .../Extensions/WebHostExtensions.cs | 88 ------- .../Identity/ApplicationRole.cs | 9 - .../Identity/ApplicationUser.cs | 21 -- .../Migration/ISeedData.cs | 16 -- .../Migration/SeedDataBase.cs | 20 -- .../Repository/EfRepository.cs | 87 ------- .../Repository/EfUnitOfWork.cs | 61 ----- .../Repository/IEfRepository.cs | 27 --- .../VND.Fw.Infrastructure.EfCore.csproj | 20 -- .../Extensions/AssemblyExtensions.cs | 20 -- .../Extensions/ByteArrayExtensions.cs | 26 --- .../Extensions/DynamicExtensions.cs | 19 -- .../VND.Fw.Utils/Extensions/HashExtensions.cs | 72 ------ .../Extensions/StringExtensions.cs | 78 ------- .../Extensions/TypeConversionExtensions.cs | 21 -- .../Extensions/TypeLookupExtensions.cs | 50 ---- src/framework/VND.Fw.Utils/Guard.cs | 214 ------------------ .../Helpers/CryptoRandomHelper.cs | 31 --- .../VND.Fw.Utils/Helpers/DateTimeHelper.cs | 12 - .../VND.Fw.Utils/Helpers/EnumHelper.cs | 43 ---- .../VND.Fw.Utils/Helpers/IdHelper.cs | 12 - .../VND.Fw.Utils/Helpers/TotpHelper.cs | 104 --------- src/framework/VND.Fw.Utils/README.md | 22 -- .../VND.Fw.Utils/VND.Fw.Utils.csproj | 30 --- src/services/cart/Dockerfile | 4 +- src/services/idp/Dockerfile | 4 +- src/services/inventory/Dockerfile | 4 +- src/services/review/Dockerfile | 4 +- 108 files changed, 8 insertions(+), 4025 deletions(-) delete mode 100644 src/framework/VND.Fw.Domain/CoreException.cs delete mode 100644 src/framework/VND.Fw.Domain/Criterion.cs delete mode 100644 src/framework/VND.Fw.Domain/EntityBase.cs delete mode 100644 src/framework/VND.Fw.Domain/IDomainEvent.cs delete mode 100644 src/framework/VND.Fw.Domain/IIdentity.cs delete mode 100644 src/framework/VND.Fw.Domain/IRepositoryAsync.cs delete mode 100644 src/framework/VND.Fw.Domain/IUnitOfWorkAsync.cs delete mode 100644 src/framework/VND.Fw.Domain/IdentityBase.cs delete mode 100644 src/framework/VND.Fw.Domain/PaginatedItem.cs delete mode 100644 src/framework/VND.Fw.Domain/VND.Fw.Domain.csproj delete mode 100644 src/framework/VND.Fw.Domain/ValueObjectBase.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/EventAggregatorExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/IEventHandler.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/PresenterExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/VND.Fw.Infrastructure.AspNetCore.CleanArch.csproj delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/Configurator.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/AuthNConfigureApplication.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/BasePathConfigureApplication.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/CorsConfigureApplication.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/ForwardedHeadersConfigureApplication.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/HealthCheckConfigureApplication.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/LoggerConfigureApplication.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/MvcConfigureApplication.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/OpenApiConfigureApplication.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/ProblemDetailsConfigureApplication.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/ApiVersionConfigureService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/AuthNConfigureService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/CleanArchConfigureService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/CorsConfigureService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/DatabaseConfigureService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/FowardedHeadersConfigureService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/HttpConfigureService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/MvcConfigureService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/OpenApiConfigureService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/ProblemDetailsConfigureService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/MiniServiceExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/Options/PersistenceOption.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceCollectionExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceParams.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceProviderExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/VND.Fw.Infrastructure.AspNetCore.Miniservice.csproj delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/AuthorizeCheckOperationFilter.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/DefaultValuesOperationFilter.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/OpenApiOptions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/SecurityRequirementsOperationFilter.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/VND.Fw.Infrastructure.AspNetCore.OpenApi.csproj delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/index.html delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/AuthAttribute.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/ControllerBase.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/ApiExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/CriterionExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HostUriExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HttpRequestExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HttpResponseExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/ServiceCollectionExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/LinkItem.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Middlewares/ErrorHandlerMiddleware.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Middlewares/LogHandlerMiddleware.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/ModelBase.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/ProxyService.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/RestClient.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/VND.FW.Infrastructure.AspNetCore.csproj delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationError.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationProblemDetails.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationProblemDetailsResult.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/Options/MsSqlDbOptions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/ServiceCollectionExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/SqlServerDatabaseConnectionStringFactory.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/SqlServerDbContextOptionsBuilderFactory.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/VND.Fw.Infrastructure.EfCore.SqlServer.csproj delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Db/ApplicationDbContext.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Db/ICustomModelBuilder.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Db/IDatabaseConnectionStringFactory.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Db/IExtendDbContextOptionsBuilder.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Extensions/DbContextExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Extensions/EfRepositoryExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Extensions/OrderByExtension.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Extensions/QueryRepositoryFactoryExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Extensions/ServiceCollectionExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Extensions/WebHostExtensions.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Identity/ApplicationRole.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Identity/ApplicationUser.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Migration/ISeedData.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Migration/SeedDataBase.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Repository/EfRepository.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Repository/EfUnitOfWork.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/Repository/IEfRepository.cs delete mode 100644 src/framework/VND.Fw.Infrastructure.EfCore/VND.Fw.Infrastructure.EfCore.csproj delete mode 100644 src/framework/VND.Fw.Utils/Extensions/AssemblyExtensions.cs delete mode 100644 src/framework/VND.Fw.Utils/Extensions/ByteArrayExtensions.cs delete mode 100644 src/framework/VND.Fw.Utils/Extensions/DynamicExtensions.cs delete mode 100644 src/framework/VND.Fw.Utils/Extensions/HashExtensions.cs delete mode 100644 src/framework/VND.Fw.Utils/Extensions/StringExtensions.cs delete mode 100644 src/framework/VND.Fw.Utils/Extensions/TypeConversionExtensions.cs delete mode 100644 src/framework/VND.Fw.Utils/Extensions/TypeLookupExtensions.cs delete mode 100644 src/framework/VND.Fw.Utils/Guard.cs delete mode 100644 src/framework/VND.Fw.Utils/Helpers/CryptoRandomHelper.cs delete mode 100644 src/framework/VND.Fw.Utils/Helpers/DateTimeHelper.cs delete mode 100644 src/framework/VND.Fw.Utils/Helpers/EnumHelper.cs delete mode 100644 src/framework/VND.Fw.Utils/Helpers/IdHelper.cs delete mode 100644 src/framework/VND.Fw.Utils/Helpers/TotpHelper.cs delete mode 100644 src/framework/VND.Fw.Utils/README.md delete mode 100644 src/framework/VND.Fw.Utils/VND.Fw.Utils.csproj diff --git a/coolstore.sln b/coolstore.sln index 637355e1..6063e21c 100644 --- a/coolstore.sln +++ b/coolstore.sln @@ -15,8 +15,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VND.CoolStore.Services.Cart EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "services", "services", "{A0F90A99-CAD3-491F-9079-D1680D659A9B}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "fw", "fw", "{368570BE-6D1B-451B-9C04-FD610C0E81B8}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DEE9CA98-802A-4F8F-B9D7-2AE2758BA21F}" ProjectSection(SolutionItems) = preProject .dockerignore = .dockerignore @@ -30,22 +28,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_", "_", "{CB8885DA-CA9C-41C5-A427-3D186A49FAC4}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VND.Fw.Infrastructure.AspNetCore", "src\framework\VND.Fw.Infrastructure.AspNetCore\VND.Fw.Infrastructure.AspNetCore.csproj", "{6AD7EFCF-A6CB-4D1D-8C2B-B5721D186747}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VND.Fw.Domain", "src\framework\VND.Fw.Domain\VND.Fw.Domain.csproj", "{7F00368D-8734-4429-B4BE-F833E7AAFFC5}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VND.Fw.Utils", "src\framework\VND.Fw.Utils\VND.Fw.Utils.csproj", "{45A63B09-7BF7-4886-8A31-52148EF8B59A}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VND.Fw.Infrastructure.EfCore", "src\framework\VND.Fw.Infrastructure.EfCore\VND.Fw.Infrastructure.EfCore.csproj", "{E7EB14A0-E2D3-40F1-BBA8-A9ACBBF674C9}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VND.Fw.Infrastructure.EfCore.SqlServer", "src\framework\VND.Fw.Infrastructure.EfCore.SqlServer\VND.Fw.Infrastructure.EfCore.SqlServer.csproj", "{B73ADF43-63AF-4226-8A48-9E3B965C78D6}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VND.Fw.Infrastructure.AspNetCore.CleanArch", "src\framework\VND.Fw.Infrastructure.AspNetCore.CleanArch\VND.Fw.Infrastructure.AspNetCore.CleanArch.csproj", "{2C051E4E-5C60-4801-8735-A17F47573A88}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VND.Fw.Infrastructure.AspNetCore.Miniservice", "src\framework\VND.Fw.Infrastructure.AspNetCore.Miniservice\VND.Fw.Infrastructure.AspNetCore.Miniservice.csproj", "{944AEFDD-0D85-4DAE-8FDF-370C508D5C9E}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VND.Fw.Infrastructure.AspNetCore.OpenApi", "src\framework\VND.Fw.Infrastructure.AspNetCore.OpenApi\VND.Fw.Infrastructure.AspNetCore.OpenApi.csproj", "{E230E18E-D8CD-4877-A691-E6BFBF82F686}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -72,38 +54,6 @@ Global {40F083E3-9524-4E5F-8036-DCE1FC3C504A}.Debug|Any CPU.Build.0 = Debug|Any CPU {40F083E3-9524-4E5F-8036-DCE1FC3C504A}.Release|Any CPU.ActiveCfg = Release|Any CPU {40F083E3-9524-4E5F-8036-DCE1FC3C504A}.Release|Any CPU.Build.0 = Release|Any CPU - {6AD7EFCF-A6CB-4D1D-8C2B-B5721D186747}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6AD7EFCF-A6CB-4D1D-8C2B-B5721D186747}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6AD7EFCF-A6CB-4D1D-8C2B-B5721D186747}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6AD7EFCF-A6CB-4D1D-8C2B-B5721D186747}.Release|Any CPU.Build.0 = Release|Any CPU - {7F00368D-8734-4429-B4BE-F833E7AAFFC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7F00368D-8734-4429-B4BE-F833E7AAFFC5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7F00368D-8734-4429-B4BE-F833E7AAFFC5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7F00368D-8734-4429-B4BE-F833E7AAFFC5}.Release|Any CPU.Build.0 = Release|Any CPU - {45A63B09-7BF7-4886-8A31-52148EF8B59A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {45A63B09-7BF7-4886-8A31-52148EF8B59A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {45A63B09-7BF7-4886-8A31-52148EF8B59A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {45A63B09-7BF7-4886-8A31-52148EF8B59A}.Release|Any CPU.Build.0 = Release|Any CPU - {E7EB14A0-E2D3-40F1-BBA8-A9ACBBF674C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E7EB14A0-E2D3-40F1-BBA8-A9ACBBF674C9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E7EB14A0-E2D3-40F1-BBA8-A9ACBBF674C9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E7EB14A0-E2D3-40F1-BBA8-A9ACBBF674C9}.Release|Any CPU.Build.0 = Release|Any CPU - {B73ADF43-63AF-4226-8A48-9E3B965C78D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B73ADF43-63AF-4226-8A48-9E3B965C78D6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B73ADF43-63AF-4226-8A48-9E3B965C78D6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B73ADF43-63AF-4226-8A48-9E3B965C78D6}.Release|Any CPU.Build.0 = Release|Any CPU - {2C051E4E-5C60-4801-8735-A17F47573A88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2C051E4E-5C60-4801-8735-A17F47573A88}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2C051E4E-5C60-4801-8735-A17F47573A88}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2C051E4E-5C60-4801-8735-A17F47573A88}.Release|Any CPU.Build.0 = Release|Any CPU - {944AEFDD-0D85-4DAE-8FDF-370C508D5C9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {944AEFDD-0D85-4DAE-8FDF-370C508D5C9E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {944AEFDD-0D85-4DAE-8FDF-370C508D5C9E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {944AEFDD-0D85-4DAE-8FDF-370C508D5C9E}.Release|Any CPU.Build.0 = Release|Any CPU - {E230E18E-D8CD-4877-A691-E6BFBF82F686}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E230E18E-D8CD-4877-A691-E6BFBF82F686}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E230E18E-D8CD-4877-A691-E6BFBF82F686}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E230E18E-D8CD-4877-A691-E6BFBF82F686}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -115,14 +65,6 @@ Global {2706AB23-A32E-4D4C-B2A2-AE0FE36F4973} = {A0F90A99-CAD3-491F-9079-D1680D659A9B} {40F083E3-9524-4E5F-8036-DCE1FC3C504A} = {A0F90A99-CAD3-491F-9079-D1680D659A9B} {DEE9CA98-802A-4F8F-B9D7-2AE2758BA21F} = {CB8885DA-CA9C-41C5-A427-3D186A49FAC4} - {6AD7EFCF-A6CB-4D1D-8C2B-B5721D186747} = {368570BE-6D1B-451B-9C04-FD610C0E81B8} - {7F00368D-8734-4429-B4BE-F833E7AAFFC5} = {368570BE-6D1B-451B-9C04-FD610C0E81B8} - {45A63B09-7BF7-4886-8A31-52148EF8B59A} = {368570BE-6D1B-451B-9C04-FD610C0E81B8} - {E7EB14A0-E2D3-40F1-BBA8-A9ACBBF674C9} = {368570BE-6D1B-451B-9C04-FD610C0E81B8} - {B73ADF43-63AF-4226-8A48-9E3B965C78D6} = {368570BE-6D1B-451B-9C04-FD610C0E81B8} - {2C051E4E-5C60-4801-8735-A17F47573A88} = {368570BE-6D1B-451B-9C04-FD610C0E81B8} - {944AEFDD-0D85-4DAE-8FDF-370C508D5C9E} = {368570BE-6D1B-451B-9C04-FD610C0E81B8} - {E230E18E-D8CD-4877-A691-E6BFBF82F686} = {368570BE-6D1B-451B-9C04-FD610C0E81B8} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {277B7E0A-BA8E-4DF8-ABD5-890801FC76F8} diff --git a/src/framework/VND.Fw.Domain/CoreException.cs b/src/framework/VND.Fw.Domain/CoreException.cs deleted file mode 100644 index a0c3696f..00000000 --- a/src/framework/VND.Fw.Domain/CoreException.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; - -namespace VND.Fw.Domain -{ - public class CoreException : Exception - { - public CoreException(string message) - : this(message, null) - { - } - - public CoreException(string message, Exception innerEx) - : base(message, innerEx) - { - } - } - - public class DomainException : CoreException - { - public DomainException(string message) - : base(message, null) - { - } - } - - public class ViolateSecurityException : CoreException - { - public ViolateSecurityException(string message) - : base(message, null) - { - } - } -} diff --git a/src/framework/VND.Fw.Domain/Criterion.cs b/src/framework/VND.Fw.Domain/Criterion.cs deleted file mode 100644 index 19923b29..00000000 --- a/src/framework/VND.Fw.Domain/Criterion.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace VND.Fw.Domain -{ - public class Criterion : ValueObjectBase - { - private const int maxPageSize = 50; - private const int configurablePageSize = 10; - - /*public Criterion(int currentPage, int pageSize, PaginationOption defaultPagingOption, string sortBy = "", string sortOrder = "") - { - if (currentPage <= 0) - throw new Exception("CurrentPage could not be less than zero."); - - if (pageSize <= 0) - throw new Exception("PageSize could not be less than zero."); - - CurrentPage = currentPage - 1; - PageSize = pageSize; - DefaultPagingOption = defaultPagingOption; - SortBy = sortBy; - SortOrder = sortOrder; - } */ - - public Criterion() - { - CurrentPage = 0; - PageSize = configurablePageSize; - SortBy = "Id"; - SortOrder = "desc"; - } - - public int CurrentPage { get; set; } - - private int _pageSize = maxPageSize; - public int PageSize - { - get { return _pageSize; } - set - { - _pageSize = (value > maxPageSize) ? maxPageSize : - (value < configurablePageSize ? configurablePageSize : value); - } - } - - public string SortBy { get; private set; } - public string SortOrder { get; private set; } - - public Criterion SetPageSize(int pageSize) - { - if (pageSize <= 0) - throw new Exception("PageSize could not be less than zero."); - - PageSize = pageSize; - return this; - } - - public Criterion SetCurrentPage(int currentPage) - { - if (currentPage <= 0) - throw new Exception("CurrentPage could not be less than zero."); - - CurrentPage = currentPage; - return this; - } - - protected override IEnumerable GetEqualityComponents() - { - yield return CurrentPage; - yield return PageSize; - yield return SortBy; - yield return SortOrder; - } - } -} diff --git a/src/framework/VND.Fw.Domain/EntityBase.cs b/src/framework/VND.Fw.Domain/EntityBase.cs deleted file mode 100644 index 2777e2b3..00000000 --- a/src/framework/VND.Fw.Domain/EntityBase.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using VND.Fw.Utils.Helpers; - -namespace VND.Fw.Domain -{ - public interface IEntity : IIdentity - { } - - public interface IAggregateRoot - { - IAggregateRoot ApplyEvent(IDomainEvent payload); - List GetUncommittedEvents(); - void ClearUncommittedEvents(); - IAggregateRoot RemoveEvent(IDomainEvent @event); - IAggregateRoot AddEvent(IDomainEvent uncommittedEvent); - IAggregateRoot RegisterHandler(Action handler); - } - - public abstract class AggregateRootBase : EntityBase, IAggregateRoot - { - private readonly List _uncommittedEvents = new List(); - private readonly Dictionary> _handlers = new Dictionary>(); - - protected AggregateRootBase() : this(IdHelper.GenerateId()) - { - } - - protected AggregateRootBase(Guid id) - { - Id = id; - Created = DateTimeHelper.GenerateDateTime(); - } - - public int Version { get; protected set; } - - public IAggregateRoot AddEvent(IDomainEvent uncommittedEvent) - { - _uncommittedEvents.Add(uncommittedEvent); - ApplyEvent(uncommittedEvent); - return this; - } - - public IAggregateRoot ApplyEvent(IDomainEvent payload) - { - _handlers[payload.GetType()](payload); - Version++; - return this; - } - - public void ClearUncommittedEvents() - { - _uncommittedEvents.Clear(); - } - - public List GetUncommittedEvents() - { - return _uncommittedEvents; - } - - public IAggregateRoot RegisterHandler(Action handler) - { - _handlers.Add(typeof(T), e => handler((T)e)); - return this; - } - - public IAggregateRoot RemoveEvent(IDomainEvent @event) - { - if (_uncommittedEvents.Find(e => e == @event) != null) - { - _uncommittedEvents.Remove(@event); - } - return this; - } - } - - public abstract class EntityBase : IEntity - { - protected EntityBase() : this(IdHelper.GenerateId()) - { - } - - protected EntityBase(Guid id) - { - Id = id; - Created = DateTimeHelper.GenerateDateTime(); - } - - [Key] - public Guid Id { get; protected set; } - - public DateTime Created { get; protected set; } - - public DateTime Updated { get; protected set; } - } -} diff --git a/src/framework/VND.Fw.Domain/IDomainEvent.cs b/src/framework/VND.Fw.Domain/IDomainEvent.cs deleted file mode 100644 index 1baa8eb3..00000000 --- a/src/framework/VND.Fw.Domain/IDomainEvent.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace VND.Fw.Domain -{ - public interface IDomainEvent - { - int EventVersion { get; set; } - DateTime OccurredOn { get; set; } - } -} diff --git a/src/framework/VND.Fw.Domain/IIdentity.cs b/src/framework/VND.Fw.Domain/IIdentity.cs deleted file mode 100644 index 7c35fa7b..00000000 --- a/src/framework/VND.Fw.Domain/IIdentity.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace VND.Fw.Domain -{ - public interface IIdentity - { - Guid Id { get; } - } -} diff --git a/src/framework/VND.Fw.Domain/IRepositoryAsync.cs b/src/framework/VND.Fw.Domain/IRepositoryAsync.cs deleted file mode 100644 index cfcaeac5..00000000 --- a/src/framework/VND.Fw.Domain/IRepositoryAsync.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Linq; -using System.Threading.Tasks; - -namespace VND.Fw.Domain -{ - public interface IRepositoryFactory - { - IRepositoryAsync Repository() where TEntity : IEntity; - } - - public interface IQueryRepositoryFactory - { - IQueryRepository QueryRepository() where TEntity : IEntity; - } - - public interface IRepositoryAsync where TEntity : IEntity - { - Task AddAsync(TEntity entity); - Task UpdateAsync(TEntity entity); - Task DeleteAsync(TEntity entity); - } - - public interface IQueryRepository where TEntity : IEntity - { - IQueryable Queryable(); - } -} diff --git a/src/framework/VND.Fw.Domain/IUnitOfWorkAsync.cs b/src/framework/VND.Fw.Domain/IUnitOfWorkAsync.cs deleted file mode 100644 index 61f8ad45..00000000 --- a/src/framework/VND.Fw.Domain/IUnitOfWorkAsync.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace VND.Fw.Domain -{ - public interface IUnitOfWorkAsync : IRepositoryFactory, IDisposable - { - int SaveChanges(); - Task SaveChangesAsync(CancellationToken cancellationToken); - int ExecuteSqlCommand(string sql, params object[] parameters); - Task ExecuteSqlCommandAsync(string sql, params object[] parameters); - Task ExecuteSqlCommandAsync(string sql, CancellationToken cancellationToken, params object[] parameters); - int? CommandTimeout { get; set; } - } -} diff --git a/src/framework/VND.Fw.Domain/IdentityBase.cs b/src/framework/VND.Fw.Domain/IdentityBase.cs deleted file mode 100644 index 94aa1810..00000000 --- a/src/framework/VND.Fw.Domain/IdentityBase.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using VND.Fw.Utils.Helpers; - -namespace VND.Fw.Domain -{ - public abstract class IdentityBase : IEquatable, IIdentity - { - protected IdentityBase() - { - Id = IdHelper.GenerateId(); - } - - protected IdentityBase(Guid id) - { - Id = id; - } - - // currently for Entity Framework, set must be protected, not private. - // will be fixed in EF 6. - public Guid Id { get; protected set; } - - public bool Equals(IdentityBase id) - { - if (ReferenceEquals(this, id)) return true; - if (ReferenceEquals(null, id)) return false; - return Id.Equals(id.Id); - } - - public override bool Equals(object anotherObject) - { - return Equals(anotherObject as IdentityBase); - } - - public override int GetHashCode() - { - return GetType().GetHashCode() * 907 + Id.GetHashCode(); - } - - public override string ToString() - { - return GetType().Name + " [Id=" + Id + "]"; - } - } -} diff --git a/src/framework/VND.Fw.Domain/PaginatedItem.cs b/src/framework/VND.Fw.Domain/PaginatedItem.cs deleted file mode 100644 index d6856c30..00000000 --- a/src/framework/VND.Fw.Domain/PaginatedItem.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Collections.Generic; - -namespace VND.Fw.Domain -{ - public class PaginatedItem : ValueObjectBase - { - public PaginatedItem(int totalItems, int totalPages, IReadOnlyList items) - { - TotalItems = totalItems; - TotalPages = totalPages; - Items = items; - } - - public int TotalItems { get; private set; } - - public long TotalPages { get; private set; } - - public IReadOnlyList Items { get; private set; } - - protected override IEnumerable GetEqualityComponents() - { - yield return TotalItems; - yield return TotalPages; - yield return Items; - } - } -} diff --git a/src/framework/VND.Fw.Domain/VND.Fw.Domain.csproj b/src/framework/VND.Fw.Domain/VND.Fw.Domain.csproj deleted file mode 100644 index 653681ba..00000000 --- a/src/framework/VND.Fw.Domain/VND.Fw.Domain.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - netstandard2.0 - - - - - - - - - - - - - diff --git a/src/framework/VND.Fw.Domain/ValueObjectBase.cs b/src/framework/VND.Fw.Domain/ValueObjectBase.cs deleted file mode 100644 index ab1dc972..00000000 --- a/src/framework/VND.Fw.Domain/ValueObjectBase.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using VND.Fw.Utils.Extensions; - -namespace VND.Fw.Domain -{ - public abstract class ValueObjectBase - { - protected abstract IEnumerable GetEqualityComponents(); - - public override bool Equals(object obj) - { - if (ReferenceEquals(this, obj)) return true; - if (ReferenceEquals(null, obj)) return false; - if (GetType() != obj.GetType()) return false; - var vo = obj as ValueObjectBase; - return GetEqualityComponents().SequenceEqual(vo.GetEqualityComponents()); - } - - public override int GetHashCode() - { - return HashExtensions.CombineHashCodes(GetEqualityComponents()); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/EventAggregatorExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/EventAggregatorExtensions.cs deleted file mode 100644 index fcd3759e..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/EventAggregatorExtensions.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Reactive.Linq; -using System.Reactive.Threading.Tasks; -using MediatR; - -namespace VND.Fw.Infrastructure.AspNetCore.CleanArch -{ - public static class EventAggregatorExtensions - { - public static IObservable SendStream(this IMediator mediator, - TRequest request, Func mapTo = null) - where TRequest : IRequest - where TResponse : class - { - return mediator.Send(request) - .ToObservable() - .Select(x => x.PresentFor(mapTo)); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/IEventHandler.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/IEventHandler.cs deleted file mode 100644 index 7d8e4ba9..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/IEventHandler.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using MediatR; -using VND.Fw.Domain; - -namespace VND.Fw.Infrastructure.AspNetCore.CleanArch -{ - public interface IEventHandler : IRequestHandler - where TRequest : IRequest - { - IQueryRepositoryFactory QueryRepositoryFactory { get; } - IUnitOfWorkAsync UnitOfWork { get; } - } - - public abstract class TxRequestHandlerBase : IEventHandler - where TRequest : IRequest - { - protected TxRequestHandlerBase(IUnitOfWorkAsync uow, IQueryRepositoryFactory queryRepositoryFactory) - { - QueryRepositoryFactory = queryRepositoryFactory; - UnitOfWork = uow; - } - - public IQueryRepositoryFactory QueryRepositoryFactory { get; } - - public IUnitOfWorkAsync UnitOfWork { get; } - - public async Task Handle(TRequest request, CancellationToken cancellationToken) - { - var result = await TxHandle(request, cancellationToken); - await UnitOfWork.SaveChangesAsync(cancellationToken); - return result; - } - - public abstract Task TxHandle(TRequest request, CancellationToken cancellationToken); - } - - public abstract class RequestHandlerBase : IEventHandler - where TRequest : IRequest - { - protected RequestHandlerBase(IUnitOfWorkAsync uow, IQueryRepositoryFactory queryRepositoryFactory) - { - QueryRepositoryFactory = queryRepositoryFactory; - UnitOfWork = uow; - } - - public IQueryRepositoryFactory QueryRepositoryFactory { get; } - - public IUnitOfWorkAsync UnitOfWork { get; } - - public abstract Task Handle(TRequest request, CancellationToken cancellationToken); - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/PresenterExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/PresenterExtensions.cs deleted file mode 100644 index d44fa1b8..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/PresenterExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using Microsoft.AspNetCore.Mvc; - -namespace VND.Fw.Infrastructure.AspNetCore.CleanArch -{ - public static class PresenterExtensions - { - public static IActionResult PresentFor(this TInput input, Func mapTo = null) - where TInput : class - { - if (input == null) - { - return new NoContentResult(); - } - - return mapTo == null ? new OkObjectResult(input) : new OkObjectResult(mapTo(input)); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/VND.Fw.Infrastructure.AspNetCore.CleanArch.csproj b/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/VND.Fw.Infrastructure.AspNetCore.CleanArch.csproj deleted file mode 100644 index 92cdb3db..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.CleanArch/VND.Fw.Infrastructure.AspNetCore.CleanArch.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - netstandard2.0 - - - - - - - - - - - - - - diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/Configurator.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/Configurator.cs deleted file mode 100644 index 938daa01..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/Configurator.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice -{ - public interface IPriorityConfigure - { - int Priority { get; } - } - - public interface IBasicConfigureServices : IPriorityConfigure - { - void Configure(IServiceCollection services); - } - - public interface IDbConfigureServices : IPriorityConfigure - { - void Configure(IServiceCollection services) where TDbContext : DbContext; - } - - public interface IConfigureApplication : IPriorityConfigure - { - void Configure(IApplicationBuilder appBuilder); - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/AuthNConfigureApplication.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/AuthNConfigureApplication.cs deleted file mode 100644 index c8b92f61..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/AuthNConfigureApplication.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureApplications -{ - public class AuthNConfigureApplication : IConfigureApplication - { - public int Priority { get; } = 700; - public void Configure(IApplicationBuilder app) - { - var config = app.ApplicationServices.GetRequiredService(); - - if (config.GetValue("EnableAuthN", false)) - { - app.UseAuthentication(); - } - } - } -} \ No newline at end of file diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/BasePathConfigureApplication.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/BasePathConfigureApplication.cs deleted file mode 100644 index 04b49a86..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/BasePathConfigureApplication.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using VND.Fw.Infrastructure.AspNetCore.Extensions; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureApplications -{ - public class BasePathConfigureApplication : IConfigureApplication - { - public int Priority { get; } = 400; - public void Configure(IApplicationBuilder app) - { - var config = app.ApplicationServices.GetRequiredService(); - var loggerFactory = app.ApplicationServices.GetRequiredService(); - var logger = loggerFactory.CreateLogger("init"); - - var basePath = config.GetBasePath(); - - if (!string.IsNullOrEmpty(basePath)) - { - logger.LogInformation($"Using PATH BASE '{basePath}'"); - app.UsePathBase(basePath); - } - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/CorsConfigureApplication.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/CorsConfigureApplication.cs deleted file mode 100644 index 1a1fb282..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/CorsConfigureApplication.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.AspNetCore.Builder; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureApplications -{ - public class CorsConfigureApplication : IConfigureApplication - { - public int Priority { get; } = 600; - public void Configure(IApplicationBuilder app) - { - app.UseCors("CorsPolicy"); - } - } -} \ No newline at end of file diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/ForwardedHeadersConfigureApplication.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/ForwardedHeadersConfigureApplication.cs deleted file mode 100644 index ff4ced37..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/ForwardedHeadersConfigureApplication.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureApplications -{ - public class ForwardedHeadersConfigureApplication : IConfigureApplication - { - public int Priority { get; } = 500; - public void Configure(IApplicationBuilder app) - { - var env = app.ApplicationServices.GetRequiredService(); - - if (!env.IsDevelopment()) - { - app.UseForwardedHeaders(); - } - } - } -} \ No newline at end of file diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/HealthCheckConfigureApplication.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/HealthCheckConfigureApplication.cs deleted file mode 100644 index 6582406f..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/HealthCheckConfigureApplication.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Microsoft.AspNetCore.Builder; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureApplications -{ - public class HealthCheckConfigureApplication : IConfigureApplication - { - public int Priority { get; } = 300; - public void Configure(IApplicationBuilder app) - { -#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously - app.Map("/liveness", lapp => lapp.Run(async ctx => ctx.Response.StatusCode = 200)); -#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously - } - } -} \ No newline at end of file diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/LoggerConfigureApplication.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/LoggerConfigureApplication.cs deleted file mode 100644 index 7d7ae750..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/LoggerConfigureApplication.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using VND.Fw.Infrastructure.AspNetCore.Middlewares; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureApplications -{ - public class LoggerConfigureApplication : IConfigureApplication - { - public int Priority { get; } = 100; - public void Configure(IApplicationBuilder app) - { - var config = app.ApplicationServices.GetRequiredService(); - var loggerFactory = app.ApplicationServices.GetRequiredService(); - - loggerFactory.AddConsole(config.GetSection("Logging")); - loggerFactory.AddDebug(); - - app.UseMiddleware(); - } - } -} \ No newline at end of file diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/MvcConfigureApplication.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/MvcConfigureApplication.cs deleted file mode 100644 index d6e1754a..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/MvcConfigureApplication.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.AspNetCore.Builder; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureApplications -{ - public class MvcConfigureApplication : IConfigureApplication - { - public int Priority { get; } = 800; - public void Configure(IApplicationBuilder app) - { - app.UseMvc(); - } - } -} \ No newline at end of file diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/OpenApiConfigureApplication.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/OpenApiConfigureApplication.cs deleted file mode 100644 index 0e50388f..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/OpenApiConfigureApplication.cs +++ /dev/null @@ -1,55 +0,0 @@ -using IdentityServer4.Models; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Mvc.ApiExplorer; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using VND.Fw.Infrastructure.AspNetCore.Extensions; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureApplications -{ - public class OpenApiConfigureApplication : IConfigureApplication - { - public int Priority { get; } = 900; - public void Configure(IApplicationBuilder app) - { - var config = app.ApplicationServices.GetRequiredService(); - var loggerFactory = app.ApplicationServices.GetRequiredService(); - - var basePath = config.GetBasePath(); - var currentHostUri = config.GetExternalCurrentHostUri(); - - if (config.GetValue("OpenApi:Enabled", false)) - { - app.UseSwagger(); - } - - if (config.GetValue("OpenApi:EnabledUI", false)) - { - app.UseSwaggerUI( - c => - { - var provider = app.ApplicationServices.GetRequiredService(); - - // build a swagger endpoint for each discovered API version - foreach (var description in provider.ApiVersionDescriptions) - { - c.SwaggerEndpoint( - $"{basePath}swagger/{description.GroupName}/swagger.json", - description.GroupName.ToUpperInvariant()); - } - - if (config.GetValue("EnableAuthN", false)) - { - c.OAuthClientId("swagger_id"); - c.OAuthClientSecret("secret".Sha256()); - c.OAuthAppName("swagger_app"); - c.OAuth2RedirectUrl($"{currentHostUri}/swagger/oauth2-redirect.html"); - } - - // c.IndexStream = () => typeof(MiniServiceExtensions).GetTypeInfo().Assembly.GetManifestResourceStream("VND.Fw.Infrastructure.AspNetCore.Swagger.index.html"); - }); - } - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/ProblemDetailsConfigureApplication.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/ProblemDetailsConfigureApplication.cs deleted file mode 100644 index 8edee3bd..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureApplications/ProblemDetailsConfigureApplication.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System; -using System.Diagnostics; -using System.Reflection; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Diagnostics; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Server.Kestrel.Core; -using Microsoft.Extensions.DependencyInjection; -using VND.Fw.Infrastructure.AspNetCore.Extensions; -using VND.Fw.Infrastructure.AspNetCore.Middlewares; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureApplications -{ - public class ProblemDetailsConfigureApplication : IConfigureApplication - { - public int Priority { get; } = 200; - public void Configure(IApplicationBuilder app) - { - var env = app.ApplicationServices.GetRequiredService(); - - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - app.UseDatabaseErrorPage(); - // app.UseMiniProfiler(); - } - else - { - app.UseExceptionHandler("/Home/Error"); - } - - app.UseExceptionHandler(errorApp => - { -#pragma warning disable CS1998 - errorApp.Run(async context => - { - var errorFeature = context.Features.Get(); - var exception = errorFeature.Error; - - // the IsTrusted() extension method doesn't exist and - // you should implement your own as you may want to interpret it differently - // i.e. based on the current principal - - var problemDetails = new ProblemDetails - { - Instance = $"urn:myorganization:error:{Guid.NewGuid()}" - }; - - if (exception is BadHttpRequestException badHttpRequestException) - { - problemDetails.Title = "Invalid request"; - problemDetails.Status = (int)typeof(BadHttpRequestException).GetProperty( - "StatusCode", BindingFlags.NonPublic | BindingFlags.Instance) - ?.GetValue(badHttpRequestException); - problemDetails.Detail = badHttpRequestException.Message; - } - else - { - problemDetails.Title = "An unexpected error occurred!"; - problemDetails.Status = 500; - problemDetails.Detail = exception.Demystify().ToString(); - } - - // TODO: log the exception etc.. - - context.Response.StatusCode = problemDetails.Status.Value; - context.Response.WriteJson(problemDetails, "application/problem+json"); - } -#pragma warning restore CS1998 - ); - }); - - app.UseMiddleware(); - } - } -} \ No newline at end of file diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/ApiVersionConfigureService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/ApiVersionConfigureService.cs deleted file mode 100644 index a1f2282f..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/ApiVersionConfigureService.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Linq; -using System.Text.RegularExpressions; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Newtonsoft.Json.Serialization; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureServices -{ - public class ApiVersionConfigureService : IBasicConfigureServices - { - public int Priority { get; } = 400; - - public void Configure(IServiceCollection services) - { - var svcProvider = services.BuildServiceProvider(); - var config = svcProvider.GetRequiredService(); - - services.AddRouting(o => o.LowercaseUrls = true); - services - .AddMvcCore() - .AddVersionedApiExplorer( - o => - { - o.GroupNameFormat = "'v'VVV"; - o.SubstituteApiVersionInUrl = true; - }) - .AddJsonFormatters(o => o.ContractResolver = new CamelCasePropertyNamesContractResolver()) - .AddDataAnnotations(); - - services.AddApiVersioning(o => - { - o.ReportApiVersions = true; - o.AssumeDefaultVersionWhenUnspecified = true; - o.DefaultApiVersion = ParseApiVersion(config.GetValue("API_VERSION")); - }); - } - - private static ApiVersion ParseApiVersion(string serviceVersion) - { - if (string.IsNullOrEmpty(serviceVersion)) - { - throw new Exception("[CS] ServiceVersion is null or empty."); - } - - const string pattern = @"(.)|(-)"; - var results = Regex.Split(serviceVersion, pattern) - .Where(x => x != string.Empty && x != "." && x != "-") - .ToArray(); - - if (results == null || results.Count() < 2) - { - throw new Exception("[CS] Could not parse ServiceVersion."); - } - - if (results.Count() > 2) - { - return new ApiVersion( - Convert.ToInt32(results[0]), - Convert.ToInt32(results[1]), - results[2]); - } - - return new ApiVersion( - Convert.ToInt32(results[0]), - Convert.ToInt32(results[1])); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/AuthNConfigureService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/AuthNConfigureService.cs deleted file mode 100644 index c3691c77..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/AuthNConfigureService.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System.Collections.Generic; -using System.IdentityModel.Tokens.Jwt; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using VND.Fw.Infrastructure.AspNetCore.Extensions; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureServices -{ - public class AuthNConfigureService : IBasicConfigureServices - { - public int Priority { get; } = 700; - - public void Configure(IServiceCollection services) - { - var svcProvider = services.BuildServiceProvider(); - var config = svcProvider.GetRequiredService(); - var env = svcProvider.GetRequiredService(); - var serviceParams = svcProvider.GetRequiredService(); - - if (config.GetValue("EnableAuthN", false)) - { - JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); - - services - .AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddJwtBearer(options => - { - options.Authority = GetAuthUri(config, env); - options.RequireHttpsMetadata = false; - options.Audience = serviceParams["audience"].ToString(); - }); - - services.AddAuthorization(c => - { - if (serviceParams.TryGetValue("claimToScopeMap", out var claimToScopeMap)) - { - foreach (var claimToScope in (IDictionary)claimToScopeMap) - { - c.AddPolicy(claimToScope.Key, p => p.RequireClaim("scope", claimToScope.Value)); - } - } - }); - } - } - - private static string GetAuthUri(IConfiguration config, IHostingEnvironment env) - { - return config.GetHostUri(env, "Auth"); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/CleanArchConfigureService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/CleanArchConfigureService.cs deleted file mode 100644 index b7424fe7..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/CleanArchConfigureService.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using MediatR; -using Microsoft.Extensions.DependencyInjection; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureServices -{ - public class CleanArchConfigureService : IBasicConfigureServices - { - public int Priority { get; } = 300; - - public void Configure(IServiceCollection services) - { - var svcProvider = services.BuildServiceProvider(); - var serviceParams = svcProvider.GetRequiredService(); - var assemblies = serviceParams["assemblies"] as HashSet; - assemblies.Add(typeof(MiniServiceExtensions).Assembly); - - services.AddMediatR(assemblies.ToArray()); - services.Scan( - scanner => scanner - .FromAssemblies(assemblies.ToArray()) - .AddClasses() - .AsImplementedInterfaces()); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/CorsConfigureService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/CorsConfigureService.cs deleted file mode 100644 index 40da3fb9..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/CorsConfigureService.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureServices -{ - public class CorsConfigureService : IBasicConfigureServices - { - public int Priority { get; } = 900; - - public void Configure(IServiceCollection services) - { - services.AddCors(options => - { - options.AddPolicy("CorsPolicy", - policy => policy.AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader() - .AllowCredentials()); - }); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/DatabaseConfigureService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/DatabaseConfigureService.cs deleted file mode 100644 index 134a50fa..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/DatabaseConfigureService.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.IdentityModel.Logging; -using VND.Fw.Infrastructure.AspNetCore.Miniservice.Options; -using VND.Fw.Infrastructure.EfCore.Db; -using VND.Fw.Infrastructure.EfCore.Extensions; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureServices -{ - public class DatabaseConfigureService : IDbConfigureServices - { - public int Priority { get; } = 100; - - public void Configure(IServiceCollection services) where TDbContext : DbContext - { - IdentityModelEventSource.ShowPII = true; - - var svcProvider = services.BuildServiceProvider(); - var config = svcProvider.GetRequiredService(); - var serviceParams = svcProvider.GetRequiredService(); - var extendOptionsBuilder = svcProvider.GetRequiredService(); - var connStringFactory = svcProvider.GetRequiredService(); - - //TODO: refactor it - var fisrtAssembly = (serviceParams["assemblies"] as HashSet).FirstOrDefault(); - - services.AddOptions() - .Configure(config.GetSection("EfCore")); - - void OptionsBuilderAction(DbContextOptionsBuilder o) - { - extendOptionsBuilder.Extend(o, connStringFactory, fisrtAssembly.GetName().Name); - } - - services.AddDbContextPool(OptionsBuilderAction); - services.AddSingleton(); - services.AddSingleton(resolver => resolver.GetRequiredService()); - services.AddEfCore(); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/FowardedHeadersConfigureService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/FowardedHeadersConfigureService.cs deleted file mode 100644 index 035c2ab4..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/FowardedHeadersConfigureService.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.Extensions.DependencyInjection; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureServices -{ - public class FowardedHeadersConfigureService : IBasicConfigureServices - { - public int Priority { get; } = 1000; - - public void Configure(IServiceCollection services) - { - var svcProvider = services.BuildServiceProvider(); - var env = svcProvider.GetRequiredService(); - - if (!env.IsDevelopment()) - { - services.Configure(options => - { - options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; - }); - } - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/HttpConfigureService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/HttpConfigureService.cs deleted file mode 100644 index e002de4d..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/HttpConfigureService.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Infrastructure; -using Microsoft.AspNetCore.Mvc.Routing; -using Microsoft.Extensions.DependencyInjection; -using VND.Fw.Infrastructure.AspNetCore.Extensions; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureServices -{ - public class HttpConfigureService : IBasicConfigureServices - { - public int Priority { get; } = 200; - - public void Configure(IServiceCollection services) - { - services.AddHttpContextAccessor(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(fac => new UrlHelper(fac.GetService().ActionContext)); - services.AddHttpPolly(); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/MvcConfigureService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/MvcConfigureService.cs deleted file mode 100644 index 74144301..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/MvcConfigureService.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.DependencyInjection; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureServices -{ - public class MvcConfigureService : IBasicConfigureServices - { - public int Priority { get; } = 500; - - public void Configure(IServiceCollection services) - { - services - .AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/OpenApiConfigureService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/OpenApiConfigureService.cs deleted file mode 100644 index d581ceaf..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/OpenApiConfigureService.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Mvc.ApiExplorer; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Swashbuckle.AspNetCore.Swagger; -using VND.Fw.Infrastructure.AspNetCore.Extensions; -using VND.Fw.Infrastructure.AspNetCore.OpenApi; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureServices -{ - public class OpenApiConfigureService : IBasicConfigureServices - { - public int Priority { get; } = 800; - - public void Configure(IServiceCollection services) - { - var svcProvider = services.BuildServiceProvider(); - var config = svcProvider.GetRequiredService(); - var serviceParams = svcProvider.GetRequiredService(); - - if (config.GetSection("OpenApi") == null) - { - throw new Exception("Please add OpenApi configuration or disabled OpenAPI."); - } - - if (config.GetValue("OpenApi:Enabled", false)) - { - services.Configure(config.GetSection("OpenApi")); - - services.AddSwaggerGen(c => - { - var provider = services.BuildServiceProvider().GetRequiredService(); - - c.DescribeAllEnumsAsStrings(); - - foreach (var description in provider.ApiVersionDescriptions) - { - c.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(config, description)); - } - - // c.IncludeXmlComments (XmlCommentsFilePath); - - if (config.GetValue("EnableAuthN", false)) - { - c.AddSecurityDefinition("oauth2", new OAuth2Scheme - { - Type = "oauth2", - Flow = "implicit", - AuthorizationUrl = $"{GetExternalAuthUri(config)}/connect/authorize", - TokenUrl = $"{GetExternalAuthUri(config)}/connect/token", - Scopes = serviceParams["scopes"] as Dictionary - }); - } - - c.EnableAnnotations(); - - if (config.GetValue("EnableAuthN", false)) - { - c.OperationFilter(); - } - - c.OperationFilter(); - c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); - }); - } - } - - private static string GetExternalAuthUri(IConfiguration config) - { - return config.GetExternalHostUri("Auth"); - } - - private static Info CreateInfoForApiVersion(IConfiguration config, ApiVersionDescription description) - { - var info = new Info() - { - Title = $"{config.GetValue("OpenApi:Title", "API")} {description.ApiVersion}", - Version = description.ApiVersion.ToString(), - Description = config.GetValue("OpenApi:Description", "An application with Swagger, Swashbuckle, and API versioning."), - Contact = new Contact() - { - Name = config.GetValue("OpenApi:ContactName", "Vietnam Devs"), - Email = config.GetValue("OpenApi:ContactEmail", "vietnam.devs.group@gmail.com") - }, - TermsOfService = config.GetValue("OpenApi:TermOfService", "Shareware"), - License = new License() - { - Name = config.GetValue("OpenApi:LicenseName", "MIT"), - Url = config.GetValue("OpenApi:LicenseUrl", "https://opensource.org/licenses/MIT") - } - }; - - if (description.IsDeprecated) - { - info.Description += " This API version has been deprecated."; - } - - return info; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/ProblemDetailsConfigureService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/ProblemDetailsConfigureService.cs deleted file mode 100644 index 9b50216c..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ConfigureServices/ProblemDetailsConfigureService.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.DependencyInjection; -using VND.Fw.Infrastructure.AspNetCore.Validation; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.ConfigureServices -{ - public class ProblemDetailsConfigureService : IBasicConfigureServices - { - public int Priority { get; } = 600; - - public void Configure(IServiceCollection services) - { - services.Configure(options => - { - options.InvalidModelStateResponseFactory = ctx => new ValidationProblemDetailsResult(); - }); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/MiniServiceExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/MiniServiceExtensions.cs deleted file mode 100644 index 65b83cf3..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/MiniServiceExtensions.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Reference at https://thenewstack.io/miniservices-a-realistic-alternative-to-microservices - -using Microsoft.AspNetCore.Builder; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice -{ - public static class MiniServiceExtensions - { - public static IServiceCollection AddMiniService(this IServiceCollection services) - where TDbContext : DbContext - { - services.ScanAndRegisterServices(); - services.ScanAndRegisterServices(); - - var svcProvider = services.BuildServiceProvider(); - var dbConfigureSvcs = svcProvider.GetServicesByPriority(); - foreach (var configureSvc in dbConfigureSvcs) - { - configureSvc.Configure(services); - } - - var configureSvcs = svcProvider.GetServicesByPriority(); - foreach (var configureSvc in configureSvcs) - { - configureSvc.Configure(services); - } - - return services; - } - - public static IApplicationBuilder UseMiniService(this IApplicationBuilder app) - { - var appSvc = app.ApplicationServices; - var configureApps = appSvc.GetServicesByPriority(); - foreach (var configureApp in configureApps) - { - configureApp.Configure(app); - } - return app; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/Options/PersistenceOption.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/Options/PersistenceOption.cs deleted file mode 100644 index 90ad3832..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/Options/PersistenceOption.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice.Options -{ - public class PersistenceOption - { - public string FullyQualifiedPrefix { get; set; } = "VND.CoolStore.Services.*"; - public string ShortyQualifiedPrefix { get; set; } = "VND.CoolStore.Services"; - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceCollectionExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceCollectionExtensions.cs deleted file mode 100644 index b47ae250..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Collections.Generic; -using System.Reflection; -using Microsoft.Extensions.DependencyInjection; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice -{ - public static class ServiceCollectionExtensions - { - public static IServiceCollection ScanAndRegisterServices(this IServiceCollection services) - { - var svcProvider = services.BuildServiceProvider(); - var serviceParams = svcProvider.GetRequiredService(); - var assemblies = serviceParams["assemblies"] as HashSet; - - return services.Scan( - scanner => scanner - .FromAssemblies(assemblies) - .AddClasses(x => x.AssignableTo()) - .AsImplementedInterfaces() - .WithScopedLifetime()); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceParams.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceParams.cs deleted file mode 100644 index b7f60c2d..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceParams.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System.Collections.Generic; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice -{ - public class ServiceParams : Dictionary - { - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceProviderExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceProviderExtensions.cs deleted file mode 100644 index f7b6854b..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/ServiceProviderExtensions.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Linq; -using Microsoft.Extensions.DependencyInjection; - -namespace VND.Fw.Infrastructure.AspNetCore.Miniservice -{ - public static class ServiceProviderExtensions - { - public static IOrderedEnumerable GetServicesByPriority( - this IServiceProvider svcProvider) - where TConfigureService : IPriorityConfigure - { - return svcProvider - .GetServices() - .OrderBy(x => x.Priority); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/VND.Fw.Infrastructure.AspNetCore.Miniservice.csproj b/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/VND.Fw.Infrastructure.AspNetCore.Miniservice.csproj deleted file mode 100644 index 42de6547..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.Miniservice/VND.Fw.Infrastructure.AspNetCore.Miniservice.csproj +++ /dev/null @@ -1,40 +0,0 @@ - - - - netstandard2.0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/AuthorizeCheckOperationFilter.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/AuthorizeCheckOperationFilter.cs deleted file mode 100644 index 21687739..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/AuthorizeCheckOperationFilter.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Authorization; -using Swashbuckle.AspNetCore.Swagger; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace VND.Fw.Infrastructure.AspNetCore.OpenApi -{ - public class AuthorizeCheckOperationFilter : IOperationFilter - { - public void Apply(Operation operation, OperationFilterContext context) - { - // Check for authorize attribute - var hasAuthorize = context.ApiDescription.ControllerAttributes().OfType().Any() || - context.ApiDescription.ActionAttributes().OfType().Any(); - - if (hasAuthorize) - { - operation.Responses.Add("401", new Response {Description = "Unauthorized"}); - operation.Responses.Add("403", new Response {Description = "Forbidden"}); - - operation.Security = new List>>(); - operation.Security.Add(new Dictionary> - { - {"oauth2", new[] {"swagger_id"}} - }); - } - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/DefaultValuesOperationFilter.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/DefaultValuesOperationFilter.cs deleted file mode 100644 index c7968eca..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/DefaultValuesOperationFilter.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Linq; -using Swashbuckle.AspNetCore.Swagger; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace VND.Fw.Infrastructure.AspNetCore.OpenApi -{ - /// - /// Represents the Swagger/Swashbuckle operation filter used to document the implicit API version parameter. - /// - /// - /// This is only required due to bugs in the . - /// Once they are fixed and published, this class can be removed. - /// - public class DefaultValuesOperationFilter : IOperationFilter - { - /// - /// Applies the filter to the specified operation using the given context. - /// - /// The operation to apply the filter to. - /// The current operation filter context. - public void Apply(Operation operation, OperationFilterContext context) - { - if (operation.Parameters == null) return; - - // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/412 - // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/413 - foreach (var parameter in operation.Parameters.OfType()) - { - var description = context.ApiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name); - var routeInfo = description.RouteInfo; - - if (parameter.Description == null) parameter.Description = description.ModelMetadata?.Description; - - if (routeInfo == null) continue; - - if (parameter.Default == null) parameter.Default = routeInfo.DefaultValue; - - parameter.Required |= !routeInfo.IsOptional; - } - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/OpenApiOptions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/OpenApiOptions.cs deleted file mode 100644 index 082c9423..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/OpenApiOptions.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace VND.Fw.Infrastructure.AspNetCore.OpenApi -{ - public class OpenApiOptions - { - public string Title { get; set; } = "API"; - public string Description { get; set; } = "An application with Swagger, Swashbuckle, and API versioning."; - public string ContactName { get; set; } = "Vietnam Devs"; - public string ContactEmail { get; set; } = "vietnam.devs.group@gmail.com"; - public string TermOfService { get; set; } = "Shareware"; - public string LicenseName { get; set; } = "MIT"; - public string LicenseUrl { get; set; } = "https://opensource.org/licenses/MIT"; - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/SecurityRequirementsOperationFilter.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/SecurityRequirementsOperationFilter.cs deleted file mode 100644 index 4d73128c..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/SecurityRequirementsOperationFilter.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Authorization; -using Swashbuckle.AspNetCore.Swagger; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace VND.Fw.Infrastructure.AspNetCore.OpenApi -{ - public class SecurityRequirementsOperationFilter : IOperationFilter - { - public void Apply(Operation operation, OperationFilterContext context) - { - // Policy names map to scopes - var requiredScopes = context.MethodInfo - .GetCustomAttributes(true) - .OfType() - .Select(attr => attr.Policy) - .Distinct(); - - if (requiredScopes.Any()) - { - operation.Responses.Add("401", new Response {Description = "Unauthorized"}); - operation.Responses.Add("403", new Response {Description = "Forbidden"}); - - operation.Security = new List>>(); - operation.Security.Add(new Dictionary> - { - {"oauth2", requiredScopes} - }); - } - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/VND.Fw.Infrastructure.AspNetCore.OpenApi.csproj b/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/VND.Fw.Infrastructure.AspNetCore.OpenApi.csproj deleted file mode 100644 index 8d4a1264..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/VND.Fw.Infrastructure.AspNetCore.OpenApi.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - netstandard2.0 - - - - - - - - - - - - - - - - - diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/index.html b/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/index.html deleted file mode 100644 index 985a01a0..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore.OpenApi/index.html +++ /dev/null @@ -1,100 +0,0 @@ - - - - - - %(DocumentTitle) - - - - - - %(HeadContent) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/AuthAttribute.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/AuthAttribute.cs deleted file mode 100644 index ea87f8c8..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/AuthAttribute.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Authorization; - -namespace VND.Fw.Infrastructure.AspNetCore -{ - public class AuthAttribute : AuthorizeAttribute - { - public AuthAttribute(string policy = null) - { - AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme; - Policy = policy; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/ControllerBase.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/ControllerBase.cs deleted file mode 100644 index 5e577b63..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/ControllerBase.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Threading.Tasks; -using MediatR; -using Microsoft.AspNetCore.Mvc; -using VND.Fw.Domain; -using VND.Fw.Infrastructure.EfCore.Extensions; -using VND.Fw.Infrastructure.EfCore.Repository; - -namespace VND.Fw.Infrastructure.AspNetCore -{ - [ApiController] - public abstract class EvtControllerBase : Controller - { - protected IMediator Eventor; - - protected EvtControllerBase(IMediator eventor) - { - Eventor = eventor; - } - } - - [ApiController] - public abstract class EfCoreControllerBase : Controller - where TEntity : EntityBase - { - protected readonly IEfQueryRepository QueryRepository; - protected readonly IEfRepositoryAsync MutateRepository; - - protected EfCoreControllerBase( - IEfQueryRepository queryRepository, - IEfRepositoryAsync mutateRepository) - { - QueryRepository = queryRepository; - MutateRepository = mutateRepository; - } - } - - /// - /// https://github.com/FabianGosebrink/ASPNETCore-WebAPI-Sample/blob/master/SampleWebApiAspNetCore/Controllers/v1/FoodsController.cs - /// - /// - [ApiController] - public abstract class CrudControllerBase : EfCoreControllerBase - where TEntity : EntityBase - { - protected CrudControllerBase( - IEfQueryRepository queryRepository, - IEfRepositoryAsync mutateRepository) - : base(queryRepository, mutateRepository) - { - } - - [HttpGet(Name = nameof(GetAllItems))] - public async Task>> GetAllItems([FromQuery] Criterion criterion) - { - criterion = criterion ?? new Criterion(); - return await QueryRepository.QueryAsync(criterion, entity => entity); - } - - [HttpGet("{id}", Name = nameof(GetItem))] - public async Task> GetItem(Guid id) - { - return await QueryRepository.GetByIdAsync(id); - } - - [HttpPost(Name = nameof(PostItem))] - public async Task PostItem(TEntity entity) - { - return await MutateRepository.AddAsync(entity); - } - - [HttpPut("{id}", Name = nameof(PutItem))] - public async Task PutItem(int id, TEntity entity) - { - return await MutateRepository.UpdateAsync(entity); - } - - [HttpDelete("{id}", Name = nameof(DeleteItem))] - public async Task DeleteItem(Guid id) - { - return await MutateRepository.DeleteAsync(await QueryRepository.GetByIdAsync(id)); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/ApiExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/ApiExtensions.cs deleted file mode 100644 index 145ff44f..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/ApiExtensions.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; -using VND.Fw.Domain; -using VND.Fw.Utils.Extensions; - -namespace VND.Fw.Infrastructure.AspNetCore.Extensions -{ - public static class ApiExtensions - { - public static List CreateLinksForCollection(this IUrlHelper urlHelper, string methodName, - Criterion criterion, int totalCount) - { - var links = new List(); - - // self - links.Add( - new LinkItem(urlHelper.Link(methodName, new - { - pagecount = criterion.PageSize, - page = criterion.CurrentPage, - orderby = criterion.SortBy - }), "self", "GET")); - - links.Add(new LinkItem(urlHelper.Link(methodName, new - { - pagecount = criterion.PageSize, - page = 1, - orderby = criterion.SortBy - }), "first", "GET")); - - links.Add(new LinkItem(urlHelper.Link(methodName, new - { - pagecount = criterion.PageSize, - page = criterion.GetTotalPages(totalCount), - orderby = criterion.SortBy - }), "last", "GET")); - - if (criterion.HasNext(totalCount)) - links.Add(new LinkItem(urlHelper.Link(methodName, new - { - pagecount = criterion.PageSize, - page = criterion.CurrentPage + 1, - orderby = criterion.SortBy - }), "next", "GET")); - - if (criterion.HasPrevious()) - links.Add(new LinkItem(urlHelper.Link(methodName, new - { - pagecount = criterion.PageSize, - page = criterion.CurrentPage - 1, - orderby = criterion.SortBy - }), "previous", "GET")); - - return links; - } - - public static dynamic ExpandSingleItem(this IUrlHelper urlHelper, string methodName, IdModelBase item) - { - var links = GetLinks(urlHelper, methodName, item.Id); - var resource = item.ToDynamic() as IDictionary; - resource.Add("links", links); - - return resource; - } - - public static void AddPaginateInfo(this HttpResponse httpResponse, Criterion criterion, int numberOfItems) - { - var paginationMetadata = new - { - totalCount = numberOfItems, - pageSize = criterion.PageSize, - currentPage = criterion.CurrentPage, - totalPages = criterion.GetTotalPages(numberOfItems) - }; - - httpResponse.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata)); - } - - private static IEnumerable GetLinks(IUrlHelper urlHelper, string methodName, Guid id) - { - var links = new List(); - - links.Add( - new LinkItem( - urlHelper.Link(methodName, new {id}), - "self", - "GET")); - - return links; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/CriterionExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/CriterionExtensions.cs deleted file mode 100644 index fc22a4ad..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/CriterionExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Linq; -using VND.Fw.Domain; - -namespace VND.Fw.Infrastructure.AspNetCore.Extensions -{ - public static class CriterionExtensions - { - public static bool HasPrevious(this Criterion criterion) - { - return criterion.CurrentPage > 1; - } - - public static bool HasNext(this Criterion criterion, int totalCount) - { - return criterion.CurrentPage < (int)GetTotalPages(criterion, totalCount); - } - - public static double GetTotalPages(this Criterion criterion, int totalCount) - { - return Math.Ceiling(totalCount / (double)criterion.PageSize); - } - - public static bool HasQuery(this Criterion criterion) - { - return !string.IsNullOrEmpty(criterion.SortBy); - } - - public static bool IsDescending(this Criterion criterion) - { - if (!string.IsNullOrEmpty(criterion.SortOrder)) - return criterion.SortOrder.Split(' ').Last().ToLowerInvariant().StartsWith("desc"); - return false; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HostUriExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HostUriExtensions.cs deleted file mode 100644 index 739de972..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HostUriExtensions.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; - -namespace VND.Fw.Infrastructure.AspNetCore.Extensions -{ - public static class HostUriExtensions - { - public static string GetHostUri(this IConfiguration config, IHostingEnvironment env, string groupName) - { - if (env.IsDevelopment()) return config.GetExternalHostUri(groupName); - return config.GetInternalHostUri(groupName); - } - - public static string GetInternalHostUri(this IConfiguration config, string groupName) - { - var group = - config - .GetSection("Hosts") - ?.GetSection("Internals") - ?.GetSection(groupName); - - var serviceHost = $"{Environment.GetEnvironmentVariable(group.GetValue("Host"))}"; - var servicePort = $"{Environment.GetEnvironmentVariable(group.GetValue("Port"))}"; - - return $"http://{serviceHost}:{servicePort}"; - } - - public static string GetExternalHostUri(this IConfiguration config, string groupName) - { - var group = - config - .GetSection("Hosts") - ?.GetSection("Externals") - ?.GetSection(groupName); - - return group.GetValue("Uri"); - } - - public static string GetBasePath(this IConfiguration config) - { - return config.GetSection("Hosts")?.GetValue("BasePath"); - } - - public static string GetExternalCurrentHostUri(this IConfiguration config) - { - return config.GetSection("Hosts")?.GetSection("Externals")?.GetValue("CurrentUri"); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HttpRequestExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HttpRequestExtensions.cs deleted file mode 100644 index acc50d5d..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HttpRequestExtensions.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Http; - -namespace VND.Fw.Infrastructure.AspNetCore.Extensions -{ - public static class HttpRequestExtensions - { - /// - /// Follow at http://opentracing.io/documentation/pages/spec - /// - /// - /// - public static IEnumerable> GetOpenTracingInfo(this HttpRequest request) - { - return request.Headers.Where(x => - x.Key == "x-request-id" || - x.Key == "x-b3-traceid" || - x.Key == "x-b3-spanid" || - x.Key == "x-b3-parentspanid" || - x.Key == "x-b3-sampled" || - x.Key == "x-b3-flags" || - x.Key == "x-ot-span-context" /* || x.Key == "Authorization" */ - ).Select(y => - new KeyValuePair( - y.Key, - y.Value.FirstOrDefault())); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HttpResponseExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HttpResponseExtensions.cs deleted file mode 100644 index 9a7ea5ae..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/HttpResponseExtensions.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Text; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.WebUtilities; -using Newtonsoft.Json; - -namespace VND.Fw.Infrastructure.AspNetCore.Extensions -{ - public static class HttpResponseExtensions - { - private static readonly JsonSerializer Serializer = new JsonSerializer - { - NullValueHandling = NullValueHandling.Ignore - }; - - public static void WriteJson(this HttpResponse response, T obj, string contentType = null) - { - response.ContentType = contentType ?? "application/json"; - using (var writer = new HttpResponseStreamWriter(response.Body, Encoding.UTF8)) - { - using (var jsonWriter = new JsonTextWriter(writer)) - { - jsonWriter.CloseOutput = false; - jsonWriter.AutoCompleteOnClose = false; - - Serializer.Serialize(jsonWriter, obj); - } - } - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/ServiceCollectionExtensions.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/ServiceCollectionExtensions.cs deleted file mode 100644 index ea17095f..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Extensions/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Net; -using System.Net.Http; -using Microsoft.Extensions.DependencyInjection; -using Polly; -using Polly.Extensions.Http; - -namespace VND.Fw.Infrastructure.AspNetCore.Extensions -{ - public static class ServiceCollectionExtensions - { - public static IServiceCollection AddHttpPolly(this IServiceCollection services) - where TRestClient : class - { - services.AddHttpClient() - .SetHandlerLifetime(TimeSpan.FromMinutes(1)) - .AddPolicyHandler(GetRetryPolicy()) - .AddPolicyHandler(GetCircuitBreakerPolicy()); - - return services; - } - - private static IAsyncPolicy GetRetryPolicy() - { - return HttpPolicyExtensions - .HandleTransientHttpError() - .OrResult(msg => msg.StatusCode == HttpStatusCode.NotFound) - .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); - } - - private static IAsyncPolicy GetCircuitBreakerPolicy() - { - return HttpPolicyExtensions - .HandleTransientHttpError() - .CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/LinkItem.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/LinkItem.cs deleted file mode 100644 index 78774df4..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/LinkItem.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace VND.Fw.Infrastructure.AspNetCore -{ - public class LinkItem - { - public string Href { get; set; } - public string Rel { get; set; } - public string Method { get; set; } - - public LinkItem(string href, string rel, string method) - { - Href = href; - Rel = rel; - Method = method; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Middlewares/ErrorHandlerMiddleware.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Middlewares/ErrorHandlerMiddleware.cs deleted file mode 100644 index 2b7be8e1..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Middlewares/ErrorHandlerMiddleware.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Net; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; -using VND.Fw.Domain; - -namespace VND.Fw.Infrastructure.AspNetCore.Middlewares -{ - public class ErrorHandlerMiddleware - { - private readonly RequestDelegate _next; - - public ErrorHandlerMiddleware(RequestDelegate next) - { - _next = next; - } - - public async Task Invoke(HttpContext context) - { - try - { - await _next(context); - } - catch (Exception exception) - { - await HandleErrorAsync(context, exception); - } - } - - private static Task HandleErrorAsync(HttpContext context, Exception exception) - { - var errorCode = "error"; - var statusCode = HttpStatusCode.BadRequest; - var message = "There was an error."; - switch (exception) - { - case CoreException e: - message = e.Message; - break; - } - - var response = new - { - code = errorCode, - message = exception.Message - }; - var payload = JsonConvert.SerializeObject(response); - context.Response.ContentType = "application/json"; - context.Response.StatusCode = (int)statusCode; - - return context.Response.WriteAsync(payload); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Middlewares/LogHandlerMiddleware.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Middlewares/LogHandlerMiddleware.cs deleted file mode 100644 index f6c78810..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Middlewares/LogHandlerMiddleware.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.Extensions.Logging; - -namespace VND.Fw.Infrastructure.AspNetCore.Middlewares -{ - public class LogHandlerMiddleware - { - private readonly ILogger _logger; - private readonly RequestDelegate _next; - - public LogHandlerMiddleware(ILogger logger, RequestDelegate next) - { - _logger = logger; - _next = next; - } - - public async Task Invoke(HttpContext context) - { - context.Items["CorrelationId"] = Guid.NewGuid().ToString(); - _logger.LogInformation($"About to start {context.Request.Method} {context.Request.GetDisplayUrl()} request"); - - await _next(context); - - _logger.LogInformation($"Request completed with status code: {context.Response.StatusCode} "); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/ModelBase.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/ModelBase.cs deleted file mode 100644 index 6432b780..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/ModelBase.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; - -namespace VND.Fw.Infrastructure.AspNetCore -{ - public abstract class ModelBase - { - } - - public abstract class IdModelBase : ModelBase - { - [Required] - public Guid Id { get; set; } - } - - public abstract class RequestModelBase : ModelBase - { - public IEnumerable> Headers { get; set; } - } - - public abstract class RequestIdModelBase : IdModelBase - { - public IEnumerable> Headers { get; set; } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/ProxyService.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/ProxyService.cs deleted file mode 100644 index fd26b9ce..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/ProxyService.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace VND.Fw.Infrastructure.AspNetCore -{ - public abstract class ProxyServiceBase - { - protected readonly RestClient RestClient; - - protected ProxyServiceBase(RestClient rest) - { - RestClient = rest; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/RestClient.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/RestClient.cs deleted file mode 100644 index bf2c3ebf..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/RestClient.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; - -namespace VND.Fw.Infrastructure.AspNetCore -{ - public class RestClient - { - private readonly HttpClient _client; - private IEnumerable> _openTracingInfo; - private readonly ILogger _logger; - - public RestClient(HttpClient httpClient, ILoggerFactory logger) - { - _client = httpClient; - _logger = logger.CreateLogger(); - } - - public void SetOpenTracingInfo(IEnumerable> info) - { - _openTracingInfo = info; - } - - public async Task GetAsync(string serviceUrl) - where TReturnMessage : class, new() - { - HttpClient enrichClient = EnrichHeaderInfo(_client, _openTracingInfo); - - HttpResponseMessage response = await enrichClient.GetAsync(serviceUrl); - response.EnsureSuccessStatusCode(); - - if (!response.IsSuccessStatusCode) - { - return await Task.FromResult(new TReturnMessage()); - } - - string result = await response.Content.ReadAsStringAsync(); - - return JsonConvert.DeserializeObject(result); - } - - public async Task PostAsync(string serviceUrl, object dataObject = null) - where TReturnMessage : class, new() - { - HttpClient enrichClient = EnrichHeaderInfo(_client, _openTracingInfo); - string content = dataObject != null ? JsonConvert.SerializeObject(dataObject) : "{}"; - - HttpResponseMessage response = await _client.PostAsync(serviceUrl, GetStringContent(content)); - response.EnsureSuccessStatusCode(); - - if (!response.IsSuccessStatusCode) - { - return await Task.FromResult(new TReturnMessage()); - } - - string result = await response.Content.ReadAsStringAsync(); - - return JsonConvert.DeserializeObject(result); - } - - public async Task PutAsync(string serviceUrl, object dataObject = null) - where TReturnMessage : class, new() - { - HttpClient enrichClient = EnrichHeaderInfo(_client, _openTracingInfo); - string content = dataObject != null ? JsonConvert.SerializeObject(dataObject) : "{}"; - - HttpResponseMessage response = await _client.PutAsync(serviceUrl, GetStringContent(content)); - response.EnsureSuccessStatusCode(); - - if (!response.IsSuccessStatusCode) - { - return await Task.FromResult(new TReturnMessage()); - } - - string result = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject(result); - } - - public async Task DeleteAsync(string serviceUrl) - { - HttpClient enrichClient = EnrichHeaderInfo(_client, _openTracingInfo); - - HttpResponseMessage response = await _client.DeleteAsync(serviceUrl); - response.EnsureSuccessStatusCode(); - - if (!response.IsSuccessStatusCode) - { - return await Task.FromResult(false); - } - - string result = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject(result); - } - - private static StringContent GetStringContent(string content) - { - return new StringContent(content, Encoding.UTF8, "application/json"); - } - - private HttpClient EnrichHeaderInfo( - HttpClient client, - IEnumerable> openTracingInfo) - { - // _logger.LogDebug($"VND: {openTracingInfo.ToArray().ToString()}"); - - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - - if (openTracingInfo != null) - { - foreach (KeyValuePair info in openTracingInfo) - { - if (!client.DefaultRequestHeaders.Contains(info.Key)) - { - client.DefaultRequestHeaders.Add(info.Key, info.Value); - } - } - } - - return client; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/VND.FW.Infrastructure.AspNetCore.csproj b/src/framework/VND.Fw.Infrastructure.AspNetCore/VND.FW.Infrastructure.AspNetCore.csproj deleted file mode 100644 index 47d1ceff..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/VND.FW.Infrastructure.AspNetCore.csproj +++ /dev/null @@ -1,45 +0,0 @@ - - - - netstandard2.0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationError.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationError.cs deleted file mode 100644 index dcac9a01..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationError.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace VND.Fw.Infrastructure.AspNetCore.Validation -{ - public class ValidationError - { - public string Name { get; set; } - public string Description { get; set; } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationProblemDetails.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationProblemDetails.cs deleted file mode 100644 index b3af3dec..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationProblemDetails.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; -using Microsoft.AspNetCore.Mvc; - -namespace VND.Fw.Infrastructure.AspNetCore.Validation -{ - public class ValidationProblemDetails : ProblemDetails - { - public ICollection ValidationErrors { get; set; } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationProblemDetailsResult.cs b/src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationProblemDetailsResult.cs deleted file mode 100644 index 167fd668..00000000 --- a/src/framework/VND.Fw.Infrastructure.AspNetCore/Validation/ValidationProblemDetailsResult.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using VND.Fw.Infrastructure.AspNetCore.Extensions; - -namespace VND.Fw.Infrastructure.AspNetCore.Validation -{ - /// - /// Reference at https://www.strathweb.com/2018/07/centralized-exception-handling-and-request-validation-in-asp-net-core - /// - public class ValidationProblemDetailsResult : IActionResult - { - public Task ExecuteResultAsync(ActionContext context) - { - var modelStateEntries = context.ModelState.Where(e => e.Value.Errors.Count > 0).ToArray(); - var errors = new List(); - - var details = "See ValidationErrors for details"; - - if (modelStateEntries.Any()) - { - if (modelStateEntries.Length == 1 - && modelStateEntries[0].Value.Errors.Count == 1 - && modelStateEntries[0].Key == string.Empty) - details = modelStateEntries[0].Value.Errors[0].ErrorMessage; - else - foreach (var modelStateEntry in modelStateEntries) - foreach (var modelStateError in modelStateEntry.Value.Errors) - { - var error = new ValidationError - { - Name = modelStateEntry.Key, - Description = modelStateError.ErrorMessage - }; - - errors.Add(error); - } - } - - var problemDetails = new ValidationProblemDetails - { - Status = 400, - Title = "Request Validation Error", - Instance = $"urn:myorganization:badrequest:{Guid.NewGuid()}", - Detail = details, - ValidationErrors = errors - }; - - context.HttpContext.Response.WriteJson(problemDetails); - return Task.CompletedTask; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/Options/MsSqlDbOptions.cs b/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/Options/MsSqlDbOptions.cs deleted file mode 100644 index 388c4f9e..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/Options/MsSqlDbOptions.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace VND.Fw.Infrastructure.EfCore.SqlServer.Options -{ - public class MsSqlDbOptions - { - public string Host { get; set; } - public string Port { get; set; } - public string Database { get; set; } - public string UserName { get; set; } - public string Password { get; set; } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/ServiceCollectionExtensions.cs b/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/ServiceCollectionExtensions.cs deleted file mode 100644 index 4257be37..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using VND.Fw.Infrastructure.EfCore.Db; -using VND.Fw.Infrastructure.EfCore.SqlServer.Options; - -namespace VND.Fw.Infrastructure.EfCore.SqlServer -{ - public static class ServiceCollectionExtensions - { - public static IServiceCollection AddEfCoreSqlServer(this IServiceCollection services) - { - var svcProvider = services.BuildServiceProvider(); - var config = svcProvider.GetRequiredService(); - - services.Configure(config.GetSection("k8s:mssqldb")); - - services.AddScoped(); - services.AddScoped(); - - return services; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/SqlServerDatabaseConnectionStringFactory.cs b/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/SqlServerDatabaseConnectionStringFactory.cs deleted file mode 100644 index e8a38175..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/SqlServerDatabaseConnectionStringFactory.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using VND.Fw.Infrastructure.EfCore.Db; - -namespace VND.Fw.Infrastructure.EfCore.SqlServer -{ - public sealed class SqlServerDatabaseConnectionStringFactory : IDatabaseConnectionStringFactory - { - private readonly IConfiguration _config; - private readonly IHostingEnvironment _env; - - public SqlServerDatabaseConnectionStringFactory( - IConfiguration config, - IHostingEnvironment env) - { - _config = config; - _env = env; - } - - public string Create() - { - if (_env.IsDevelopment()) - { - return _config.GetConnectionString("mssqldb"); - } - - return string.Format( - _config.GetConnectionString("mssqldb"), - Environment.GetEnvironmentVariable(_config.GetValue("k8s:mssqldb:Host")), - Environment.GetEnvironmentVariable(_config.GetValue("k8s:mssqldb:Port")), - _config.GetValue("k8s:mssqldb:Database"), - _config.GetValue("k8s:mssqldb:UserName"), - _config.GetValue("k8s:mssqldb:Password")); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/SqlServerDbContextOptionsBuilderFactory.cs b/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/SqlServerDbContextOptionsBuilderFactory.cs deleted file mode 100644 index 73778ed9..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/SqlServerDbContextOptionsBuilderFactory.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore; -using VND.Fw.Infrastructure.EfCore.Db; - -namespace VND.Fw.Infrastructure.EfCore.SqlServer -{ - public sealed class SqlServerDbContextOptionsBuilderFactory : IExtendDbContextOptionsBuilder - { - public DbContextOptionsBuilder Extend( - DbContextOptionsBuilder optionsBuilder, - IDatabaseConnectionStringFactory connectionStringFactory, - string assemblyName) - { - return optionsBuilder.UseSqlServer( - connectionStringFactory.Create(), - sqlOptions => - { - sqlOptions.MigrationsAssembly(assemblyName); - sqlOptions.EnableRetryOnFailure( - maxRetryCount: 15, - maxRetryDelay: TimeSpan.FromSeconds(30), - errorNumbersToAdd: null); - }) - .EnableSensitiveDataLogging(); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/VND.Fw.Infrastructure.EfCore.SqlServer.csproj b/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/VND.Fw.Infrastructure.EfCore.SqlServer.csproj deleted file mode 100644 index 5148d613..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore.SqlServer/VND.Fw.Infrastructure.EfCore.SqlServer.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - netstandard2.0 - - - - - - - - - - - - - diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Db/ApplicationDbContext.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Db/ApplicationDbContext.cs deleted file mode 100644 index 3639bdc2..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Db/ApplicationDbContext.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Humanizer; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.Extensions.Configuration; -using VND.Fw.Domain; -using VND.Fw.Utils.Extensions; - -namespace VND.Fw.Infrastructure.EfCore.Db -{ - public abstract class ApplicationDbContext : DbContext - { - protected ApplicationDbContext(DbContextOptions options) : base(options) - { - } - - protected override void OnModelCreating(ModelBuilder builder) - { - var config = this.GetService(); - - var typeToRegisters = new List(); - - var ourModules = config - .GetValue("EfCore:FullyQualifiedPrefix") - .LoadAssemblyWithPattern(); - - typeToRegisters.AddRange(ourModules.SelectMany(m => m.DefinedTypes)); - - RegisterEntities(builder, typeToRegisters); - - RegisterConvention(builder); - - base.OnModelCreating(builder); - - RegisterCustomMappings(builder, typeToRegisters); - } - - private static void RegisterEntities(ModelBuilder modelBuilder, IEnumerable typeToRegisters) - { - // TODO: will optimize this more - var types = typeToRegisters.Where(x => - typeof(IEntity).IsAssignableFrom(x) && - !x.GetTypeInfo().IsAbstract); - - foreach (var type in types) modelBuilder.Entity(type); - } - - private static void RegisterConvention(ModelBuilder modelBuilder) - { - var types = modelBuilder.Model.GetEntityTypes() - .Where(entity => entity.ClrType.Namespace != null); - - foreach (var entityType in types) - modelBuilder.Entity(entityType.Name).ToTable(entityType.ClrType.Name.Pluralize()); - } - - private static void RegisterCustomMappings(ModelBuilder modelBuilder, IEnumerable typeToRegisters) - { - var customModelBuilderTypes = - typeToRegisters.Where(x => typeof(ICustomModelBuilder).IsAssignableFrom(x)); - - foreach (var builderType in customModelBuilderTypes) - if (builderType != null && builderType != typeof(ICustomModelBuilder)) - { - var builder = (ICustomModelBuilder)Activator.CreateInstance(builderType); - builder.Build(modelBuilder); - } - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Db/ICustomModelBuilder.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Db/ICustomModelBuilder.cs deleted file mode 100644 index 52606760..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Db/ICustomModelBuilder.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Microsoft.EntityFrameworkCore; - -namespace VND.Fw.Infrastructure.EfCore.Db -{ - public interface ICustomModelBuilder - { - void Build(ModelBuilder modelBuilder); - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Db/IDatabaseConnectionStringFactory.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Db/IDatabaseConnectionStringFactory.cs deleted file mode 100644 index b60ffcf1..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Db/IDatabaseConnectionStringFactory.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace VND.Fw.Infrastructure.EfCore.Db -{ - public interface IDatabaseConnectionStringFactory - { - string Create(); - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Db/IExtendDbContextOptionsBuilder.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Db/IExtendDbContextOptionsBuilder.cs deleted file mode 100644 index 3b97b43e..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Db/IExtendDbContextOptionsBuilder.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Microsoft.EntityFrameworkCore; - -namespace VND.Fw.Infrastructure.EfCore.Db -{ - public interface IExtendDbContextOptionsBuilder - { - DbContextOptionsBuilder Extend( - DbContextOptionsBuilder optionsBuilder, - IDatabaseConnectionStringFactory connectionStringFactory, - string assemblyName); - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/DbContextExtensions.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/DbContextExtensions.cs deleted file mode 100644 index e3988fce..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/DbContextExtensions.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Linq; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace VND.Fw.Infrastructure.EfCore.Extensions -{ - public static class DbContextExtensions - { - public static bool AllMigrationsApplied(this DbContext context) - { - var applied = context.GetService() - .GetAppliedMigrations() - .Select(m => m.MigrationId); - - var total = context.GetService() - .Migrations - .Select(m => m.Key); - - return !total.Except(applied).Any(); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/EfRepositoryExtensions.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/EfRepositoryExtensions.cs deleted file mode 100644 index 2d31c94b..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/EfRepositoryExtensions.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; -using VND.Fw.Domain; -using VND.Fw.Infrastructure.EfCore.Repository; - -namespace VND.Fw.Infrastructure.EfCore.Extensions -{ - public static class EfRepositoryExtensions - { - public static async Task GetByIdAsync( - this IEfQueryRepository repo, - Guid id, - Func, IIncludableQueryable> include = null, - bool tracking = true) - where TDbContext : DbContext - where TEntity : class, IEntity - - { - var queryable = repo.Queryable(); - - if (!tracking) - { - queryable = queryable.AsNoTracking(); - } - - if (include != null) - { - queryable = include(queryable); - } - - return await queryable.SingleOrDefaultAsync(e => e.Id.Equals(id)); - } - - public static async Task FindOneAsync( - this IEfQueryRepository repo, - Expression> filter, - Func, IIncludableQueryable> include = null, - bool disableTracking = true) - where TDbContext : DbContext - where TEntity : class, IEntity - { - var queryable = repo.Queryable(); - - include?.Invoke(queryable); - - if (disableTracking) - { - queryable = queryable.AsNoTracking() as IQueryable; - } - - return await queryable.FirstOrDefaultAsync(filter); - } - - public static async Task> ListAsync( - this IEfQueryRepository repo, - Func, IIncludableQueryable> include = null, - bool disableTracking = true) - where TDbContext : DbContext - where TEntity : class, IEntity - { - var queryable = repo.Queryable(); - if (disableTracking) - { - queryable = queryable.AsNoTracking() as IQueryable; - } - - include?.Invoke(queryable); - - return await queryable.ToListAsync(); - } - - public static async Task> QueryAsync( - this IEfQueryRepository repo, - Criterion criterion, - Expression> selector, - Func, IIncludableQueryable> include = null, - bool disableTracking = true) - where TDbContext : DbContext - where TEntity : class, IEntity - { - return await GetDataAsync(repo, criterion, selector, null, include, disableTracking); - } - - public static async Task> FindAllAsync( - this IEfQueryRepository repo, - Criterion criterion, - Expression> selector, - Expression> filter, - Func, IIncludableQueryable> include = null, - bool disableTracking = true) - where TDbContext : DbContext - where TEntity : class, IEntity - { - return await GetDataAsync(repo, criterion, selector, filter, include, disableTracking); - } - - private static async Task> GetDataAsync( - IEfQueryRepository repo, - Criterion criterion, - Expression> selector, - Expression> filter = null, - Func, IIncludableQueryable> include = null, - bool disableTracking = true) - where TDbContext : DbContext - where TEntity : class, IEntity - { - var queryable = repo.Queryable(); - if (disableTracking) - { - queryable = queryable.AsNoTracking() as IQueryable; - } - - include?.Invoke(queryable); - - if (filter != null) - { - queryable = queryable.Where(filter); - } - - if (!string.IsNullOrWhiteSpace(criterion.SortBy)) - { - bool isDesc = string.Equals(criterion.SortOrder, "desc", StringComparison.OrdinalIgnoreCase) ? true : false; - queryable = queryable.OrderByPropertyName(criterion.SortBy, isDesc); - } - - var results = await queryable - .Skip(criterion.CurrentPage * criterion.PageSize) - .Take(criterion.PageSize) - .Select(selector) - .ToListAsync(); - - var totalRecord = await queryable.CountAsync(); - var totalPages = (int)Math.Ceiling((double)totalRecord / criterion.PageSize); - - if (criterion.CurrentPage > totalPages) - { - // criterion.SetCurrentPage(totalPages); - } - - return new PaginatedItem(totalRecord, totalPages, results); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/OrderByExtension.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/OrderByExtension.cs deleted file mode 100644 index ae78da93..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/OrderByExtension.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using VND.Fw.Domain; - -namespace VND.Fw.Infrastructure.EfCore.Extensions -{ - public static class OrderByExtension - { - public static IQueryable OrderByPropertyName(this IQueryable source, string propertyName, bool isDescending) - where TEntity : IEntity - { - if (source == null) - { - throw new ArgumentException("source"); - } - - if (string.IsNullOrWhiteSpace(propertyName)) - { - throw new ArgumentException("propertyName"); - } - - Type type = typeof(TEntity); - ParameterExpression arg = Expression.Parameter(type, "x"); - PropertyInfo propertyInfo = type.GetProperty(propertyName); - Expression expression = Expression.Property(arg, propertyInfo); - type = propertyInfo.PropertyType; - - Type delegateType = typeof(Func<,>).MakeGenericType(typeof(TEntity), type); - LambdaExpression lambda = Expression.Lambda(delegateType, expression, arg); - - string methodName = isDescending ? "OrderByDescending" : "OrderBy"; - object result = typeof(Queryable).GetMethods().Single( - method => method.Name == methodName - && method.IsGenericMethodDefinition - && method.GetGenericArguments().Length == 2 - && method.GetParameters().Length == 2) - .MakeGenericMethod(typeof(TEntity), type) - .Invoke(null, new object[] { source, lambda }); - - return (IQueryable)result; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/QueryRepositoryFactoryExtensions.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/QueryRepositoryFactoryExtensions.cs deleted file mode 100644 index 3efb960f..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/QueryRepositoryFactoryExtensions.cs +++ /dev/null @@ -1,14 +0,0 @@ -using VND.Fw.Domain; -using VND.Fw.Infrastructure.EfCore.Repository; - -namespace VND.Fw.Infrastructure.EfCore.Extensions -{ - public static class EfQueryRepositoryFactoryExtensions - { - public static IEfQueryRepository QueryEfRepository(this IQueryRepositoryFactory factory) - where TEntity : IEntity - { - return factory.QueryRepository() as IEfQueryRepository; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/ServiceCollectionExtensions.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/ServiceCollectionExtensions.cs deleted file mode 100644 index 7356ae76..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using VND.Fw.Domain; -using VND.Fw.Infrastructure.EfCore.Db; -using VND.Fw.Infrastructure.EfCore.Repository; -using VND.Fw.Utils.Extensions; - -namespace VND.Fw.Infrastructure.EfCore.Extensions -{ - public static class ServiceCollectionExtensions - { - public static IServiceCollection AddEfCore(this IServiceCollection services) - { - var serviceProvider = services.BuildServiceProvider(); - var fullyQualifiedPrefix = serviceProvider - .GetRequiredService() - .GetValue("EfCore:FullyQualifiedPrefix"); - - var entityTypes = fullyQualifiedPrefix - .LoadAssemblyWithPattern() - .SelectMany(m => m.DefinedTypes) - .Where(x => typeof(IEntity).IsAssignableFrom(x) && !x.GetTypeInfo().IsAbstract); - - foreach (var entity in entityTypes) - { - var repoType = typeof(IEfRepositoryAsync<>).MakeGenericType(entity); - var implRepoType = typeof(EfRepositoryAsync<>).MakeGenericType(entity); - services.AddSingleton(repoType, implRepoType); - - var queryRepoType = typeof(IEfQueryRepository<>).MakeGenericType(entity); - var implQueryRepoType = typeof(EfQueryRepository<>).MakeGenericType(entity); - services.AddSingleton(queryRepoType, implQueryRepoType); - } - - services.AddSingleton( - typeof(IUnitOfWorkAsync), resolver => - new EfUnitOfWork( - resolver.GetService(), - resolver.GetService())); - - services.AddSingleton( - typeof(IQueryRepositoryFactory), resolver => - new EfQueryRepositoryFactory(resolver.GetService())); - - // by default, we register the in-memory database - services.AddSingleton(typeof(IDatabaseConnectionStringFactory), typeof(NoOpDatabaseConnectionStringFactory)); - services.AddSingleton(typeof(IExtendDbContextOptionsBuilder), typeof(InMemoryDbContextOptionsBuilderFactory)); - - return services; - } - } - - public class NoOpDatabaseConnectionStringFactory : IDatabaseConnectionStringFactory - { - public string Create() - { - return string.Empty; - } - } - - public class InMemoryDbContextOptionsBuilderFactory : IExtendDbContextOptionsBuilder - { - public DbContextOptionsBuilder Extend( - DbContextOptionsBuilder optionsBuilder, - IDatabaseConnectionStringFactory connectionStringFactory, - string assemblyName) - { - return optionsBuilder.UseSqlite( - "Data Source=App_Data\\localdb.db", - sqlOptions => - { - sqlOptions.MigrationsAssembly(assemblyName); - }); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/WebHostExtensions.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/WebHostExtensions.cs deleted file mode 100644 index 9b79bf2a..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Extensions/WebHostExtensions.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Hosting; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using VND.Fw.Infrastructure.EfCore.Migration; -using VND.Fw.Utils.Extensions; - -namespace VND.Fw.Infrastructure.EfCore.Extensions -{ - public static class WebHostExtensions - { - public static IServiceProvider MigrateDbContext(this IServiceProvider serviceProvider) - where TDbContext : DbContext - { - return serviceProvider.MigrateDbContext((context, services) => - { - InstanceSeedData(services, context, typeof(ISeedData<>)); - }); - } - - public static IWebHost RegisterDbContext(this IWebHost webHost) - where TDbContext : DbContext - { - return webHost - .MigrateDbContext((context, services) => - { - InstanceSeedData(services, context, typeof(ISeedData<>)); - }); - } - - internal static IWebHost MigrateDbContext(this IWebHost webHost, - Action seeder) - where TContext : DbContext - { - using (var scope = webHost.Services.CreateScope()) - { - scope.ServiceProvider.MigrateDbContext(seeder); - } - - return webHost; - } - - public static void InstanceSeedData(this IServiceProvider resolver, DbContext context, Type seedData) - { - var configuration = resolver.GetService(); - var scanAssemblyPattern = configuration.GetSection("EfCore")["FullyQualifiedPrefix"]; - var seeders = scanAssemblyPattern.ResolveModularGenericTypes(seedData, context.GetType()); - - if (seeders == null) return; - - foreach (var seeder in seeders) - { - var seedInstance = Activator.CreateInstance(seeder, configuration); - var method = seeder.GetMethod("SeedAsync"); - ((Task)method.Invoke(seedInstance, new object[] {context})).Wait(); - } - } - - /// - /// This function will open up the door to make the Setup page - /// Because we can call to this function for provision new database - /// - /// - /// - /// - public static IServiceProvider MigrateDbContext( - this IServiceProvider serviceProvider, - Action seeder) - where TDbContext : DbContext - { - var logger = serviceProvider.GetRequiredService>(); - var context = serviceProvider.GetRequiredService(); - - logger.LogInformation($"[VND] Migrating database associated with {typeof(TDbContext).FullName} context."); - context.Database.OpenConnection(); - if (!context.AllMigrationsApplied()) context.Database.Migrate(); - - logger.LogInformation($"[VND] Start to seed data for {typeof(TDbContext).FullName} context."); - seeder(context, serviceProvider); - - logger.LogInformation($"[VND] Migrated database associated with {typeof(TDbContext).FullName} context."); - return serviceProvider; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Identity/ApplicationRole.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Identity/ApplicationRole.cs deleted file mode 100644 index 20507b1d..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Identity/ApplicationRole.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; -using Microsoft.AspNetCore.Identity; - -namespace VND.Fw.Infrastructure.EfCore.Identity -{ - public class ApplicationRole : IdentityRole - { - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Identity/ApplicationUser.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Identity/ApplicationUser.cs deleted file mode 100644 index 8a1fce3d..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Identity/ApplicationUser.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using Microsoft.AspNetCore.Identity; -using VND.Fw.Domain; - -namespace VND.Fw.Infrastructure.EfCore.Identity -{ - public class ApplicationUser : IdentityUser, IEntity - { - public string LastName - { - get; - set; - } - - public string FirstName - { - get; - set; - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Migration/ISeedData.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Migration/ISeedData.cs deleted file mode 100644 index 14b0744d..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Migration/ISeedData.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; - -namespace VND.Fw.Infrastructure.EfCore.Migration -{ - public interface ISeedData - where TDbContext : DbContext - { - Task SeedAsync(TDbContext context); - } - - public interface IAuthConfigSeedData : ISeedData - where TDbContext : DbContext - { - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Migration/SeedDataBase.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Migration/SeedDataBase.cs deleted file mode 100644 index 9350011a..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Migration/SeedDataBase.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; - -namespace VND.Fw.Infrastructure.EfCore.Migration -{ - public abstract class SeedDataBase - : ISeedData, IAuthConfigSeedData - where TDbContext : DbContext - { - protected IConfiguration Configuration { get; } - - protected SeedDataBase(IConfiguration configuration) - { - Configuration = configuration; - } - - public abstract Task SeedAsync(TDbContext context); - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Repository/EfRepository.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Repository/EfRepository.cs deleted file mode 100644 index 5f7c1158..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Repository/EfRepository.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using VND.Fw.Domain; - -namespace VND.Fw.Infrastructure.EfCore.Repository -{ - public class EfQueryRepositoryFactory : IQueryRepositoryFactory - { - private readonly IServiceProvider _serviceProvider; - - public EfQueryRepositoryFactory(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - - public IQueryRepository QueryRepository() where TEntity : IEntity - { - return _serviceProvider.GetService(typeof(IEfQueryRepository)) as IEfQueryRepository; - } - } - - public class EfRepositoryAsync - : EfRepositoryAsync, IEfRepositoryAsync - where TEntity : class, IEntity - { - public EfRepositoryAsync(DbContext dbContext) : base(dbContext) - { - } - } - - public class EfQueryRepository - : EfQueryRepository, IEfQueryRepository - where TEntity : class, IEntity - { - public EfQueryRepository(DbContext dbContext) : base(dbContext) - { - } - } - - public class EfRepositoryAsync : IEfRepositoryAsync - where TDbContext : DbContext - where TEntity : class, IEntity - { - private readonly TDbContext _dbContext; - - public EfRepositoryAsync(TDbContext dbContext) - { - _dbContext = dbContext; - _dbContext.ChangeTracker.AutoDetectChangesEnabled = false; - } - - public async Task AddAsync(TEntity entity) - { - await _dbContext.Set().AddAsync(entity); - return entity; - } - - public async Task DeleteAsync(TEntity entity) - { - _dbContext.Entry(entity).State = EntityState.Deleted; - return await Task.FromResult(entity); - } - - public async Task UpdateAsync(TEntity entity) - { - _dbContext.Entry(entity).State = EntityState.Modified; - return await Task.FromResult(entity); - } - } - - public class EfQueryRepository : IEfQueryRepository - where TDbContext : DbContext - where TEntity : class, IEntity - { - private readonly TDbContext _dbContext; - - public EfQueryRepository(TDbContext dbContext) - { - _dbContext = dbContext; - _dbContext.ChangeTracker.AutoDetectChangesEnabled = false; - } - - public IQueryable Queryable() => _dbContext.Set(); - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Repository/EfUnitOfWork.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Repository/EfUnitOfWork.cs deleted file mode 100644 index e99305dd..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Repository/EfUnitOfWork.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Storage; -using VND.Fw.Domain; - -namespace VND.Fw.Infrastructure.EfCore.Repository -{ - public class EfUnitOfWork : IUnitOfWorkAsync - { - private readonly DbContext _context; - protected IDbContextTransaction Transaction; - protected IServiceProvider ServiceProvider; - - public EfUnitOfWork(DbContext context, IServiceProvider serviceProvider) - { - _context = context; - ServiceProvider = serviceProvider; - } - - public virtual IRepositoryAsync Repository() where TEntity : IEntity - { - return (IEfRepositoryAsync)ServiceProvider.GetService(typeof(IEfRepositoryAsync)); - } - - public int? CommandTimeout - { - get => _context.Database.GetCommandTimeout(); - set => _context.Database.SetCommandTimeout(value); - } - - public virtual int SaveChanges() => _context.SaveChanges(); - - public virtual Task SaveChangesAsync(CancellationToken cancellationToken) - { - return _context.SaveChangesAsync(cancellationToken); - } - - public virtual int ExecuteSqlCommand(string sql, params object[] parameters) - { - return _context.Database.ExecuteSqlCommand(sql, parameters); - } - - public virtual async Task ExecuteSqlCommandAsync(string sql, params object[] parameters) - { - return await _context.Database.ExecuteSqlCommandAsync(sql, parameters); - } - - public virtual async Task ExecuteSqlCommandAsync(string sql, CancellationToken cancellationToken, params object[] parameters) - { - return await _context.Database.ExecuteSqlCommandAsync(sql, cancellationToken, parameters); - } - - public void Dispose() - { - Transaction?.Dispose(); - _context?.Dispose(); - } - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/Repository/IEfRepository.cs b/src/framework/VND.Fw.Infrastructure.EfCore/Repository/IEfRepository.cs deleted file mode 100644 index 6fc7ab6e..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/Repository/IEfRepository.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using VND.Fw.Domain; - -namespace VND.Fw.Infrastructure.EfCore.Repository -{ - public interface IEfRepositoryAsync : IEfRepositoryAsync - where TEntity : IEntity - { - } - - public interface IEfQueryRepository : IEfQueryRepository - where TEntity : IEntity - { - } - - public interface IEfRepositoryAsync : IRepositoryAsync - where TDbContext : DbContext - where TEntity : IEntity - { - } - - public interface IEfQueryRepository : IQueryRepository - where TDbContext : DbContext - where TEntity : IEntity - { - } -} diff --git a/src/framework/VND.Fw.Infrastructure.EfCore/VND.Fw.Infrastructure.EfCore.csproj b/src/framework/VND.Fw.Infrastructure.EfCore/VND.Fw.Infrastructure.EfCore.csproj deleted file mode 100644 index ebf1d591..00000000 --- a/src/framework/VND.Fw.Infrastructure.EfCore/VND.Fw.Infrastructure.EfCore.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - netstandard2.0 - - - - - - - - - - - - - - - - diff --git a/src/framework/VND.Fw.Utils/Extensions/AssemblyExtensions.cs b/src/framework/VND.Fw.Utils/Extensions/AssemblyExtensions.cs deleted file mode 100644 index 01ca7152..00000000 --- a/src/framework/VND.Fw.Utils/Extensions/AssemblyExtensions.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Linq; -using System.Reflection; -using Microsoft.Extensions.DependencyModel; - -namespace VND.Fw.Utils.Extensions -{ - /// - /// https://stackoverflow.com/questions/37895278/how-to-load-assemblies-located-in-a-folder-in-net-core-console-app - /// - public static class AssemblyExtensions - { - public static Assembly FindAssemblyBy(this string assemblyName) - { - var deps = DependencyContext.Default; - var res = deps.CompileLibraries.Where(d => d.Name.Contains(assemblyName)).ToList(); - var assembly = Assembly.Load(new AssemblyName(res.First().Name)); - return assembly; - } - } -} diff --git a/src/framework/VND.Fw.Utils/Extensions/ByteArrayExtensions.cs b/src/framework/VND.Fw.Utils/Extensions/ByteArrayExtensions.cs deleted file mode 100644 index 1bbde74f..00000000 --- a/src/framework/VND.Fw.Utils/Extensions/ByteArrayExtensions.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Text; - -namespace VND.Fw.Utils.Extensions -{ - public static class ByteArrayExtensions - { - public static string ToBase64String(this byte[] input) - { - return Convert.ToBase64String(input); - } - - public static string ToUrlSuitable(this byte[] input) - { - return input.ToBase64String().Replace("+", "-").Replace("/", "_").Replace("=", "%3d"); - } - - public static string ToHexString(this byte[] bytes) - { - var hex = new StringBuilder(bytes.Length * 2); - foreach (var b in bytes) hex.AppendFormat("{0:x2}", b); - - return hex.ToString(); - } - } -} diff --git a/src/framework/VND.Fw.Utils/Extensions/DynamicExtensions.cs b/src/framework/VND.Fw.Utils/Extensions/DynamicExtensions.cs deleted file mode 100644 index 26f38288..00000000 --- a/src/framework/VND.Fw.Utils/Extensions/DynamicExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Collections.Generic; -using System.ComponentModel; -using System.Dynamic; - -namespace VND.Fw.Utils.Extensions -{ - public static class DynamicExtensions - { - public static dynamic ToDynamic(this object value) - { - IDictionary expando = new ExpandoObject(); - - foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType())) - expando.Add(property.Name, property.GetValue(value)); - - return expando as ExpandoObject; - } - } -} diff --git a/src/framework/VND.Fw.Utils/Extensions/HashExtensions.cs b/src/framework/VND.Fw.Utils/Extensions/HashExtensions.cs deleted file mode 100644 index fea98d39..00000000 --- a/src/framework/VND.Fw.Utils/Extensions/HashExtensions.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System.Collections.Generic; -using System.Security.Cryptography; -using System.Text; - -namespace VND.Fw.Utils.Extensions -{ - public static class HashExtensions - { - private static readonly byte[] _empty = new byte[0]; - - public static int CombineHashCodes(this IEnumerable objs) - { - unchecked - { - var hash = 17; - foreach (var obj in objs) hash = hash * 23 + (obj?.GetHashCode() ?? 0); - - return hash; - } - } - - public static byte[] Hash(this string plainText, HashAlgorithm hashAlgorithm, string encoding = "gb2312") - { - // get bytes from the plaintext - var bytes = Encoding.GetEncoding(encoding).GetBytes(plainText); - - // encrypt - using (var algorithm = hashAlgorithm ?? System.Security.Cryptography.MD5.Create()) - { - return algorithm.ComputeHash(bytes); - } - } - - public static byte[] MD5(this string input, string encoding = "gb2312") - { - if (string.IsNullOrEmpty(input)) return _empty; - - return Hash(input, System.Security.Cryptography.MD5.Create(), encoding); - } - - public static byte[] Sha512(this string input, string encoding = "gb2312") - { - if (string.IsNullOrEmpty(input)) return _empty; - - return Hash(input, SHA512.Create(), encoding); - } - - public static byte[] Sha256(this string input, string encoding = "gb2312") - { - if (string.IsNullOrEmpty(input)) return _empty; - - return Hash(input, SHA256.Create()); - } - - public static byte[] Sha1(this string input, string encoding = "gb2312") - { - if (string.IsNullOrEmpty(input)) return _empty; - - return Hash(input, SHA1.Create()); - } - - public static byte[] Sha256(this byte[] input) - { - if (input == null) return null; - - using (var sha = SHA256.Create()) - { - return sha.ComputeHash(input); - } - } - } -} diff --git a/src/framework/VND.Fw.Utils/Extensions/StringExtensions.cs b/src/framework/VND.Fw.Utils/Extensions/StringExtensions.cs deleted file mode 100644 index db39d551..00000000 --- a/src/framework/VND.Fw.Utils/Extensions/StringExtensions.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Text; - -namespace VND.Fw.Utils.Extensions -{ - public static class StringExtensions - { - public static string TrimStart(this string source, string trim, - StringComparison stringComparison = StringComparison.Ordinal) - { - if (source == null) return null; - - var s = source; - while (s.StartsWith(trim, stringComparison)) s = s.Substring(trim.Length); - - return s; - } - - public static string TrimAfter(this string source, string trim) - { - var index = source.IndexOf(trim, StringComparison.Ordinal); - if (index > 0) source = source.Substring(0, index); - - return source; - } - - public static string MySQLEscape(this string value) - { - if (!IsQuoting(value)) return value; - - var sb = new StringBuilder(); - foreach (var c in value) - { - var charClass = charClassArray[c]; - if (charClass != CharKinds.None) sb.Append("\\"); - sb.Append(c); - } - - return sb.ToString(); - } - - #region MySQLEscape Helpers - - private enum CharKinds : byte - { - None, - Quote, - Backslash - } - - private static readonly string backslashChars = "\u005c\u00a5\u0160\u20a9\u2216\ufe68\uff3c"; - - private static readonly string quoteChars = - "\u0022\u0027\u0060\u00b4\u02b9\u02ba\u02bb\u02bc\u02c8\u02ca\u02cb\u02d9\u0300\u0301\u2018\u2019\u201a\u2032\u2035\u275b\u275c\uff07"; - - private static readonly CharKinds[] charClassArray = MakeCharClassArray(); - - private static CharKinds[] MakeCharClassArray() - { - var a = new CharKinds[65536]; - foreach (var c in backslashChars) a[c] = CharKinds.Backslash; - foreach (var c in quoteChars) a[c] = CharKinds.Quote; - - return a; - } - - private static bool IsQuoting(string str) - { - foreach (var c in str) - if (charClassArray[c] != CharKinds.None) - return true; - - return false; - } - - #endregion - } -} diff --git a/src/framework/VND.Fw.Utils/Extensions/TypeConversionExtensions.cs b/src/framework/VND.Fw.Utils/Extensions/TypeConversionExtensions.cs deleted file mode 100644 index 9883af03..00000000 --- a/src/framework/VND.Fw.Utils/Extensions/TypeConversionExtensions.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.ComponentModel; - -namespace VND.Fw.Utils.Extensions -{ - public static class TypeConversionExtensions - { - public static T ConvertTo(this string input) - { - try - { - var converter = TypeDescriptor.GetConverter(typeof(T)); - return (T)converter.ConvertFromString(input); - } - catch (NotSupportedException) - { - return default(T); - } - } - } -} diff --git a/src/framework/VND.Fw.Utils/Extensions/TypeLookupExtensions.cs b/src/framework/VND.Fw.Utils/Extensions/TypeLookupExtensions.cs deleted file mode 100644 index aae4abbf..00000000 --- a/src/framework/VND.Fw.Utils/Extensions/TypeLookupExtensions.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text.RegularExpressions; -using Microsoft.Extensions.DependencyModel; - -namespace VND.Fw.Utils.Extensions -{ - public static class TypeLookupExtensions - { - public static IEnumerable ResolveModularGenericTypes(this string patterns, Type genericInterfaceType, - Type genericType) - { - var assemblies = patterns - .LoadAssemblyWithPattern() - .SelectMany(m => m.DefinedTypes); - - var interfaceWithType = genericInterfaceType.MakeGenericType(genericType); - - return assemblies.Where(x => x.GetInterfaces().Contains(interfaceWithType)); - } - - public static IEnumerable ResolveModularTypes(this string patterns, Type interfaceType) - { - var assemblies = patterns - .LoadAssemblyWithPattern() - .SelectMany(m => m.DefinedTypes); - - return assemblies.Where(x => - interfaceType.IsAssignableFrom(x) && - !x.GetTypeInfo().IsAbstract); - } - - public static IEnumerable LoadAssemblyWithPattern(this string searchPattern) - { - var assemblies = new HashSet(); - var searchRegex = new Regex(searchPattern, RegexOptions.IgnoreCase); - var moduleAssemblyFiles = DependencyContext - .Default - .RuntimeLibraries - .Where(x => searchRegex.IsMatch(x.Name)).ToList(); - - foreach (var assemblyFiles in moduleAssemblyFiles) - assemblies.Add(Assembly.Load(new AssemblyName(assemblyFiles.Name))); - - return assemblies.ToList(); - } - } -} diff --git a/src/framework/VND.Fw.Utils/Guard.cs b/src/framework/VND.Fw.Utils/Guard.cs deleted file mode 100644 index 9dd5571e..00000000 --- a/src/framework/VND.Fw.Utils/Guard.cs +++ /dev/null @@ -1,214 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace VND.Fw.Utils -{ - /// - /// Helper class that will throw exceptions when conditions are not satisfied. - /// Reference at https://github.com/saaskit/saaskit/blob/master/src/SaasKit.Multitenancy/Ensure.cs - /// - public static class Guard - { - /// - /// Ensures that the given expression is true - /// - /// Exception thrown if false condition - /// Condition to test/ensure - /// Message for the exception - /// Thrown when is false - public static void That(bool condition, string message = "") - { - That(condition, message); - } - - /// - /// Ensures that the given expression is true - /// - /// Type of exception to throw - /// Condition to test/ensure - /// Message for the exception - /// Thrown when is false - /// must have a constructor that takes a single string - public static void That(bool condition, string message = "") where TException : Exception - { - if (!condition) - { - throw (TException)Activator.CreateInstance(typeof(TException), message); - } - } - - /// - /// Ensures given condition is false - /// - /// Type of exception to throw - /// Condition to test - /// Message for the exception - /// Thrown when is true - /// must have a constructor that takes a single string - public static void Not(bool condition, string message = "") where TException : Exception - { - That(!condition, message); - } - - /// - /// Ensures given condition is false - /// - /// Condition to test - /// Message for the exception - /// Thrown when is true - public static void Not(bool condition, string message = "") - { - Not(condition, message); - } - - /// - /// Ensures given object is not null - /// - /// Value of the object to test for null reference - /// Message for the Null Reference Exception - /// Thrown when is null - public static void NotNull(object value, string message = "") - { - That(value != null, message); - } - - /// - /// Ensures given string is not null or empty - /// - /// String value to compare - /// Message of the exception if value is null or empty - /// string value is null or empty - public static void NotNullOrEmpty(string value, string message = "String cannot be null or empty") - { - That(!string.IsNullOrEmpty(value), message); - } - - /// - /// Ensures given objects are equal - /// - /// Type of objects to compare for equality - /// First Value to Compare - /// Second Value to Compare - /// Message of the exception when values equal - /// - /// Exception is thrown when not equal to - /// - /// - /// Null values will cause an exception to be thrown - public static void Equal(T left, T right, string message = "Values must be equal") - { - That(left != null && right != null && left.Equals(right), message); - } - - /// - /// Ensures given objects are not equal - /// - /// Type of objects to compare for equality - /// First Value to Compare - /// Second Value to Compare - /// Message of the exception when values equal - /// Thrown when equal to - /// Null values will cause an exception to be thrown - public static void NotEqual(T left, T right, string message = "Values must not be equal") - { - That(left != null && right != null && !left.Equals(right), message); - } - - /// - /// Ensures given collection contains a value that satisfied a predicate - /// - /// Collection type - /// Collection to test - /// Predicate where one value in the collection must satisfy - /// Message of the exception if value not found - /// - /// Thrown if collection is null, empty or doesn't contain a value that satisfies - /// - public static void Contains(IEnumerable collection, Func predicate, string message = "") - { - That(collection != null && collection.Any(predicate), message); - } - - /// - /// Ensures ALL items in the given collection satisfy a predicate - /// - /// Collection type - /// Collection to test - /// Predicate that ALL values in the collection must satisfy - /// Message of the exception if not all values are valid - /// - /// Thrown if collection is null, empty or not all values satisfies - /// - public static void Items(IEnumerable collection, Func predicate, string message = "") - { - That(collection != null && !collection.Any(x => !predicate(x)), message); - } - - /// - /// Argument-specific ensure methods - /// - public static class Argument - { - /// - /// Ensures given condition is true - /// - /// Condition to test - /// Message of the exception if condition fails - /// - /// Thrown if is false - /// - public static void Is(bool condition, string message = "") - { - That(condition, message); - } - - /// - /// Ensures given condition is false - /// - /// Condition to test - /// Message of the exception if condition is true - /// - /// Thrown if is true - /// - public static void IsNot(bool condition, string message = "") - { - Is(!condition, message); - } - - /// - /// Ensures given value is not null - /// - /// Value to test for null - /// Name of the parameter in the method - /// - /// Thrown if is null - /// - public static void NotNull(object value, string paramName = "") - { - That(value != null, paramName); - } - - /// - /// Ensures the given string value is not null or empty - /// - /// Value to test for null or empty - /// Name of the parameter in the method - /// - /// Thrown if is null or empty string - /// - public static void NotNullOrEmpty(string value, string paramName = "") - { - if (value == null) - { - throw new ArgumentNullException(paramName, "String value cannot be null"); - } - - if (string.IsNullOrEmpty(value)) - { - throw new ArgumentException("String value cannot be empty", paramName); - } - } - } - } -} diff --git a/src/framework/VND.Fw.Utils/Helpers/CryptoRandomHelper.cs b/src/framework/VND.Fw.Utils/Helpers/CryptoRandomHelper.cs deleted file mode 100644 index 7a0bffbe..00000000 --- a/src/framework/VND.Fw.Utils/Helpers/CryptoRandomHelper.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Security.Cryptography; -using VND.Fw.Utils.Extensions; - -namespace VND.Fw.Utils.Helpers -{ - public class CryptoRandomHelper - { - private static RandomNumberGenerator _rng = RandomNumberGenerator.Create(); - - public static byte[] CreateRandomBytes(int length) - { - byte[] bytes = new byte[length]; - _rng.GetBytes(bytes); - - return bytes; - } - - public static string CreateRandomKey(int length) - { - byte[] bytes = new byte[length]; - _rng.GetBytes(bytes); - - return Convert.ToBase64String(CreateRandomBytes(length)); - } - - public static string CreateUniqueKey(int length = 8) => CreateRandomBytes(length).ToHexString(); - - public static string CreateSeriesNumber(string prefix = "MSK") => $"{prefix}{DateTime.Now.ToString("yyyyMMddHHmmss")}{CreateUniqueKey()}"; - } -} diff --git a/src/framework/VND.Fw.Utils/Helpers/DateTimeHelper.cs b/src/framework/VND.Fw.Utils/Helpers/DateTimeHelper.cs deleted file mode 100644 index 7d680df2..00000000 --- a/src/framework/VND.Fw.Utils/Helpers/DateTimeHelper.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace VND.Fw.Utils.Helpers -{ - public static class DateTimeHelper - { - public static DateTime GenerateDateTime() - { - return DateTimeOffset.Now.UtcDateTime; - } - } -} diff --git a/src/framework/VND.Fw.Utils/Helpers/EnumHelper.cs b/src/framework/VND.Fw.Utils/Helpers/EnumHelper.cs deleted file mode 100644 index 7cc84361..00000000 --- a/src/framework/VND.Fw.Utils/Helpers/EnumHelper.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace VND.Fw.Utils.Helpers -{ - public class EnumHelper - { - public static IEnumerable> GetEnumKeyValue() - where TKey : class - { - (IEnumerable, IEnumerable) metas = GetMetadata(); - IEnumerable> results = metas.Item1.Zip(metas.Item2, (key, value) => - new KeyValueObject - ( - key: key, - value: value - ) - ); - return results; - } - - public static (IEnumerable, IEnumerable) GetMetadata() - { - TKey[] keyArray = (TKey[])Enum.GetValues(typeof(TEnum)); - string[] nameArray = Enum.GetNames(typeof(TEnum)); - - IList keys = new List(); - foreach (TKey item in keyArray) - { - keys.Add(item); - } - - IList names = new List(); - foreach (string item in nameArray) - { - names.Add(item); - } - - return (keys, names); - } - } -} diff --git a/src/framework/VND.Fw.Utils/Helpers/IdHelper.cs b/src/framework/VND.Fw.Utils/Helpers/IdHelper.cs deleted file mode 100644 index 2c686df8..00000000 --- a/src/framework/VND.Fw.Utils/Helpers/IdHelper.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace VND.Fw.Utils.Helpers -{ - public static class IdHelper - { - public static Guid GenerateId(string guid = "") - { - return string.IsNullOrEmpty(guid) ? Guid.NewGuid() : new Guid(guid); - } - } -} diff --git a/src/framework/VND.Fw.Utils/Helpers/TotpHelper.cs b/src/framework/VND.Fw.Utils/Helpers/TotpHelper.cs deleted file mode 100644 index 892edd24..00000000 --- a/src/framework/VND.Fw.Utils/Helpers/TotpHelper.cs +++ /dev/null @@ -1,104 +0,0 @@ -using System; -using System.Diagnostics; -using System.Net; -using System.Security.Cryptography; -using System.Text; - -namespace VND.Fw.Utils.Helpers -{ - /// - /// https://tools.ietf.org/html/rfc6238 - /// - public static class TotpHelper - { - private static readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - private static TimeSpan _timestep = TimeSpan.FromMinutes(3); - private static readonly Encoding _encoding = new UTF8Encoding(false, true); - - private static int ComputeTotp(HashAlgorithm hashAlgorithm, ulong timestepNumber, string modifier) - { - // # of 0's = length of pin - const int Mod = 1000000; - - // See https://tools.ietf.org/html/rfc4226 - // We can add an optional modifier - byte[] timestepAsBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((long)timestepNumber)); - byte[] hash = hashAlgorithm.ComputeHash(ApplyModifier(timestepAsBytes, modifier)); - - // Generate DT string - int offset = hash[hash.Length - 1] & 0xf; - Debug.Assert(offset + 4 < hash.Length); - int binaryCode = (hash[offset] & 0x7f) << 24 - | (hash[offset + 1] & 0xff) << 16 - | (hash[offset + 2] & 0xff) << 8 - | (hash[offset + 3] & 0xff); - - return binaryCode % Mod; - } - - private static byte[] ApplyModifier(byte[] input, string modifier) - { - if (string.IsNullOrEmpty(modifier)) - { - return input; - } - - byte[] modifierBytes = _encoding.GetBytes(modifier); - byte[] combined = new byte[checked(input.Length + modifierBytes.Length)]; - Buffer.BlockCopy(input, 0, combined, 0, input.Length); - Buffer.BlockCopy(modifierBytes, 0, combined, input.Length, modifierBytes.Length); - return combined; - } - - // More info: https://tools.ietf.org/html/rfc6238#section-4 - private static ulong GetCurrentTimeStepNumber() - { - TimeSpan delta = DateTime.UtcNow - _unixEpoch; - return (ulong)(delta.Ticks / _timestep.Ticks); - } - - public static int GenerateCode(byte[] securityToken, string modifier = null) - { - if (securityToken == null) - { - throw new ArgumentNullException(nameof(securityToken)); - } - - // Allow a variance of no greater than 90 seconds in either direction - ulong currentTimeStep = GetCurrentTimeStepNumber(); - using (HMACSHA1 hashAlgorithm = new HMACSHA1(securityToken)) - { - return ComputeTotp(hashAlgorithm, currentTimeStep, modifier); - } - } - - public static bool ValidateCode(byte[] securityToken, int code, string modifier = null) - { - if (securityToken == null) - { - throw new ArgumentNullException(nameof(securityToken)); - } - - // Allow a variance of no greater than 90 seconds in either direction - ulong currentTimeStep = GetCurrentTimeStepNumber(); - using (HMACSHA1 hashAlgorithm = new HMACSHA1(securityToken)) - { - for (int i = -2; i <= 2; i++) - { - int computedTotp = ComputeTotp(hashAlgorithm, (ulong)((long)currentTimeStep + i), modifier); - if (computedTotp == code) - { - return true; - } - } - } - - // No match - return false; - } - - public static int GenerateCode(string securityToken, string modifier = null) => GenerateCode(Encoding.Unicode.GetBytes(securityToken), modifier); - - public static bool ValidateCode(string securityToken, int code, string modifier = null) => ValidateCode(Encoding.Unicode.GetBytes(securityToken), code, modifier); - } -} diff --git a/src/framework/VND.Fw.Utils/README.md b/src/framework/VND.Fw.Utils/README.md deleted file mode 100644 index f60a0b91..00000000 --- a/src/framework/VND.Fw.Utils/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# VND.Fw.Utils module - -This utils library contains ultility functions and helpers (e.g. string, bytes, hash, modular) that need for the web development. - -# List of utility helper and function - -- Extension functions - - StringExtensions - - AssemblyExtensions - - ByteArrayExtensions - - HashExtensions - - MyModularLookupExtensions - -- Helpers - - CryptoRandomHelper - - DateTimeHelper - - EnumHelper - - IdHelper - - TotpHelper - -- Guard - diff --git a/src/framework/VND.Fw.Utils/VND.Fw.Utils.csproj b/src/framework/VND.Fw.Utils/VND.Fw.Utils.csproj deleted file mode 100644 index d20ae8d1..00000000 --- a/src/framework/VND.Fw.Utils/VND.Fw.Utils.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - This utils library contains ultility functions and helpers (e.g. string, bytes, hash, modular). - The need utilities for the web development using in Modular Starter Kit. - This utils library contains ultility functions and helpers (e.g. string, bytes, hash, modular) that need for the web development. - 0.0.1 - 0.0.1 - 0.0.1 - 0.0.1 - Thang Chung - netstandard2.0 - Library - VND.Fw.Utils - cloud-native utils web-development - https://github.com/vietnam-devs/coolstore-microservices - https://github.com/vietnam-devs/coolstore-microservices/blob/master/LICENSE - true - git - https://github.com/vietnam-devs/coolstore-microservices.git - en-US - VND.Fw.Utils - Copyright (c) Thang Chung - 2018 - - - - - - - diff --git a/src/services/cart/Dockerfile b/src/services/cart/Dockerfile index 7ef5b5e7..ed464401 100644 --- a/src/services/cart/Dockerfile +++ b/src/services/cart/Dockerfile @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.1.2-aspnetcore-runtime AS base +FROM microsoft/dotnet:2.1.2-aspnetcore-runtime-alpine AS base WORKDIR /app ARG service_version @@ -10,7 +10,7 @@ ENV API_VERSION ${api_version:-1.0} ENV ASPNETCORE_URLS http://+:5003 EXPOSE 5003 -FROM microsoft/dotnet:2.1.302-sdk AS build +FROM microsoft/dotnet:2.1.302-sdk-alpine AS build WORKDIR /src COPY . . diff --git a/src/services/idp/Dockerfile b/src/services/idp/Dockerfile index eefa7bc1..4b1d53e4 100644 --- a/src/services/idp/Dockerfile +++ b/src/services/idp/Dockerfile @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.1.2-aspnetcore-runtime AS base +FROM microsoft/dotnet:2.1.2-aspnetcore-runtime-alpine AS base WORKDIR /app ARG service_version @@ -10,7 +10,7 @@ ENV API_VERSION ${api_version:-1.0} ENV ASPNETCORE_URLS http://+:5001 EXPOSE 5001 -FROM microsoft/dotnet:2.1.302-sdk AS build +FROM microsoft/dotnet:2.1.302-sdk-alpine AS build WORKDIR /src COPY . . diff --git a/src/services/inventory/Dockerfile b/src/services/inventory/Dockerfile index b0241925..5deaa409 100644 --- a/src/services/inventory/Dockerfile +++ b/src/services/inventory/Dockerfile @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.1.2-aspnetcore-runtime AS base +FROM microsoft/dotnet:2.1.2-aspnetcore-runtime-alpine AS base WORKDIR /app ARG service_version @@ -10,7 +10,7 @@ ENV API_VERSION ${api_version:-1.0} ENV ASPNETCORE_URLS http://+:5004 EXPOSE 5004 -FROM microsoft/dotnet:2.1.302-sdk AS build +FROM microsoft/dotnet:2.1.302-sdk-alpine AS build WORKDIR /src COPY . . diff --git a/src/services/review/Dockerfile b/src/services/review/Dockerfile index df855520..29a050cb 100644 --- a/src/services/review/Dockerfile +++ b/src/services/review/Dockerfile @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.1.2-aspnetcore-runtime AS base +FROM microsoft/dotnet:2.1.2-aspnetcore-runtime-alpine AS base WORKDIR /app ARG service_version @@ -10,7 +10,7 @@ ENV API_VERSION ${api_version:-1.0} ENV ASPNETCORE_URLS http://+:5006 EXPOSE 5006 -FROM microsoft/dotnet:2.1.302-sdk AS build +FROM microsoft/dotnet:2.1.302-sdk-alpine AS build WORKDIR /src COPY . .