diff --git a/src/Mixcore.sln b/src/Mixcore.sln index 80b39793d..85a2dff0a 100644 --- a/src/Mixcore.sln +++ b/src/Mixcore.sln @@ -109,9 +109,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mix.auth", "platform\mix.au EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mixcore", "applications\mixcore\mixcore.csproj", "{BEFA0F34-2594-4E77-88A9-4DF2B535343A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mixcore.host.aspire.AppHost", "applications\mixcore.host.aspire\mixcore.host.aspire.AppHost\mixcore.host.aspire.AppHost.csproj", "{803BBEFE-A5AF-4C43-87FC-DA9132F18498}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mixcore.host.aspire.AppHost", "applications\mixcore.host.aspire.AppHost\mixcore.host.aspire.AppHost.csproj", "{803BBEFE-A5AF-4C43-87FC-DA9132F18498}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mixcore.host.aspire.ServiceDefaults", "applications\mixcore.host.aspire\mixcore.host.aspire.ServiceDefaults\mixcore.host.aspire.ServiceDefaults.csproj", "{3BADD396-E830-468B-B2D8-A52FD5E6C6BD}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mixcore.host.aspire.ServiceDefaults", "applications\mixcore.host.aspire.ServiceDefaults\mixcore.host.aspire.ServiceDefaults.csproj", "{3BADD396-E830-468B-B2D8-A52FD5E6C6BD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mixcore.gateway", "applications\mixcore.gateway\mixcore.gateway.csproj", "{5FA252B6-6FDA-451E-BE5E-F6D82EDE9AB1}" EndProject @@ -121,9 +121,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "mix-message-queue", "mix-me EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "mix-auth-service", "mix-auth-service", "{EC933357-1D95-4CDD-B290-7A5984FC1AA2}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mix.mq.server", "services\mix-message-queue\mix.mq.server\mix.mq.server.csproj", "{7C5101F3-E3E6-42DB-8585-D08C2BE5E30C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mix.mq.server", "services\core\mix-message-queue\mix.mq.server\mix.mq.server.csproj", "{7C5101F3-E3E6-42DB-8585-D08C2BE5E30C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mix.auth.api", "services\mix-auth-service\mix.auth.api\mix.auth.api.csproj", "{9C04921A-38D5-4EC9-8FF5-0E0D74681049}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mix.auth.api", "services\core\mix-auth-service\mix.auth.api\mix.auth.api.csproj", "{9C04921A-38D5-4EC9-8FF5-0E0D74681049}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -348,8 +348,8 @@ Global {3BADD396-E830-468B-B2D8-A52FD5E6C6BD} = {4E880812-C336-4EB2-9FED-2E437957F50A} {5FA252B6-6FDA-451E-BE5E-F6D82EDE9AB1} = {4E880812-C336-4EB2-9FED-2E437957F50A} {F5D4C70F-DD2E-4EC9-A191-56A717B1B5EE} = {B4C40E02-E06A-4359-BDC5-349E103366AD} - {C93898B7-2001-4C29-9BBE-33A2E61C350A} = {C0A05428-767E-46C5-A31F-0D220E41F7C5} - {EC933357-1D95-4CDD-B290-7A5984FC1AA2} = {C0A05428-767E-46C5-A31F-0D220E41F7C5} + {C93898B7-2001-4C29-9BBE-33A2E61C350A} = {7C9FFA1B-D992-4E3F-B2B1-74D86E81512D} + {EC933357-1D95-4CDD-B290-7A5984FC1AA2} = {7C9FFA1B-D992-4E3F-B2B1-74D86E81512D} {7C5101F3-E3E6-42DB-8585-D08C2BE5E30C} = {C93898B7-2001-4C29-9BBE-33A2E61C350A} {9C04921A-38D5-4EC9-8FF5-0E0D74681049} = {EC933357-1D95-4CDD-B290-7A5984FC1AA2} EndGlobalSection diff --git a/src/applications/mixcore.gateway/Dockerfile b/src/applications/mixcore.gateway/Dockerfile index 5a52d3bc8..d097c8ccb 100644 --- a/src/applications/mixcore.gateway/Dockerfile +++ b/src/applications/mixcore.gateway/Dockerfile @@ -9,9 +9,29 @@ EXPOSE 8081 FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build ARG BUILD_CONFIGURATION=Release WORKDIR /src +COPY ["platform/core/mix-heart/nuget.config", "platform/core/mix-heart/"] COPY ["applications/mixcore.gateway/mixcore.gateway.csproj", "applications/mixcore.gateway/"] -COPY ["applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/"] -RUN dotnet restore "./applications/mixcore.gateway/./mixcore.gateway.csproj" +COPY ["platform/mix.library/mix.library.csproj", "platform/mix.library/"] +COPY ["platform/core/mix.mixdb.event/mix.mixdb.event.csproj", "platform/core/mix.mixdb.event/"] +COPY ["platform/mix.mixdb/mix.mixdb.csproj", "platform/mix.mixdb/"] +COPY ["platform/mix.database/mix.database.csproj", "platform/mix.database/"] +COPY ["platform/mix.shared/mix.shared.csproj", "platform/mix.shared/"] +COPY ["platform/core/mix-heart/src/mix.heart/mix.heart.csproj", "platform/core/mix-heart/src/mix.heart/"] +COPY ["platform/mix.constant/mix.constant.csproj", "platform/mix.constant/"] +COPY ["platform/mix.service/mix.service.csproj", "platform/mix.service/"] +COPY ["platform/mix.identity/mix.identity.csproj", "platform/mix.identity/"] +COPY ["platform/mix.auth/mix.auth.csproj", "platform/mix.auth/"] +COPY ["platform/mix.quartz/mix.quartz.csproj", "platform/mix.quartz/"] +COPY ["platform/mix.queue/mix.queue.csproj", "platform/mix.queue/"] +COPY ["services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj", "services/core/mix-message-queue/mix.mq/"] +COPY ["applications/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "applications/mixcore.host.aspire.ServiceDefaults/"] +COPY ["services/core/mix-message-queue/mix.mq.lib/mix.mq.lib.csproj", "services/core/mix-message-queue/mix.mq.lib/"] +COPY ["platform/mix.signalr/mix.signalr.csproj", "platform/mix.signalr/"] +COPY ["platform/mix.repodb/mix.repodb.csproj", "platform/mix.repodb/"] +COPY ["platform/mix.communicator/mix.communicator.csproj", "platform/mix.communicator/"] +COPY ["platform/mix.signalr.hub/mix.signalr.hub.csproj", "platform/mix.signalr.hub/"] +COPY ["platform/mix.log/mix.log.lib.csproj", "platform/mix.log/"] +RUN dotnet restore "./applications/mixcore.gateway/mixcore.gateway.csproj" COPY . . WORKDIR "/src/applications/mixcore.gateway" RUN dotnet build "./mixcore.gateway.csproj" -c $BUILD_CONFIGURATION -o /app/build diff --git a/src/applications/mixcore.gateway/Dockerfile_linux b/src/applications/mixcore.gateway/Dockerfile_linux new file mode 100644 index 000000000..9b3e07727 --- /dev/null +++ b/src/applications/mixcore.gateway/Dockerfile_linux @@ -0,0 +1,41 @@ +#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base +USER app +EXPOSE 8080 +EXPOSE 8081 + +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +ARG BUILD_CONFIGURATION=Release +COPY ["src/applications/mixcore.gateway/mixcore.gateway.csproj", "src/applications/mixcore.gateway/"] +COPY ["src/platform/mix.library/mix.library.csproj", "src/platform/mix.library/"] +COPY ["src/platform/core/mix.mixdb.event/mix.mixdb.event.csproj", "src/platform/core/mix.mixdb.event/"] +COPY ["src/platform/mix.mixdb/mix.mixdb.csproj", "src/platform/mix.mixdb/"] +COPY ["src/platform/mix.database/mix.database.csproj", "src/platform/mix.database/"] +COPY ["src/platform/mix.shared/mix.shared.csproj", "src/platform/mix.shared/"] +COPY ["src/platform/core/mix-heart/src/mix.heart/mix.heart.csproj", "src/platform/core/mix-heart/src/mix.heart/"] +COPY ["src/platform/mix.constant/mix.constant.csproj", "src/platform/mix.constant/"] +COPY ["src/platform/mix.service/mix.service.csproj", "src/platform/mix.service/"] +COPY ["src/platform/mix.identity/mix.identity.csproj", "src/platform/mix.identity/"] +COPY ["src/platform/mix.auth/mix.auth.csproj", "src/platform/mix.auth/"] +COPY ["src/platform/mix.quartz/mix.quartz.csproj", "src/platform/mix.quartz/"] +COPY ["src/platform/mix.queue/mix.queue.csproj", "src/platform/mix.queue/"] +COPY ["src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj", "src/services/core/mix-message-queue/mix.mq/"] +COPY ["src/applications/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "applications/mixcore.host.aspire.ServiceDefaults/"] +COPY ["src/services/core/mix-message-queue/mix.mq.lib/mix.mq.lib.csproj", "src/services/core/mix-message-queue/mix.mq.lib/"] +COPY ["src/platform/mix.signalr/mix.signalr.csproj", "src/platform/mix.signalr/"] +COPY ["src/platform/mix.repodb/mix.repodb.csproj", "src/platform/mix.repodb/"] +COPY ["src/platform/mix.communicator/mix.communicator.csproj", "src/platform/mix.communicator/"] +COPY ["src/platform/mix.signalr.hub/mix.signalr.hub.csproj", "src/platform/mix.signalr.hub/"] +COPY ["src/platform/mix.log/mix.log.lib.csproj", "src/platform/mix.log/"] +RUN dotnet restore "src/applications/mixcore.gateway/mixcore.gateway.csproj" +COPY . . +RUN dotnet build "/src/applications/mixcore.gateway/mixcore.gateway.csproj" -c $BUILD_CONFIGURATION -o /app/build + +FROM build AS publish +ARG BUILD_CONFIGURATION=Release +RUN dotnet publish "/src/applications/mixcore.gateway/mixcore.gateway.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +FROM base AS final +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "mixcore.gateway.dll"] \ No newline at end of file diff --git a/src/applications/mixcore.gateway/Program.cs b/src/applications/mixcore.gateway/Program.cs index 3416ac75d..f0bf1f748 100644 --- a/src/applications/mixcore.gateway/Program.cs +++ b/src/applications/mixcore.gateway/Program.cs @@ -4,12 +4,11 @@ using Mix.Database.Entities.Cms; using Mix.Heart.Services; using Mix.Lib.Helpers; +using Mix.Lib.Services; using Mix.Shared.Services; using Ocelot.DependencyInjection; using Ocelot.Middleware; using System.Reflection; -using System.Text.Encodings.Web; -using System.Text.Unicode; bool isInit = true; @@ -36,6 +35,7 @@ builder.Services.AddControllers(); builder.Services.AddMixServices(Assembly.GetExecutingAssembly(), builder.Configuration); builder.Services.AddMixAuthorize(builder.Configuration); +builder.Services.AddScoped(); builder.Services.TryAddSingleton(); builder.Services.AddOcelot(builder.Configuration); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle diff --git a/src/applications/mixcore/appsettings.Production.json b/src/applications/mixcore.gateway/appsettings.Production.json similarity index 100% rename from src/applications/mixcore/appsettings.Production.json rename to src/applications/mixcore.gateway/appsettings.Production.json diff --git a/src/applications/mixcore.gateway/mixcore.gateway.csproj b/src/applications/mixcore.gateway/mixcore.gateway.csproj index 46219679d..e45aa7182 100644 --- a/src/applications/mixcore.gateway/mixcore.gateway.csproj +++ b/src/applications/mixcore.gateway/mixcore.gateway.csproj @@ -2,19 +2,21 @@ net8.0 + false + true false enable enable true - Mixcore.Gateway + mixcore.gateway bbdd7c53-6dfa-4f6f-ab46-5ecda7005ed0 Linux ..\.. - - + + @@ -22,7 +24,7 @@ - + diff --git a/src/applications/mixcore.gateway/ocelot.json b/src/applications/mixcore.gateway/ocelot.json deleted file mode 100644 index 31aa9590e..000000000 --- a/src/applications/mixcore.gateway/ocelot.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "Routes": [ - { - "Priority": 0, - "DownstreamPathTemplate": "/{everything}", - "DownstreamScheme": "https", - "DownstreamHostAndPorts": [ - { - "Host": "localhost", - "Port": 5010 - } - ], - "UpstreamPathTemplate": "/{everything}", - "UpstreamHttpMethod": [ "Get", "Post", "Put", "Patch", "Delete" ], - "RateLimitOptions": { - "ClientWhitelist": [], - "EnableRateLimiting": true, - "Period": "1s", - "PeriodTimespan": 1, - "Limit": 10 - }, - "FileCacheOptions": { - "TtlSeconds": 0, - "Region": "VN" - }, - "HttpHandlerOptions": { - "AllowAutoRedirect": true, - "UseCookieContainer": true, - "UseTracing": true, - "MaxConnectionsPerServer": 20 - } - } - ], - "GlobalConfiguration": { - "BaseUrl": "" - } -} \ No newline at end of file diff --git a/src/applications/mixcore.gateway/ocelot.sample.json b/src/applications/mixcore.gateway/ocelot.sample.json deleted file mode 100644 index 7c583e0ba..000000000 --- a/src/applications/mixcore.gateway/ocelot.sample.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "Routes": [ - { - "Priority": 0, - "DownstreamPathTemplate": "/{everything}", - "DownstreamScheme": "https", - "DownstreamHostAndPorts": [ - { - "Host": "localhost", - "Port": 5010 - } - ], - "UpstreamPathTemplate": "/{everything}", - "UpstreamHttpMethod": [ "Get", "Post", "Put", "Patch", "Delete", "options" ], - "RateLimitOptions": { - "ClientWhitelist": [], - "EnableRateLimiting": true, - "Period": "1s", - "PeriodTimespan": 1, - "Limit": 100 - }, - "FileCacheOptions": { - "TtlSeconds": 10, - "Region": "VN" - }, - "HttpHandlerOptions": { - "AllowAutoRedirect": true, - "UseCookieContainer": true, - "UseTracing": true, - "MaxConnectionsPerServer": 20 - } - }, - { - "Priority": 1, - "DownstreamPathTemplate": "/hub/{everything}", - "DownstreamScheme": "ws", - "DownstreamHostAndPorts": [ - { - "Host": "localhost", - "Port": 5010 - } - ], - "UpstreamPathTemplate": "/hub/{everything}", - "UpstreamHttpMethod": [ "Get", "Post", "Put", "Patch", "Delete", "options" ], - "RateLimitOptions": { - "ClientWhitelist": [], - "EnableRateLimiting": true, - "Period": "1s", - "PeriodTimespan": 1, - "Limit": 100 - }, - "FileCacheOptions": { - "TtlSeconds": 10, - "Region": "VN" - }, - "HttpHandlerOptions": { - "AllowAutoRedirect": true, - "UseCookieContainer": true, - "UseTracing": true, - "MaxConnectionsPerServer": 20 - } - } - ], - "GlobalConfiguration": { - "RateLimitOptions": { - "DisableRateLimitHeaders": false, - "QuotaExceededMessage": "Customize Tips!", - "HttpStatusCode": 999, - "ClientIdHeader": "Test" - }, - "HttpHandlerOptions": { - "AllowAutoRedirect": true, - "UseCookieContainer": true, - "UseTracing": true, - "MaxConnectionsPerServer": 20 - }, - "BaseUrl": "https://localhost:7221" - } -} \ No newline at end of file diff --git a/src/services/mix-message-queue/mix.mq.server/runtimeconfig.template.json b/src/applications/mixcore.gateway/runtimeconfig.template.json similarity index 100% rename from src/services/mix-message-queue/mix.mq.server/runtimeconfig.template.json rename to src/applications/mixcore.gateway/runtimeconfig.template.json diff --git a/src/applications/mixcore.host.aspire.AppHost/Program.cs b/src/applications/mixcore.host.aspire.AppHost/Program.cs new file mode 100644 index 000000000..b64702668 --- /dev/null +++ b/src/applications/mixcore.host.aspire.AppHost/Program.cs @@ -0,0 +1,8 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var mixMq = builder.AddProject("mix-mq-server"); + +builder.AddProject("mixcore").WithReference(mixMq); +builder.AddProject("gateway").WithReference(mixMq); + +builder.Build().Run(); diff --git a/src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/Properties/launchSettings.json b/src/applications/mixcore.host.aspire.AppHost/Properties/launchSettings.json similarity index 72% rename from src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/Properties/launchSettings.json rename to src/applications/mixcore.host.aspire.AppHost/Properties/launchSettings.json index 606cc3684..0e7a9db7a 100644 --- a/src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/Properties/launchSettings.json +++ b/src/applications/mixcore.host.aspire.AppHost/Properties/launchSettings.json @@ -9,7 +9,8 @@ "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "DOTNET_ENVIRONMENT": "Development", - "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:16178" + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:16178", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22212" } } } diff --git a/src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/appsettings.Development.json b/src/applications/mixcore.host.aspire.AppHost/appsettings.Development.json similarity index 100% rename from src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/appsettings.Development.json rename to src/applications/mixcore.host.aspire.AppHost/appsettings.Development.json diff --git a/src/applications/mixcore.host.aspire.AppHost/mixcore.host.aspire.AppHost.csproj b/src/applications/mixcore.host.aspire.AppHost/mixcore.host.aspire.AppHost.csproj new file mode 100644 index 000000000..643a0fcee --- /dev/null +++ b/src/applications/mixcore.host.aspire.AppHost/mixcore.host.aspire.AppHost.csproj @@ -0,0 +1,23 @@ + + + + Exe + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/src/applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/Extensions.cs b/src/applications/mixcore.host.aspire.ServiceDefaults/Extensions.cs similarity index 99% rename from src/applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/Extensions.cs rename to src/applications/mixcore.host.aspire.ServiceDefaults/Extensions.cs index bbe43d57a..c9046b234 100644 --- a/src/applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/Extensions.cs +++ b/src/applications/mixcore.host.aspire.ServiceDefaults/Extensions.cs @@ -11,7 +11,7 @@ namespace Microsoft.Extensions.Hosting; public static class Extensions { - public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder) + public static IHostApplicationBuilder AddServiceDefaults(this WebApplicationBuilder builder) { builder.ConfigureOpenTelemetry(); diff --git a/src/applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj b/src/applications/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj similarity index 85% rename from src/applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj rename to src/applications/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj index 07112a618..f0c3e82f2 100644 --- a/src/applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj +++ b/src/applications/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj @@ -13,16 +13,17 @@ - + - + - - + + - - - + + + + diff --git a/src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/Program.cs b/src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/Program.cs deleted file mode 100644 index 1f65b47c9..000000000 --- a/src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/Program.cs +++ /dev/null @@ -1,10 +0,0 @@ -var builder = DistributedApplication.CreateBuilder(args); - -//var mixmq = builder.AddProject("mix.mq.server"); - -var mixcore = builder.AddProject("mixcore"); - -//builder.AddProject("mix.auth.api"); -builder.AddProject("mixcore.gateway"); - -builder.Build().Run(); diff --git a/src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/mixcore.host.aspire.AppHost.csproj b/src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/mixcore.host.aspire.AppHost.csproj deleted file mode 100644 index 61bf092d4..000000000 --- a/src/applications/mixcore.host.aspire/mixcore.host.aspire.AppHost/mixcore.host.aspire.AppHost.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - Exe - net8.0 - enable - enable - true - - - - - - - - - - - - - - diff --git a/src/applications/mixcore/Controllers/AppController.cs b/src/applications/mixcore/Controllers/AppController.cs index c07645d34..216b55e43 100644 --- a/src/applications/mixcore/Controllers/AppController.cs +++ b/src/applications/mixcore/Controllers/AppController.cs @@ -1,8 +1,5 @@ using Microsoft.AspNetCore.Mvc; using Mix.Database.Services; -using Mix.Lib.Interfaces; -using Mix.Lib.Services; -using Mix.Shared.Models.Configurations; using Mix.Shared.Services; namespace Mixcore.Controllers @@ -14,7 +11,7 @@ public class AppController : MixControllerBase protected readonly MixCmsContext CmsContext; private readonly MixCacheService _cacheService; private readonly DatabaseService _databaseService; - public AppController( + public AppController( IHttpContextAccessor httpContextAccessor, IPSecurityConfigService ipSecurityConfigService, IMixCmsService mixCmsService, diff --git a/src/applications/mixcore/Controllers/HomeController.cs b/src/applications/mixcore/Controllers/HomeController.cs index 7bf8d3758..f1cedc399 100644 --- a/src/applications/mixcore/Controllers/HomeController.cs +++ b/src/applications/mixcore/Controllers/HomeController.cs @@ -2,7 +2,6 @@ using Mix.Database.Services; using Mix.Heart.Exceptions; using Mix.Heart.Extensions; -using Mix.Lib.Interfaces; using Mix.Lib.Services; using Mix.RepoDb.Interfaces; using Mix.RepoDb.Repositories; diff --git a/src/applications/mixcore/Controllers/ModuleDataController.cs b/src/applications/mixcore/Controllers/ModuleDataController.cs index 9b4f96d96..e126a1c0f 100644 --- a/src/applications/mixcore/Controllers/ModuleDataController.cs +++ b/src/applications/mixcore/Controllers/ModuleDataController.cs @@ -20,7 +20,7 @@ public ModuleDataController(IHttpContextAccessor httpContextAccessor, IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { } diff --git a/src/applications/mixcore/Controllers/PageContentApiController.cs b/src/applications/mixcore/Controllers/PageContentApiController.cs index a58a23113..397305e47 100644 --- a/src/applications/mixcore/Controllers/PageContentApiController.cs +++ b/src/applications/mixcore/Controllers/PageContentApiController.cs @@ -1,13 +1,8 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Heart.Extensions; -using Mix.Heart.Helpers; -using Mix.Lib.Models.Common; using Mix.Lib.Services; using Mix.Mq.Lib.Models; using Mix.RepoDb.Interfaces; -using Mix.RepoDb.Repositories; using Mix.Services.Databases.Lib.Interfaces; -using Mix.Shared.Models; using Mix.SignalR.Interfaces; namespace Mixcore.Controllers diff --git a/src/applications/mixcore/Controllers/PageController.cs b/src/applications/mixcore/Controllers/PageController.cs index aef220707..82df8c6ea 100644 --- a/src/applications/mixcore/Controllers/PageController.cs +++ b/src/applications/mixcore/Controllers/PageController.cs @@ -1,7 +1,6 @@ using Microsoft.AspNetCore.Mvc; using Mix.Database.Services; using Mix.RepoDb.Interfaces; -using Mix.RepoDb.Repositories; using Mix.Services.Databases.Lib.Interfaces; using Mix.Shared.Services; diff --git a/src/applications/mixcore/Controllers/PostContentApiController.cs b/src/applications/mixcore/Controllers/PostContentApiController.cs index 1edd3e24a..e58fe6621 100644 --- a/src/applications/mixcore/Controllers/PostContentApiController.cs +++ b/src/applications/mixcore/Controllers/PostContentApiController.cs @@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Mvc; using Mix.Heart.Exceptions; using Mix.Heart.Extensions; -using Mix.Heart.Helpers; using Mix.Lib.Models.Common; using Mix.Lib.Services; using Mix.Mq.Lib.Models; diff --git a/src/applications/mixcore/Controllers/PostController.cs b/src/applications/mixcore/Controllers/PostController.cs index eb8c2d1be..c8f5647f5 100644 --- a/src/applications/mixcore/Controllers/PostController.cs +++ b/src/applications/mixcore/Controllers/PostController.cs @@ -1,7 +1,6 @@ using Microsoft.AspNetCore.Mvc; using Mix.Database.Entities.MixDb; using Mix.Database.Services; -using Mix.Lib.Interfaces; using Mix.RepoDb.Interfaces; using Mix.RepoDb.Repositories; using Mix.Services.Databases.Lib.Interfaces; @@ -93,7 +92,7 @@ protected async Task Post(int postId, string seoName = null) return NotFound(); } await post.LoadAdditionalDataAsync(_mixDbDataService, _metadataService, _cacheService); - + ViewData["Title"] = post.SeoTitle; ViewData["Description"] = post.SeoDescription; ViewData["Keywords"] = post.SeoKeywords; diff --git a/src/applications/mixcore/Domain/Extensions/ServiceExtension.cs b/src/applications/mixcore/Domain/Extensions/ServiceExtension.cs index 2e1b9ee47..bde508f46 100644 --- a/src/applications/mixcore/Domain/Extensions/ServiceExtension.cs +++ b/src/applications/mixcore/Domain/Extensions/ServiceExtension.cs @@ -23,7 +23,7 @@ public static void UseMixMVCEndpoints(this IEndpointRouteBuilder routes) { string notStartWithPattern = "regex(^(?!(mix-app|graph|app|init|page|post|security|portal|api|vue|error|swagger|graphql|ReDoc|OpenAPI|.+Hub))(.+)$)"; //string urlPathPattern = @"regex((([A-z0-9\-\%]+\/)*[A-z0-9\-\%]+$)?)"; - + routes.MapDynamicControllerRoute( pattern: "{seoName:" + notStartWithPattern + "}"); routes.MapDynamicControllerRoute( diff --git a/src/applications/mixcore/Domain/StartupServices.cs b/src/applications/mixcore/Domain/StartupServices.cs index d66d94d3c..e000a6397 100644 --- a/src/applications/mixcore/Domain/StartupServices.cs +++ b/src/applications/mixcore/Domain/StartupServices.cs @@ -1,9 +1,6 @@ -using Microsoft.Extensions.DependencyInjection.Extensions; -using Mix.Lib.Publishers; +using Mix.Lib.Publishers; using Mix.Lib.Subscribers; -using Mix.Log.Lib.Publishers; using Mix.Log.Lib.Subscribers; -using Mix.Quartz.Interfaces; using Mix.Quartz.Services; using Mix.RepoDb.Publishers; using Mix.RepoDb.Subscribers; @@ -30,7 +27,7 @@ public void AddServices(IServiceCollection services, IConfiguration configuratio services.AddHostedService(); services.AddHostedService(); - services.AddMixQuartzServices(configuration); + services.AddHostedService(); services.AddHostedService(); if (!globalConfigs!.IsInit) diff --git a/src/applications/mixcore/Domain/ViewModels/ApplicationViewModel.cs b/src/applications/mixcore/Domain/ViewModels/ApplicationViewModel.cs index a53d3cc4e..6e7ea12f2 100644 --- a/src/applications/mixcore/Domain/ViewModels/ApplicationViewModel.cs +++ b/src/applications/mixcore/Domain/ViewModels/ApplicationViewModel.cs @@ -1,7 +1,6 @@ using Mix.Heart.Helpers; using Mix.Lib.ViewModels.ReadOnly; using Mix.RepoDb.Interfaces; -using Mix.RepoDb.Repositories; namespace Mixcore.Domain.ViewModels { diff --git a/src/applications/mixcore/Domain/ViewModels/ModuleContentViewModel.cs b/src/applications/mixcore/Domain/ViewModels/ModuleContentViewModel.cs index fa75ccca4..f14d49568 100644 --- a/src/applications/mixcore/Domain/ViewModels/ModuleContentViewModel.cs +++ b/src/applications/mixcore/Domain/ViewModels/ModuleContentViewModel.cs @@ -1,8 +1,6 @@ using Mix.Heart.Helpers; using Mix.RepoDb.Interfaces; -using Mix.RepoDb.Repositories; using Mix.Services.Databases.Lib.Interfaces; -using MySqlX.XDevAPI.Common; namespace Mixcore.Domain.ViewModels { diff --git a/src/applications/mixcore/Domain/ViewModels/PageContentViewModel.cs b/src/applications/mixcore/Domain/ViewModels/PageContentViewModel.cs index eebf27ea3..3025e2030 100644 --- a/src/applications/mixcore/Domain/ViewModels/PageContentViewModel.cs +++ b/src/applications/mixcore/Domain/ViewModels/PageContentViewModel.cs @@ -1,7 +1,6 @@ using Microsoft.EntityFrameworkCore; using Mix.Heart.Helpers; using Mix.RepoDb.Interfaces; -using Mix.RepoDb.Repositories; using Mix.Services.Databases.Lib.Interfaces; using Mix.Shared.Models; @@ -53,8 +52,8 @@ public override async Task ExpandView(CancellationToken cancellationToken = defa #region Public Method - public async Task LoadDataAsync(IMixDbDataService mixDbDataService, - IMixMetadataService metadataService, + public async Task LoadDataAsync(IMixDbDataService mixDbDataService, + IMixMetadataService metadataService, PagingRequestModel pagingModel, MixCacheService cacheService) { await LoadAdditionalDataAsync(mixDbDataService); diff --git a/src/applications/mixcore/Domain/ViewModels/PostContentViewModel.cs b/src/applications/mixcore/Domain/ViewModels/PostContentViewModel.cs index 2dcd8b678..89173ac2b 100644 --- a/src/applications/mixcore/Domain/ViewModels/PostContentViewModel.cs +++ b/src/applications/mixcore/Domain/ViewModels/PostContentViewModel.cs @@ -1,10 +1,7 @@ using Mix.Heart.Helpers; using Mix.RepoDb.Interfaces; -using Mix.RepoDb.Repositories; using Mix.Services.Databases.Lib.Interfaces; using Mix.Services.Databases.Lib.Models; -using RepoDb; -using RepoDb.Enumerations; namespace Mixcore.Domain.ViewModels { diff --git a/src/applications/mixcore/Program.cs b/src/applications/mixcore/Program.cs index 59feb2a2f..18aa4ecdb 100644 --- a/src/applications/mixcore/Program.cs +++ b/src/applications/mixcore/Program.cs @@ -1,14 +1,20 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Mix.Database.Entities.Account; +using Mix.Lib.Middlewares; +using Mix.Lib.Publishers; +using Mix.Lib.Services; +using Mix.Lib.Subscribers; +using Mix.Log.Lib; +using Mix.Log.Lib.Subscribers; +using Mix.Quartz.Services; +using Mix.Queue.Extensions; +using Mix.RepoDb.Publishers; +using Mix.RepoDb.Subscribers; +using Mix.Shared.Models.Configurations; +using Mix.Storage.Lib.Subscribers; using System.Reflection; using System.Text.Encodings.Web; using System.Text.Unicode; -using Mix.Log.Lib; -using Microsoft.Extensions.FileProviders; -using Mix.Lib.Middlewares; -using Mix.Shared.Services; -using Mix.Shared.Models.Configurations; -using Mix.Queue.Extensions; var builder = MixCmsHelper.CreateWebApplicationBuilder(args); if (builder.Environment.IsDevelopment()) @@ -34,11 +40,16 @@ builder.Services.AddScoped(); builder.Services.AddMixLog(builder.Configuration); builder.Services.AddMixAuthorize(builder.Configuration); - +builder.Services.AddScoped(); builder.Services.TryAddScoped(); - +AddPortalServices(builder.Services, builder.Configuration); var app = builder.Build(); +if (builder.Environment.IsDevelopment()) +{ + app.MapDefaultEndpoints(); +} + Configure(app, builder.Environment, builder.Configuration); app.Run(); @@ -60,14 +71,14 @@ void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration // Typically, UseStaticFiles is called before UseCors. Apps that use JavaScript to retrieve static files cross site must call UseCors before UseStaticFiles. app.UseMixStaticFiles(env.ContentRootPath); - + // UseCors must be placed after UseRouting and before UseAuthorization. This is to ensure that CORS headers are included in the response for both authorized and unauthorized calls. app.UseMixCors(); // must go between app.UseRouting() and app.UseEndpoints. app.UseMixAuth(); - + app.UseMixRateLimiter(); app.UseMixApps(Assembly.GetExecutingAssembly(), configuration, env.ContentRootPath, env.IsDevelopment()); app.UseMixSwaggerApps(env.IsDevelopment(), Assembly.GetExecutingAssembly()); app.UseResponseCompression(); @@ -81,4 +92,30 @@ void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration //} -} \ No newline at end of file +} + +void AddPortalServices(IServiceCollection services, IConfiguration configuration) +{ + var globalConfigs = configuration.GetSection(MixAppSettingsSection.GlobalSettings).Get()!; + services.AddMixRoutes(); + + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + + services.AddHostedService(); + services.AddHostedService(); + + if (!globalConfigs!.IsInit) + { + services.AddHostedService(); + } + + services.AddMixRateLimiter(configuration); +} diff --git a/src/applications/mixcore/mixcore.csproj b/src/applications/mixcore/mixcore.csproj index fba68cdab..213ad162b 100644 --- a/src/applications/mixcore/mixcore.csproj +++ b/src/applications/mixcore/mixcore.csproj @@ -14,10 +14,7 @@ - - - - + @@ -58,19 +55,22 @@ + + + - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + @@ -89,9 +89,6 @@ true PreserveNewest - - PreserveNewest - diff --git a/src/applications/mixcore/mixcore.gateway.csproj b/src/applications/mixcore/mixcore.gateway.csproj deleted file mode 100644 index 008722f7c..000000000 --- a/src/applications/mixcore/mixcore.gateway.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - net8.0 - false - true - false - enable - enable - true - Mixcore.Gateway - bbdd7c53-6dfa-4f6f-ab46-5ecda7005ed0 - Linux - ..\.. - - - - - - - - - - - - - - - - - - - - diff --git a/src/applications/mixcore/mixcore.gateway.http b/src/applications/mixcore/mixcore.gateway.http deleted file mode 100644 index 32ea4bf3d..000000000 --- a/src/applications/mixcore/mixcore.gateway.http +++ /dev/null @@ -1,6 +0,0 @@ -@mixcore.gateway_HostAddress = http://localhost:5025 - -GET {{mixcore.gateway_HostAddress}}/weatherforecast/ -Accept: application/json - -### diff --git a/src/modules/mix.common/Controllers/SettingApiController.cs b/src/modules/mix.common/Controllers/SettingApiController.cs index 74bcc966c..e8fd61d53 100644 --- a/src/modules/mix.common/Controllers/SettingApiController.cs +++ b/src/modules/mix.common/Controllers/SettingApiController.cs @@ -6,7 +6,6 @@ using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; using Mix.Service.Models; -using MySqlX.XDevAPI.Common; namespace Mix.Common.Controllers { @@ -25,7 +24,7 @@ public SettingApiController( MixIdentityService mixIdentityService, IMemoryQueueService queueService, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, queueService, mixTenantService) { } diff --git a/src/modules/mix.common/Controllers/SharedApiController.cs b/src/modules/mix.common/Controllers/SharedApiController.cs index 563f49fda..4e2fb710a 100644 --- a/src/modules/mix.common/Controllers/SharedApiController.cs +++ b/src/modules/mix.common/Controllers/SharedApiController.cs @@ -6,18 +6,14 @@ using Mix.Common.Domain.Dtos; using Mix.Common.Domain.Models; using Mix.Common.Domain.ViewModels; -using Mix.Database.Entities.MixDb; using Mix.Heart.Exceptions; using Mix.Lib.Interfaces; using Mix.Lib.Services; -using Mix.Mixdb.ViewModels; using Mix.Mq.Lib.Models; -using Mix.Queue.Engines.MixQueue; using Mix.Queue.Interfaces; using Mix.Shared.Models.Configurations; using Mix.Shared.Services; using Mix.SignalR.Enums; -using Mix.SignalR.Hubs; using Mix.SignalR.Interfaces; using Mix.SignalR.Models; using System.Diagnostics; diff --git a/src/modules/mix.common/Domain/Helpers/CommonHelper.cs b/src/modules/mix.common/Domain/Helpers/CommonHelper.cs index 57b7acf3b..b63c4822c 100644 --- a/src/modules/mix.common/Domain/Helpers/CommonHelper.cs +++ b/src/modules/mix.common/Domain/Helpers/CommonHelper.cs @@ -1,5 +1,4 @@ -using Mix.Common.Models; -using Mix.Service.Models; +using Mix.Service.Models; using Mix.Shared.Models.Configurations; using Mix.Shared.Services; diff --git a/src/modules/mix.common/Domain/ViewModels/PostContentViewModel.cs b/src/modules/mix.common/Domain/ViewModels/PostContentViewModel.cs index 88d9752da..23cf3fd96 100644 --- a/src/modules/mix.common/Domain/ViewModels/PostContentViewModel.cs +++ b/src/modules/mix.common/Domain/ViewModels/PostContentViewModel.cs @@ -1,7 +1,4 @@ using Mix.RepoDb.Interfaces; -using Mix.RepoDb.Repositories; -using RepoDb; -using RepoDb.Enumerations; namespace Mix.Common.Domain.ViewModels { diff --git a/src/modules/mix.common/Startup.cs b/src/modules/mix.common/Startup.cs index 3e316e154..67683ded4 100644 --- a/src/modules/mix.common/Startup.cs +++ b/src/modules/mix.common/Startup.cs @@ -1,4 +1,5 @@ using Mix.Database.Entities.Account; +using Mix.Lib.Services; using System.Reflection; namespace Mix.Common @@ -19,6 +20,7 @@ public void ConfigureServices(IServiceCollection services) // Must app Auth config after Add mixservice to init App config services.AddMixAuthorize(Configuration); + services.AddScoped(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/src/modules/mix.grpc/Domain/Models/GrpcChannelModel.cs b/src/modules/mix.grpc/Domain/Models/GrpcChannelModel.cs index 2eca7593d..6a0d9389b 100644 --- a/src/modules/mix.grpc/Domain/Models/GrpcChannelModel.cs +++ b/src/modules/mix.grpc/Domain/Models/GrpcChannelModel.cs @@ -1,9 +1,7 @@ -using Grpc.Core; -using Grpc.Net.Client; +using Grpc.Net.Client; using Microsoft.AspNetCore.Http; using System; using System.Net.Http; -using System.Threading.Tasks; namespace Mix.Grpc.Domain.Models { diff --git a/src/modules/mix.grpc/Domain/StartupService.cs b/src/modules/mix.grpc/Domain/StartupService.cs index 53e294e40..34516f3b3 100644 --- a/src/modules/mix.grpc/Domain/StartupService.cs +++ b/src/modules/mix.grpc/Domain/StartupService.cs @@ -3,7 +3,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Mix.Grpc.Domain.Services; -using Mix.Lib.Interfaces; using Mix.Shared.Interfaces; namespace Mix.Grpc.Domain diff --git a/src/modules/mix.grpc/mix.grpc.csproj b/src/modules/mix.grpc/mix.grpc.csproj index 422ada4ec..85fbb6527 100644 --- a/src/modules/mix.grpc/mix.grpc.csproj +++ b/src/modules/mix.grpc/mix.grpc.csproj @@ -6,7 +6,7 @@ - + diff --git a/src/modules/mix.log/Controllers/MixAuditLogController.cs b/src/modules/mix.log/Controllers/MixAuditLogController.cs index a7017c9e9..854b33ea0 100644 --- a/src/modules/mix.log/Controllers/MixAuditLogController.cs +++ b/src/modules/mix.log/Controllers/MixAuditLogController.cs @@ -2,10 +2,9 @@ using Mix.Auth.Constants; using Mix.Constant.Constants; using Mix.Database.Entities.AuditLog; -using Mix.Database.Entities.Queue; +using Mix.Database.Services; using Mix.Heart.Enums; using Mix.Heart.Exceptions; -using Mix.Heart.Models; using Mix.Heart.Services; using Mix.Heart.UnitOfWork; using Mix.Lib.Attributes; @@ -28,6 +27,7 @@ namespace Mix.Log.Controllers public class AuditLogController : MixQueryApiControllerBase { + private readonly DatabaseService _databaseService; public AuditLogController( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, @@ -37,11 +37,12 @@ public AuditLogController( UnitOfWorkInfo uow, IMemoryQueueService queueService, IPortalHubClientService portalHub, - IMixTenantService mixTenantService) + IMixTenantService mixTenantService, + DatabaseService databaseService) : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { - + _databaseService = databaseService; } #region Routes @@ -107,7 +108,7 @@ private async Task> SearchByDate(SearchQueryM }; } - using (var context = new AuditLogDbContext(searchDate)) + using (var context = _databaseService.GetAuditLogDbContext()) { using (var AuditLogUow = new UnitOfWorkInfo(context)) { diff --git a/src/modules/mix.log/Controllers/MixQueueLogController.cs b/src/modules/mix.log/Controllers/MixQueueLogController.cs index a9a2c5ff0..96c84da50 100644 --- a/src/modules/mix.log/Controllers/MixQueueLogController.cs +++ b/src/modules/mix.log/Controllers/MixQueueLogController.cs @@ -1,11 +1,10 @@ using Microsoft.AspNetCore.Mvc; -using Microsoft.VisualBasic; using Mix.Auth.Constants; using Mix.Constant.Constants; -using Mix.Database.Entities.Queue; +using Mix.Database.Entities.QueueLog; +using Mix.Database.Services; using Mix.Heart.Enums; using Mix.Heart.Exceptions; -using Mix.Heart.Models; using Mix.Heart.Services; using Mix.Heart.UnitOfWork; using Mix.Lib.Attributes; @@ -17,7 +16,6 @@ using Mix.Log.Lib.ViewModels; using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; -using Mix.Service.Services; using Mix.Shared.Dtos; using Mix.SignalR.Interfaces; @@ -26,18 +24,20 @@ namespace Mix.Log.Controllers [Route("api/v2/rest/mix-log/queue-log")] [ApiController] [MixAuthorize(MixRoles.Owner)] - public class MixQueueLogController : MixQueryApiControllerBase + public class MixQueueLogController : MixQueryApiControllerBase { + private readonly DatabaseService _databaseService; public MixQueueLogController( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, MixCacheService cacheService, TranslatorService translator, MixIdentityService mixIdentityService, - UnitOfWorkInfo uow, + UnitOfWorkInfo uow, IMemoryQueueService queueService, IPortalHubClientService portalHub, - IMixTenantService mixTenantService) + IMixTenantService mixTenantService, + DatabaseService databaseService) : base( httpContextAccessor, configuration, @@ -49,6 +49,7 @@ public MixQueueLogController( portalHub, mixTenantService) { + _databaseService = databaseService; } #region Routes @@ -99,7 +100,7 @@ public async Task Search([FromQuery] SearchRequestDto req, Cancell #region Overrides - private async Task> SearchByDate(SearchQueryModel searchRequest, DateTime searchDate, CancellationToken cancellationToken) + private async Task> SearchByDate(SearchQueryModel searchRequest, DateTime searchDate, CancellationToken cancellationToken) { try { @@ -114,7 +115,7 @@ private async Task> SearchByDate(Se }; } - using (var context = new MixQueueDbContext(searchDate)) + using (var context = _databaseService.GetQueueLogDbContext()) { using (var MixQueueMessageLogUow = new UnitOfWorkInfo(context)) { diff --git a/src/modules/mix.log/StartupService.cs b/src/modules/mix.log/StartupService.cs index 2839b485d..9a61939dd 100644 --- a/src/modules/mix.log/StartupService.cs +++ b/src/modules/mix.log/StartupService.cs @@ -1,5 +1,4 @@ -using Mix.Lib.Interfaces; -using Mix.Shared.Interfaces; +using Mix.Shared.Interfaces; namespace Mix.Log { diff --git a/src/modules/mix.messenger/Domain/StartupService.cs b/src/modules/mix.messenger/Domain/StartupService.cs index b39709884..41caf1988 100644 --- a/src/modules/mix.messenger/Domain/StartupService.cs +++ b/src/modules/mix.messenger/Domain/StartupService.cs @@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Mix.Lib.Interfaces; using Mix.Shared.Interfaces; namespace Mix.Messenger.Domain diff --git a/src/modules/mix.portal/Controllers/CommonController.cs b/src/modules/mix.portal/Controllers/CommonController.cs index 6f5ed462b..7c1b15394 100644 --- a/src/modules/mix.portal/Controllers/CommonController.cs +++ b/src/modules/mix.portal/Controllers/CommonController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Heart.Helpers; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; @@ -27,7 +26,7 @@ public CommonController( TenantUserManager userManager, MixRepoDbRepository repoDbRepository, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, queueService, mixTenantService) { _context = context; diff --git a/src/modules/mix.portal/Controllers/MixApplicationController.cs b/src/modules/mix.portal/Controllers/MixApplicationController.cs index 1fc9865e8..3a01124cc 100644 --- a/src/modules/mix.portal/Controllers/MixApplicationController.cs +++ b/src/modules/mix.portal/Controllers/MixApplicationController.cs @@ -1,7 +1,4 @@ -using FirebaseAdmin.Auth.Multitenancy; -using Microsoft.AspNetCore.Mvc; -using Microsoft.CodeAnalysis.Elfie.Diagnostics; -using Mix.Database.Entities.AuditLog; +using Microsoft.AspNetCore.Mvc; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; diff --git a/src/modules/mix.portal/Controllers/MixConfigurationController.cs b/src/modules/mix.portal/Controllers/MixConfigurationController.cs index c2dbb6853..6e710abf4 100644 --- a/src/modules/mix.portal/Controllers/MixConfigurationController.cs +++ b/src/modules/mix.portal/Controllers/MixConfigurationController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; @@ -25,7 +24,7 @@ public MixConfigurationController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { _cmsUow = uow; diff --git a/src/modules/mix.portal/Controllers/MixCultureController.cs b/src/modules/mix.portal/Controllers/MixCultureController.cs index 61f8d93f1..d36412da6 100644 --- a/src/modules/mix.portal/Controllers/MixCultureController.cs +++ b/src/modules/mix.portal/Controllers/MixCultureController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.Portal.Domain.Interfaces; @@ -25,7 +24,7 @@ public MixCultureController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { _cloneCultureService = cloneCultureService; diff --git a/src/modules/mix.portal/Controllers/MixDatabaseAssociationController.cs b/src/modules/mix.portal/Controllers/MixDatabaseAssociationController.cs index e188b4300..0163ab692 100644 --- a/src/modules/mix.portal/Controllers/MixDatabaseAssociationController.cs +++ b/src/modules/mix.portal/Controllers/MixDatabaseAssociationController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; @@ -22,7 +21,7 @@ public MixDatabaseAssociationController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { diff --git a/src/modules/mix.portal/Controllers/MixDatabaseColumnPortalController.cs b/src/modules/mix.portal/Controllers/MixDatabaseColumnPortalController.cs index d038fd8da..0a179bc07 100644 --- a/src/modules/mix.portal/Controllers/MixDatabaseColumnPortalController.cs +++ b/src/modules/mix.portal/Controllers/MixDatabaseColumnPortalController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Heart.Helpers; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; diff --git a/src/modules/mix.portal/Controllers/MixDatabaseContextController.cs b/src/modules/mix.portal/Controllers/MixDatabaseContextController.cs index 3efe6a8da..64553e50b 100644 --- a/src/modules/mix.portal/Controllers/MixDatabaseContextController.cs +++ b/src/modules/mix.portal/Controllers/MixDatabaseContextController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Heart.Helpers; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; diff --git a/src/modules/mix.portal/Controllers/MixDatabaseController.cs b/src/modules/mix.portal/Controllers/MixDatabaseController.cs index 708c87ea7..ffca20040 100644 --- a/src/modules/mix.portal/Controllers/MixDatabaseController.cs +++ b/src/modules/mix.portal/Controllers/MixDatabaseController.cs @@ -1,6 +1,7 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; +using Mix.Database.Services; using Mix.Lib.Interfaces; +using Mix.Mixdb.Services; using Mix.Mq.Lib.Models; using Mix.RepoDb.Interfaces; using Mix.RepoDb.ViewModels; @@ -15,6 +16,7 @@ namespace Mix.Portal.Controllers public class MixDatabaseController : MixRestfulApiControllerBase { + private readonly DatabaseService _databaseService; private readonly IMixDbService _mixDbService; private readonly IMixMemoryCacheService _memoryCache; public MixDatabaseController( @@ -28,12 +30,14 @@ public MixDatabaseController( IMixDbService mixDbService, IPortalHubClientService portalHub, IMixTenantService mixTenantService, - IMixMemoryCacheService memoryCache) + IMixMemoryCacheService memoryCache, + DatabaseService databaseService) : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cmsUow, queueService, portalHub, mixTenantService) { _mixDbService = mixDbService; _memoryCache = memoryCache; + _databaseService = databaseService; } #region Routes @@ -62,6 +66,24 @@ public async Task> Duplicate(int id, Cancella throw new MixException(MixErrorStatus.NotFound, id); } + //[MixAuthorize(MixRoles.Owner)] + [HttpGet("export-entity/{dbContextName}")] + public async Task ExportEntity(string dbContextName) + { + MixDatabaseContextViewModel dbContext = await MixDatabaseContextViewModel + .GetRepository(Uow, CacheService).GetSingleAsync(m => m.SystemName == dbContextName); + if (dbContext == null) + { + return BadRequest(dbContextName); + } + var runtimeDbContextService = new RuntimeDbContextService(HttpContextAccessor, _databaseService); + string cnn = dbContext != null + ? dbContext.ConnectionString + : _databaseService.GetConnectionString(MixConstants.CONST_MIXDB_CONNECTION); + var sourceFiles = runtimeDbContextService.CreateDynamicDbContext(cnn); + return Ok(sourceFiles); + } + [MixAuthorize(MixRoles.Owner)] [HttpGet("migrate/{name}")] public async Task Migrate(string name) diff --git a/src/modules/mix.portal/Controllers/MixDatabaseRelationshipController.cs b/src/modules/mix.portal/Controllers/MixDatabaseRelationshipController.cs index 4f4c9c6ed..49a5c5897 100644 --- a/src/modules/mix.portal/Controllers/MixDatabaseRelationshipController.cs +++ b/src/modules/mix.portal/Controllers/MixDatabaseRelationshipController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; diff --git a/src/modules/mix.portal/Controllers/MixDbController.cs b/src/modules/mix.portal/Controllers/MixDbController.cs index 933a166bc..c6ebc1d5c 100644 --- a/src/modules/mix.portal/Controllers/MixDbController.cs +++ b/src/modules/mix.portal/Controllers/MixDbController.cs @@ -1,10 +1,5 @@ -using Amazon.SQS.Model.Internal.MarshallTransformations; -using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing; -using DocumentFormat.OpenXml.Spreadsheet; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Azure; using Mix.Database.Services; using Mix.Heart.Helpers; using Mix.Heart.Model; @@ -14,7 +9,6 @@ using Mix.RepoDb.Helpers; using Mix.RepoDb.Interfaces; using Mix.RepoDb.Repositories; -using Mix.RepoDb.Services; using Mix.RepoDb.ViewModels; using Mix.Service.Commands; using Mix.Service.Interfaces; @@ -23,8 +17,6 @@ using Mix.SignalR.Enums; using Mix.SignalR.Interfaces; using Mix.SignalR.Models; -using MySqlX.XDevAPI.Common; -using Org.BouncyCastle.Ocsp; using RepoDb; using RepoDb.Enumerations; using RepoDb.Interfaces; @@ -72,7 +64,7 @@ public MixDbController( cacheService, translator, mixIdentityService, queueService, mixTenantService) { _repository = repository; - _associationRepository = new(cache, databaseService, cmsUow); + _associationRepository = new(cache, databaseService); _associationRepository.InitTableName(AssociationTableName); _cmsUow = cmsUow; _memoryCache = memoryCache; @@ -111,10 +103,10 @@ public async Task>> MyData([FromQuery] } [HttpGet("my-data/{id}")] - public async Task> GetMyDataById(int id, [FromQuery] bool loadNestedData) + public async Task> GetMyDataById(string id, [FromQuery] bool loadNestedData) { string username = _idService.GetClaim(User, MixClaims.Username); - JObject result = await _mixDbDataService.GetMyDataById(_tableName, username, id, loadNestedData); + JObject result = await _mixDbDataService.GetMyDataById(_tableName, username, GetId(id), loadNestedData); return Ok(result); } @@ -152,8 +144,15 @@ public async Task>> Filter([FromBody] [HttpPost("nested-data/filter")] public async Task>> NestedFilter([FromBody] SearchMixDbRequestDto req) { - var result = await SearchManyToManyDataHandler(req); - return Ok(result); + if (req.Relationship == MixDatabaseRelationshipType.ManyToMany) + { + var result = await SearchManyToManyDataHandler(req); + return Ok(result); + } + else + { + return Ok(await SearchHandler(req)); + } } [HttpPost("export")] @@ -171,9 +170,10 @@ public async Task Import([FromForm] IFormFile file) { var data = MixCmsHelper.LoadExcelFileData(file); List lstDto = new(); + var username = _idService.GetClaim(User, MixClaims.Username); foreach (var item in data) { - lstDto.Add(await MixDbHelper.ParseImportDtoToEntityAsync(item, _mixDb.Columns, _fieldNameService, CurrentTenant.Id, _idService.GetClaim(User, MixClaims.Username))); + lstDto.Add(await MixDbHelper.ParseDtoToEntityAsync(item, _mixDb.Type, _mixDb.Columns, _fieldNameService, username: username)); } var result = await _repository.InsertManyAsync(lstDto, _mixDb); @@ -182,22 +182,18 @@ public async Task Import([FromForm] IFormFile file) [HttpGet("{id}")] - public async Task> GetSingle(int id, [FromQuery] bool loadNestedData) + public async Task> GetSingle(string id, [FromQuery] bool loadNestedData) { - var result = await _mixDbDataService.GetById(_tableName, id, loadNestedData); - string username = _idService.GetClaim(User, MixClaims.Username); - QueueService.PushMemoryQueue(CurrentTenant.Id, - MixQueueTopics.MixBackgroundTasks, - MixQueueActions.MixDbEvent - , new MixDbEventCommand(username, MixDbCommandQueueActions.Read, _tableName, result)); + object objId = GetId(id); + var result = await _mixDbDataService.GetById(_tableName, objId, loadNestedData); return result != default ? Ok(result) : NotFound(id); } - [HttpPut("update-priority/{dbName}/{id}")] - public async Task> UpdatePriority(string dbName, int id, [FromBody] UpdatePriorityDto dto) + public async Task> UpdatePriority(string dbName, string id, [FromBody] UpdatePriorityDto dto) { - var data = await _mixDbDataService.GetById(dbName, id, false); + object objId = GetId(id); + var data = await _mixDbDataService.GetById(dbName, objId, false); if (data == null) { return NotFound(); @@ -224,7 +220,7 @@ public async Task> UpdatePriority(string dbName, int id, [ foreach (var item in query.OrderBy(m => m[_fieldNameService.Priority])) { item.Priority = start; - await _repository.UpdateAsync(id, item, _mixDb); + await _repository.UpdateAsync(objId, item, _mixDb); start++; } @@ -347,7 +343,7 @@ public ActionResult CreateHub(object dto) Body = JObject.FromObject(dto), MixDbName = _tableName }; - QueueService.PushMemoryQueue(CurrentTenant.Id, MixQueueTopics.MixDbCommand, MixDbCommandQueueActions.Create, obj); + QueueService.PushMemoryQueue(CurrentTenant.Id, MixQueueTopics.MixDbCommand, MixDbCommandQueueAction.Create.ToString(), obj); return Ok(); } @@ -356,7 +352,7 @@ public ActionResult CreateHub(object dto) public async Task> Create(JObject dto) { string username = _idService.GetClaim(User, MixClaims.Username); - JObject obj = await MixDbHelper.ParseDtoToEntityAsync(dto, _mixDb.Columns, _fieldNameService, CurrentTenant.Id, username); + JObject obj = await MixDbHelper.ParseDtoToEntityAsync(dto, _mixDb.Type, _mixDb.Columns, _fieldNameService, CurrentTenant.Id, username); var id = await _repository.InsertAsync(obj, _mixDb); var resp = await _repository.GetSingleAsync(new QueryField(_fieldNameService.Id, id)); @@ -366,40 +362,43 @@ public async Task> Create(JObject dto) } var result = resp != null ? ReflectionHelper.ParseObject(resp) : obj; - QueueService.PushMemoryQueue(CurrentTenant.Id, MixQueueTopics.MixBackgroundTasks, MixQueueActions.MixDbEvent, - new MixDbEventCommand(username, MixDbCommandQueueActions.Create, _tableName, result)); + await NotifyResult(id, result); return Ok(result); } [PreventDuplicateFormSubmission] [HttpPut("{id}")] - public async Task> Update(int id, [FromBody] JObject dto) + public async Task> Update(string id, [FromBody] JObject dto) { - JObject obj = await MixDbHelper.ParseDtoToEntityAsync(dto, _mixDb.Columns, _fieldNameService, CurrentTenant.Id, _idService.GetClaim(User, MixClaims.Username)); + JObject obj = await MixDbHelper.ParseDtoToEntityAsync(dto, _mixDb.Type, _mixDb.Columns, _fieldNameService, CurrentTenant.Id, _idService.GetClaim(User, MixClaims.Username)); - var data = await _repository.UpdateAsync(id, obj, _mixDb); + var data = await _repository.UpdateAsync(GetId(id), obj, _mixDb); if (data != null) { - var result = await _repository.GetSingleAsync(new QueryField(_fieldNameService.Id, id)); + var result = await _repository.GetSingleAsync(new QueryField(_fieldNameService.Id, GetId(id))); var resp = result != null ? ReflectionHelper.ParseObject(result) : obj; - await NotifyResult(id, resp); + await NotifyResult(GetId(id), resp); return Ok(ReflectionHelper.ParseObject(resp)); } return BadRequest(); } - private async Task NotifyResult(int id, JObject obj) + private async Task NotifyResult(object id, JObject obj) { try { string username = _idService.GetClaim(User, MixClaims.Username); - QueueService.PushMemoryQueue(CurrentTenant.Id, MixQueueTopics.MixBackgroundTasks, MixQueueActions.MixDbEvent, - new MixDbEventCommand(username, MixDbCommandQueueActions.Update, _tableName, obj)); - var modifiedEnties = new List() + QueueService.PushMemoryQueue( + CurrentTenant.Id, + MixQueueTopics.MixBackgroundTasks, + MixQueueActions.MixDbEvent, + new MixDbEventCommand(username, MixDbCommandQueueAction.Update.ToString(), _tableName, obj)); + + var modifiedEntities = new List() { - new ModifiedEntityModel() + new() { Id = id, CacheFolder = $"{MixFolders.MixDbCacheFolder}/{_tableName}", @@ -407,7 +406,7 @@ private async Task NotifyResult(int id, JObject obj) } }; var modifiedData = new JObject() { - new JProperty("modifiedEntiies", JArray.FromObject(modifiedEnties)) + new JProperty("modifiedEntities", JArray.FromObject(modifiedEntities)) }; await PortalHub.SendMessageAsync(new SignalRMessageModel() { @@ -455,17 +454,18 @@ public async Task PatchMany([FromBody] IEnumerable lstOb } [HttpDelete("{id}")] - public async Task> Delete(int id) + public async Task> Delete(string id) { - var data = await _repository.DeleteAsync(id, _fieldNameService); - var childAssociationsQueries = GetAssociationQueries(parentDatabaseName: _tableName, parentId: id); - var parentAssociationsQueries = GetAssociationQueries(childDatabaseName: _tableName, childId: id); - _repository.InitTableName(AssociationTableName); + var objId = GetId(id); + var data = await _repository.DeleteAsync(objId, _fieldNameService); + var childAssociationsQueries = GetAssociationQueries(parentDatabaseName: _tableName, parentId: objId); + var parentAssociationsQueries = GetAssociationQueries(childDatabaseName: _tableName, childId: objId); + _repository.InitTableName(GetRelationshipDbName()); await _repository.DeleteAsync(childAssociationsQueries); await _repository.DeleteAsync(parentAssociationsQueries); string username = _idService.GetClaim(User, MixClaims.Username); QueueService.PushMemoryQueue(CurrentTenant.Id, MixQueueTopics.MixBackgroundTasks, MixQueueActions.MixDbEvent, - new MixDbEventCommand(username, MixDbCommandQueueActions.Delete, _tableName, new(new JProperty("data", id)))); + new MixDbEventCommand(username, MixDbCommandQueueAction.Delete.ToString(), _tableName, new(new JProperty("data", objId)))); return data > 0 ? Ok() : NotFound(); } @@ -499,7 +499,7 @@ private async Task CreateDataRelationship(string parentName, string parentId, st _repository.InitTableName(relDbName); var relDb = await GetMixDatabase(relDbName); var fieldNameService = new FieldNameService(relDb.NamingConvention); - var obj = await MixDbHelper.ParseDtoToEntityAsync(JObject.FromObject(rel), relDb.Columns, fieldNameService, CurrentTenant.Id, username); + var obj = await MixDbHelper.ParseDtoToEntityAsync(JObject.FromObject(rel), relDb.Type, relDb.Columns, fieldNameService, CurrentTenant.Id, username); await _repository.InsertAsync(obj, relDb); } @@ -557,10 +557,10 @@ private async Task PatchHandler(JObject objDto, CancellationToken cancellationTo obj[propName] = prop.Value; } } - - await _repository.UpdateAsync(id, objDto, _mixDb); + var parsedObj = await MixDbHelper.ParseDtoToEntityAsync(obj, _mixDb.Type, _mixDb.Columns, _fieldNameService, CurrentTenant.Id, username); + await _repository.UpdateAsync(id, parsedObj, _mixDb); QueueService.PushMemoryQueue(CurrentTenant.Id, MixQueueTopics.MixBackgroundTasks, MixQueueActions.MixDbEvent, - new MixDbEventCommand(username, MixDbCommandQueueActions.Patch, _tableName, objDto)); + new MixDbEventCommand(username, MixDbCommandQueueAction.Patch.ToString(), _tableName, objDto)); } catch (Exception ex) { @@ -573,6 +573,7 @@ private async Task> SearchHandler(SearchMixDbReques try { IEnumerable queries = await BuildSearchQueryAsync(request); + var paging = new PagingRequestModel() { PageIndex = request.PageIndex, @@ -581,7 +582,15 @@ private async Task> SearchHandler(SearchMixDbReques SortDirection = request.Direction }; - return await GetResult(queries, paging, request.LoadNestedData); + var result = await GetResult(queries, paging, request.LoadNestedData); + if (request.LoadNestedData) + { + foreach (var item in result.Items) + { + item.Add(await _mixDbDataService.LoadNestedData(_mixDb, _fieldNameService, item.Value(_fieldNameService.Id))); + } + } + return result; } catch (Exception ex) { @@ -593,7 +602,7 @@ private async Task> SearchManyToManyDataHandler(Sea { try { - if (!request.ParentId.HasValue && !request.GuidParentId.HasValue) + if (request.ObjParentId == null) { throw new MixException(MixErrorStatus.Badrequest, "Bad Request"); } @@ -604,16 +613,17 @@ private async Task> SearchManyToManyDataHandler(Sea new QueryField(_fieldNameService.ParentDatabaseName, request.ParentName), new QueryField(_fieldNameService.ChildDatabaseName, _tableName) }; - - if (request.ParentId.HasValue) + var parentDb = await GetMixDatabase(request.ParentName); + var childDb = await GetMixDatabase(_tableName); + if (parentDb.Type == MixDatabaseType.GuidService) { - relQuery.Add(new(_fieldNameService.ParentId, request.ParentId.Value)); + relQuery.Add(new(_fieldNameService.GuidParentId, request.ObjParentId)); } - - if (request.GuidParentId.HasValue) + else { - relQuery.Add(new(_fieldNameService.GuidParentId, request.GuidParentId.Value)); + relQuery.Add(new(_fieldNameService.ParentId, request.ObjParentId)); } + var allowsRels = await _mixDbDataService.ParseListDataAsync(relDbName, await _repository.GetListByAsync(relQuery)); _repository.InitTableName(_tableName); @@ -629,9 +639,11 @@ private async Task> SearchManyToManyDataHandler(Sea } queries.Add( new( - _fieldNameService.Id, - Operation.In, - allowsRels.Select(m => m.Value(_fieldNameService.ChildId)).ToList() + _fieldNameService.Id, + Operation.In, + childDb.Type == MixDatabaseType.GuidService + ? allowsRels.Select(m => m.Value(_fieldNameService.GuidChildId)).ToList() + : allowsRels.Select(m => m.Value(_fieldNameService.ChildId)).ToList() )); var paging = new PagingRequestModel() @@ -643,10 +655,12 @@ private async Task> SearchManyToManyDataHandler(Sea }; var nestedData = await GetResult(queries, paging, request.LoadNestedData); var items = new List(); - + foreach (var item in nestedData.Items) { - var relId = allowsRels.FirstOrDefault(m => m.Value(_fieldNameService.ChildId) == item.Value(_fieldNameService.Id)); + var relId = childDb.Type == MixDatabaseType.GuidService + ? allowsRels.FirstOrDefault(m => m.Value(_fieldNameService.GuidChildId) == item.Value(_fieldNameService.Id)) + : allowsRels.FirstOrDefault(m => m.Value(_fieldNameService.ChildId) == item.Value(_fieldNameService.Id)); if (relId != null) items.Add( new JObject( @@ -654,7 +668,7 @@ private async Task> SearchManyToManyDataHandler(Sea new JProperty("data", item) )); } - + return new PagingResponseModel() { Items = items, @@ -681,12 +695,12 @@ private async Task> GetResult(IEnumerable("id"); + var id = data.Value(_fieldNameService.Id); List nestedQueries = GetAssociationQueries(rel.SourceDatabaseName, rel.DestinateDatabaseName, id); var orderFields = new List { - new(_fieldNameService.Priority, Order.Ascending) + new(paging.SortBy, paging.SortDirection == SortDirection.Asc? Order.Ascending: Order.Descending) }; var associations = await _associationRepository.GetListByAsync(nestedQueries, orderFields: orderFields); @@ -721,18 +735,13 @@ private async Task> GetResult(IEnumerable { Items = items, PagingData = result.PagingData }; } - private async Task> BuildSearchQueryAsync(SearchMixDbRequestDto request) + private Task> BuildSearchQueryAsync(SearchMixDbRequestDto request) { var queries = BuildSearchPredicate(request).ToList(); - if (request.ParentId.HasValue) + if (request.ObjParentId != null) { - await FilterByIntegerId(queries, request); + queries.Add(new QueryField(_fieldNameService.GetParentId(request.ParentName), request.ObjParentId)); } - else if (request.GuidParentId.HasValue) - { - await FilterByGuidId(queries, request); - } - if (request.Queries != null) { foreach (var query in request.Queries) @@ -741,68 +750,7 @@ private async Task> BuildSearchQueryAsync(SearchMixDbRequestDto queries.Add(new(query.FieldName, op, ParseSearchKeyword(query.CompareOperator, query.Value))); } } - return queries; - } - - private async Task FilterByIntegerId(List queries, SearchMixDbRequestDto request) - { - if (request.RelationShip == MixDatabaseRelationshipType.OneToMany) - { - queries.Add(new(_fieldNameService.GetParentId(request.ParentName), request.ParentId)); - } - else if (_mixDb.Type == MixDatabaseType.AdditionalData) - { - queries.Add(new(_fieldNameService.ParentId, request.ParentId)); - } - else - { - _repository.InitTableName(GetRelationshipDbName()); - - var relQuery = new List() { - new QueryField(_fieldNameService.ParentDatabaseName, request.ParentName), - new QueryField(_fieldNameService.ChildDatabaseName, _tableName) - }; - - if (request.ParentId.HasValue) - { - relQuery.Add(new(_fieldNameService.ParentId, request.ParentId.Value)); - } - var allowsIds = JArray.FromObject(await _repository.GetListByAsync(relQuery)) - .Select(m => m.Value(_fieldNameService.ChildId)).ToList(); - queries.Add(new(_fieldNameService.Id, Operation.In, allowsIds)); - _repository.InitTableName(_tableName); - } - } - - private async Task FilterByGuidId(List queries, SearchMixDbRequestDto request) - { - if (_mixDb.Type == MixDatabaseType.GuidAdditionalData) - { - queries.Add(new(_fieldNameService.ParentId, request.GuidParentId)); - } - else - { - _repository.InitTableName(GetRelationshipDbName()); - var relQuery = new List() { - new QueryField(_fieldNameService.ParentDatabaseName, request.ParentName), - new QueryField(_fieldNameService.ChildDatabaseName, _tableName) - }; - if (request.GuidParentId.HasValue) - { - relQuery.Add(new(_fieldNameService.ParentId, request.GuidParentId.Value)); - } - - var allowsIds = await _repository.GetListByAsync(relQuery); - if (request.ParentName == "Role" || request.ParentName == "User") - { - queries.Add(new(_fieldNameService.Id, Operation.In, allowsIds.Select(m => m.ChildId))); - } - else - { - queries.Add(new(_fieldNameService.Id, Operation.In, allowsIds.Select(m => m.GuildChildId))); - } - _repository.InitTableName(_tableName); - } + return Task.FromResult(queries); } private Operation ParseOperator(MixCompareOperator compareOperator) @@ -838,7 +786,7 @@ private Operation ParseOperator(MixCompareOperator compareOperator) private IEnumerable BuildSearchPredicate(SearchMixDbRequestDto req) { - req.OrderBy = ReflectionHelper.GetPropertyValue(_fieldNameService, req.OrderBy).ToString(); + req.OrderBy ??= _fieldNameService.Priority; var operation = ParseSearchOperation(req.SearchMethod); var queries = new List() { @@ -895,24 +843,38 @@ private Operation ParseSearchOperation(MixCompareOperator? searchMethod) #region Private - private List GetAssociationQueries(string parentDatabaseName = null, string childDatabaseName = null, int? parentId = null, int? childId = null) + private List GetAssociationQueries(string parentDatabaseName = null, string childDatabaseName = null, object? parentId = null, object? childId = null) { var queries = new List(); if (!string.IsNullOrEmpty(parentDatabaseName)) { - queries.Add(new QueryField("ParentDatabaseName", parentDatabaseName)); + queries.Add(new QueryField(_fieldNameService.ParentDatabaseName, parentDatabaseName)); } if (!string.IsNullOrEmpty(childDatabaseName)) { - queries.Add(new QueryField("ChildDatabaseName", childDatabaseName)); + queries.Add(new QueryField(_fieldNameService.ChildDatabaseName, childDatabaseName)); } - if (parentId.HasValue) + if (parentId != null) { - queries.Add(new QueryField(_fieldNameService.ParentId, parentId)); + if (parentId.GetType() == typeof(Guid)) + { + queries.Add(new QueryField(_fieldNameService.GuidParentId, parentId)); + } + else + { + queries.Add(new QueryField(_fieldNameService.ParentId, parentId)); + } } - if (childId.HasValue) + if (childId != null) { - queries.Add(new QueryField(_fieldNameService.ChildId, childId)); + if (childId.GetType() == typeof(Guid)) + { + queries.Add(new QueryField(_fieldNameService.GuidChildId, childId)); + } + else + { + queries.Add(new QueryField(_fieldNameService.ChildId, childId)); + } } return queries; } @@ -930,7 +892,24 @@ private async Task GetMixDatabase(string tableName = } ); } - + private object GetId(string id) + { + try + { + if (_mixDb.Type == MixDatabaseType.GuidService) + { + return Guid.Parse(id); + } + else + { + return int.Parse(id); + } + } + catch (Exception ex) + { + throw new MixException(MixErrorStatus.Badrequest, ex); + } + } #endregion } } \ No newline at end of file diff --git a/src/modules/mix.portal/Controllers/MixDomainController.cs b/src/modules/mix.portal/Controllers/MixDomainController.cs index 882012500..96855c83d 100644 --- a/src/modules/mix.portal/Controllers/MixDomainController.cs +++ b/src/modules/mix.portal/Controllers/MixDomainController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; @@ -18,8 +17,8 @@ public MixDomainController( MixCacheService cacheService, TranslatorService translator, MixIdentityService mixIdentityService, UnitOfWorkInfo uow, IMemoryQueueService queueService, IPortalHubClientService portalHub, - IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + IMixTenantService mixTenantService) + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { diff --git a/src/modules/mix.portal/Controllers/MixLanguageController.cs b/src/modules/mix.portal/Controllers/MixLanguageController.cs index ee86c5a9e..bbfa9df70 100644 --- a/src/modules/mix.portal/Controllers/MixLanguageController.cs +++ b/src/modules/mix.portal/Controllers/MixLanguageController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; @@ -14,8 +13,8 @@ public class MixLanguageController { public MixLanguageController(IHttpContextAccessor httpContextAccessor, IConfiguration configuration, MixCacheService cacheService, TranslatorService translator, MixIdentityService mixIdentityService, UnitOfWorkInfo uow, IMemoryQueueService queueService, IPortalHubClientService portalHub, - IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + IMixTenantService mixTenantService) + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { diff --git a/src/modules/mix.portal/Controllers/MixModuleContentController.cs b/src/modules/mix.portal/Controllers/MixModuleContentController.cs index 9f513ddae..58fbdfce4 100644 --- a/src/modules/mix.portal/Controllers/MixModuleContentController.cs +++ b/src/modules/mix.portal/Controllers/MixModuleContentController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; diff --git a/src/modules/mix.portal/Controllers/MixModuleController.cs b/src/modules/mix.portal/Controllers/MixModuleController.cs index 7458051f9..ddd1b52f7 100644 --- a/src/modules/mix.portal/Controllers/MixModuleController.cs +++ b/src/modules/mix.portal/Controllers/MixModuleController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; diff --git a/src/modules/mix.portal/Controllers/MixModuleDataController.cs b/src/modules/mix.portal/Controllers/MixModuleDataController.cs index eb18b3a04..faf261d03 100644 --- a/src/modules/mix.portal/Controllers/MixModuleDataController.cs +++ b/src/modules/mix.portal/Controllers/MixModuleDataController.cs @@ -22,7 +22,7 @@ public MixModuleDataController( IMixDbService mixDbService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cmsUow, queueService, portalHub, mixTenantService) { diff --git a/src/modules/mix.portal/Controllers/MixModulePostPortalController.cs b/src/modules/mix.portal/Controllers/MixModulePostPortalController.cs index ef1a05614..cdaa75c68 100644 --- a/src/modules/mix.portal/Controllers/MixModulePostPortalController.cs +++ b/src/modules/mix.portal/Controllers/MixModulePostPortalController.cs @@ -22,7 +22,7 @@ public MixModulePostController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cmsUow, queueService, portalHub, mixTenantService) { _cmsUow = cmsUow; diff --git a/src/modules/mix.portal/Controllers/MixPageContentController.cs b/src/modules/mix.portal/Controllers/MixPageContentController.cs index e1c559100..9cd69daa3 100644 --- a/src/modules/mix.portal/Controllers/MixPageContentController.cs +++ b/src/modules/mix.portal/Controllers/MixPageContentController.cs @@ -23,8 +23,8 @@ public MixPageContentController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(MixContentType.Page, identityService, userManager, - httpContextAccessor, configuration, cacheService, translator, + : base(MixContentType.Page, identityService, userManager, + httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cmsUow, queueService, portalHub, mixTenantService) { diff --git a/src/modules/mix.portal/Controllers/MixPageController.cs b/src/modules/mix.portal/Controllers/MixPageController.cs index d76077877..64fe3837e 100644 --- a/src/modules/mix.portal/Controllers/MixPageController.cs +++ b/src/modules/mix.portal/Controllers/MixPageController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; diff --git a/src/modules/mix.portal/Controllers/MixPageModuleController.cs b/src/modules/mix.portal/Controllers/MixPageModuleController.cs index 63486514d..9e0558853 100644 --- a/src/modules/mix.portal/Controllers/MixPageModuleController.cs +++ b/src/modules/mix.portal/Controllers/MixPageModuleController.cs @@ -22,7 +22,7 @@ public MixPageModuleController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cmsUow, queueService, portalHub, mixTenantService) { _cmsUow = cmsUow; diff --git a/src/modules/mix.portal/Controllers/MixPagePostPortalController.cs b/src/modules/mix.portal/Controllers/MixPagePostPortalController.cs index d70e07996..cfe0ac207 100644 --- a/src/modules/mix.portal/Controllers/MixPagePostPortalController.cs +++ b/src/modules/mix.portal/Controllers/MixPagePostPortalController.cs @@ -14,8 +14,8 @@ public class MixPagePostController public MixPagePostController(IHttpContextAccessor httpContextAccessor, IConfiguration configuration, MixCacheService cacheService, TranslatorService translator, MixIdentityService mixIdentityService, UnitOfWorkInfo cmsUow, IMemoryQueueService queueService, IPortalHubClientService portalHub, - IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + IMixTenantService mixTenantService) + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cmsUow, queueService, portalHub, mixTenantService) { _cmsUow = cmsUow; diff --git a/src/modules/mix.portal/Controllers/MixPostContentController.cs b/src/modules/mix.portal/Controllers/MixPostContentController.cs index 95084ced0..80aa10f43 100644 --- a/src/modules/mix.portal/Controllers/MixPostContentController.cs +++ b/src/modules/mix.portal/Controllers/MixPostContentController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.Portal.Domain.Services; diff --git a/src/modules/mix.portal/Controllers/MixPostController.cs b/src/modules/mix.portal/Controllers/MixPostController.cs index 33cab372f..86208ad2d 100644 --- a/src/modules/mix.portal/Controllers/MixPostController.cs +++ b/src/modules/mix.portal/Controllers/MixPostController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; diff --git a/src/modules/mix.portal/Controllers/MixPostPostController.cs b/src/modules/mix.portal/Controllers/MixPostPostController.cs index 0bca50bac..e2d30e9fb 100644 --- a/src/modules/mix.portal/Controllers/MixPostPostController.cs +++ b/src/modules/mix.portal/Controllers/MixPostPostController.cs @@ -14,8 +14,8 @@ public class MixPostPostController public MixPostPostController(IHttpContextAccessor httpContextAccessor, IConfiguration configuration, MixCacheService cacheService, TranslatorService translator, MixIdentityService mixIdentityService, UnitOfWorkInfo cmsUow, IMemoryQueueService queueService, IPortalHubClientService portalHub, - IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + IMixTenantService mixTenantService) + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cmsUow, queueService, portalHub, mixTenantService) { _cmsUow = cmsUow; diff --git a/src/modules/mix.portal/Controllers/MixTemplateController.cs b/src/modules/mix.portal/Controllers/MixTemplateController.cs index 31bf0d139..b599bb760 100644 --- a/src/modules/mix.portal/Controllers/MixTemplateController.cs +++ b/src/modules/mix.portal/Controllers/MixTemplateController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; @@ -22,7 +21,7 @@ public MixTemplateController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cmsUow, queueService, portalHub, mixTenantService) { } diff --git a/src/modules/mix.portal/Controllers/MixTenantController.cs b/src/modules/mix.portal/Controllers/MixTenantController.cs index 0925d37e2..e95553363 100644 --- a/src/modules/mix.portal/Controllers/MixTenantController.cs +++ b/src/modules/mix.portal/Controllers/MixTenantController.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -using Mix.Auth.Constants; using Mix.Database.Entities.Account; using Mix.Heart.Helpers; using Mix.Identity.Enums; diff --git a/src/modules/mix.portal/Controllers/MixThemeController.cs b/src/modules/mix.portal/Controllers/MixThemeController.cs index eb99a7db3..3b3639e82 100644 --- a/src/modules/mix.portal/Controllers/MixThemeController.cs +++ b/src/modules/mix.portal/Controllers/MixThemeController.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; -using Mix.Auth.Constants; using Mix.Heart.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; @@ -41,7 +40,7 @@ public MixThemeController( MixConfigurationService configService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cmsUow, queueService, portalHub, mixTenantService) { diff --git a/src/modules/mix.portal/Controllers/MixUrlAliasController.cs b/src/modules/mix.portal/Controllers/MixUrlAliasController.cs index b02ed0f2b..ec9c1c9ec 100644 --- a/src/modules/mix.portal/Controllers/MixUrlAliasController.cs +++ b/src/modules/mix.portal/Controllers/MixUrlAliasController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; diff --git a/src/modules/mix.portal/Controllers/MixViewTemplateController.cs b/src/modules/mix.portal/Controllers/MixViewTemplateController.cs index 578dcf067..d3c5c4e86 100644 --- a/src/modules/mix.portal/Controllers/MixViewTemplateController.cs +++ b/src/modules/mix.portal/Controllers/MixViewTemplateController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.SignalR.Interfaces; diff --git a/src/modules/mix.portal/Domain/Services/CloneCultureService.cs b/src/modules/mix.portal/Domain/Services/CloneCultureService.cs index 04b0adf00..12f8ecc4a 100644 --- a/src/modules/mix.portal/Domain/Services/CloneCultureService.cs +++ b/src/modules/mix.portal/Domain/Services/CloneCultureService.cs @@ -2,7 +2,6 @@ using Mix.Database.Entities.Base; using Mix.Lib.Interfaces; using Mix.Portal.Domain.Interfaces; -using System.Linq.Expressions; namespace Mix.Portal.Domain.Services { diff --git a/src/modules/mix.portal/Domain/Services/MixApplicationService.cs b/src/modules/mix.portal/Domain/Services/MixApplicationService.cs index 33752eb7f..b789a362f 100644 --- a/src/modules/mix.portal/Domain/Services/MixApplicationService.cs +++ b/src/modules/mix.portal/Domain/Services/MixApplicationService.cs @@ -1,20 +1,13 @@ -using DocumentFormat.OpenXml.Wordprocessing; -using Humanizer; -using Microsoft.AspNetCore.SignalR; -using Mix.Auth.Constants; +using Microsoft.AspNetCore.SignalR; using Mix.Heart.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.Portal.Domain.Interfaces; using Mix.Shared.Helpers; -using Mix.Shared.Models.Configurations; using Mix.Shared.Services; using Mix.SignalR.Constants; using Mix.SignalR.Hubs; -using System.Configuration; -using System.IO.Packaging; using System.Text.RegularExpressions; -using static NuGet.Packaging.PackagingConstants; namespace Mix.Portal.Domain.Services { @@ -88,10 +81,10 @@ public async Task UpdatePackage(MixApplicationViewModel string deployUrl = $"{MixFolders.StaticFiles}/{MixFolders.MixApplications}/{name}"; string package = await DownloadPackage(name, app.PackageFilePath, deployUrl); MixFileHelper.UnZipFile(package, deployUrl); - + await ImportSchema($"{deployUrl}/schema", cancellationToken); await SaveTemplate(app.TemplateId, name, deployUrl, app.BaseHref); - + packages.Add(package); app.AppSettings["activePackage"] = package; app.AppSettings["packages"] = packages; @@ -126,10 +119,10 @@ public async Task RestorePackage(RestoreMixApplicationP MixFileHelper.UnZipFile(dto.PackageFilePath, deployUrl); _ = AlertAsync(_hubContext.Clients.Group("Theme"), "Status", 200, $"Extract Package {dto.PackageFilePath} Successfully"); - + await ImportSchema($"{deployUrl}/schema", cancellationToken); await SaveTemplate(app.TemplateId, name, deployUrl, app.BaseHref); - + app.AppSettings["activePackage"] = dto.PackageFilePath; await app.SaveAsync(cancellationToken); @@ -313,7 +306,7 @@ private async Task DownloadPackage(string name, string packageUrl, strin } } - + #region Helpers public async Task AlertAsync(IClientProxy clients, string action, int status, T message) diff --git a/src/modules/mix.portal/Domain/StartupService.cs b/src/modules/mix.portal/Domain/StartupService.cs index 8f4dddbce..92741ee7a 100644 --- a/src/modules/mix.portal/Domain/StartupService.cs +++ b/src/modules/mix.portal/Domain/StartupService.cs @@ -1,5 +1,4 @@ -using Mix.Lib.Interfaces; -using Mix.Portal.Domain.Interfaces; +using Mix.Portal.Domain.Interfaces; using Mix.Portal.Domain.Services; using Mix.Shared.Interfaces; diff --git a/src/modules/mix.portal/Domain/ViewModels/MixPostContentViewModel.cs b/src/modules/mix.portal/Domain/ViewModels/MixPostContentViewModel.cs index 4f28b11e5..d0cc92740 100644 --- a/src/modules/mix.portal/Domain/ViewModels/MixPostContentViewModel.cs +++ b/src/modules/mix.portal/Domain/ViewModels/MixPostContentViewModel.cs @@ -1,9 +1,5 @@ -using Microsoft.AspNetCore.Routing; -using Mix.Heart.Helpers; -using Mix.Lib.Services; +using Mix.Heart.Helpers; using Mix.RepoDb.Repositories; -using Mix.Service.Services; -using Mix.Services.Databases.Lib.Interfaces; using RepoDb; using RepoDb.Enumerations; diff --git a/src/modules/mix.portal/Program.cs b/src/modules/mix.portal/Program.cs index 73350b7cd..bcff7f263 100644 --- a/src/modules/mix.portal/Program.cs +++ b/src/modules/mix.portal/Program.cs @@ -1,9 +1,7 @@ using Mix.Database.Entities.Account; -using System.Configuration; -using System.Reflection; -using Mix.Log.Lib; -using Microsoft.Azure.Amqp.Framing; using Mix.Lib.Middlewares; +using Mix.Log.Lib; +using System.Reflection; var builder = MixCmsHelper.CreateWebApplicationBuilder(args); if (builder.Environment.IsDevelopment()) diff --git a/src/modules/mix.portal/Startup.cs b/src/modules/mix.portal/Startup.cs index 2d3a0239c..9c4881e00 100644 --- a/src/modules/mix.portal/Startup.cs +++ b/src/modules/mix.portal/Startup.cs @@ -23,6 +23,7 @@ public void ConfigureServices(IServiceCollection services) services.AddMixLog(Configuration); // Must app Auth config after Add mixservice to init App config services.AddMixAuthorize(Configuration); + services.AddScoped(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/src/modules/mix.portal/mix.portal.csproj b/src/modules/mix.portal/mix.portal.csproj index b6f19bce2..c483627b9 100644 --- a/src/modules/mix.portal/mix.portal.csproj +++ b/src/modules/mix.portal/mix.portal.csproj @@ -51,7 +51,7 @@ - + @@ -63,7 +63,7 @@ - + diff --git a/src/modules/mix.scheduler/Domain/Jobs/KeepPoolAliveJob.cs b/src/modules/mix.scheduler/Domain/Jobs/KeepPoolAliveJob.cs index ad667e0dd..9e255297f 100644 --- a/src/modules/mix.scheduler/Domain/Jobs/KeepPoolAliveJob.cs +++ b/src/modules/mix.scheduler/Domain/Jobs/KeepPoolAliveJob.cs @@ -1,16 +1,13 @@ -using Mix.Queue.Interfaces; -using Mix.Shared.Services; -using Quartz; -using System; -using System.Threading.Tasks; +using Mix.Mq.Lib.Models; using Mix.Quartz.Enums; using Mix.Quartz.Jobs; using Mix.Quartz.Models; -using NuGet.Packaging.Signing; -using Mix.Mq.Lib.Models; +using Mix.Queue.Interfaces; +using Mix.Shared.Services; using Newtonsoft.Json.Linq; -using System.Collections.Generic; -using System.Collections.Immutable; +using Quartz; +using System; +using System.Threading.Tasks; namespace Mix.Scheduler.Domain.Jobs { diff --git a/src/modules/mix.scheduler/Domain/Jobs/SendPortalMessageJob.cs b/src/modules/mix.scheduler/Domain/Jobs/SendPortalMessageJob.cs index a315adb33..5a1fc0ab2 100644 --- a/src/modules/mix.scheduler/Domain/Jobs/SendPortalMessageJob.cs +++ b/src/modules/mix.scheduler/Domain/Jobs/SendPortalMessageJob.cs @@ -1,12 +1,12 @@ -using Mix.Queue.Interfaces; +using Mix.Mq.Lib.Models; +using Mix.Quartz.Jobs; +using Mix.Queue.Interfaces; +using Mix.SignalR.Interfaces; using Mix.SignalR.Models; using Newtonsoft.Json.Linq; using Quartz; using System; using System.Threading.Tasks; -using Mix.Quartz.Jobs; -using Mix.SignalR.Interfaces; -using Mix.Mq.Lib.Models; namespace Mix.Scheduler.Domain.Jobs { diff --git a/src/modules/mix.scheduler/Domain/StartupService.cs b/src/modules/mix.scheduler/Domain/StartupService.cs index 488868f19..468ed469e 100644 --- a/src/modules/mix.scheduler/Domain/StartupService.cs +++ b/src/modules/mix.scheduler/Domain/StartupService.cs @@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Mix.Lib.Interfaces; using Mix.Shared.Interfaces; namespace Mix.Scheduler.Domain diff --git a/src/modules/mix.storage/Controllers/FileSystemController.cs b/src/modules/mix.storage/Controllers/FileSystemController.cs index cefc3f4fb..326991289 100644 --- a/src/modules/mix.storage/Controllers/FileSystemController.cs +++ b/src/modules/mix.storage/Controllers/FileSystemController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Auth.Constants; using Mix.Heart.Constants; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; @@ -21,7 +20,7 @@ public FileSystemController( IMemoryQueueService queueService, MixStorageService storageService, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, queueService, mixTenantService) { } diff --git a/src/modules/mix.storage/Controllers/StorageController.cs b/src/modules/mix.storage/Controllers/StorageController.cs index 2c1b5358e..c96564c8d 100644 --- a/src/modules/mix.storage/Controllers/StorageController.cs +++ b/src/modules/mix.storage/Controllers/StorageController.cs @@ -14,8 +14,8 @@ public class StorageController : MixRestfulApiControllerBase uow, IMemoryQueueService queueService, IPortalHubClientService portalHub, - IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + IMixTenantService mixTenantService) + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { _storageService = storageService; diff --git a/src/modules/mix.storage/Domain/StartupService.cs b/src/modules/mix.storage/Domain/StartupService.cs index 7efc09874..e1f01114b 100644 --- a/src/modules/mix.storage/Domain/StartupService.cs +++ b/src/modules/mix.storage/Domain/StartupService.cs @@ -1,5 +1,4 @@ -using Mix.Lib.Interfaces; -using Mix.Shared.Interfaces; +using Mix.Shared.Interfaces; using Mix.Storage.Lib.Extensions; namespace Mix.Storage.Domain diff --git a/src/modules/mix.tenancy/Controllers/InitController.cs b/src/modules/mix.tenancy/Controllers/InitController.cs index 673860b36..6bf7ad2c6 100644 --- a/src/modules/mix.tenancy/Controllers/InitController.cs +++ b/src/modules/mix.tenancy/Controllers/InitController.cs @@ -1,21 +1,21 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; -using Mix.Shared.Extensions; +using Mix.Auth.Constants; +using Mix.Auth.Models; +using Mix.Database.Services; +using Mix.Lib.Interfaces; using Mix.Lib.Services; using Mix.Lib.ViewModels; +using Mix.Mq.Lib.Models; +using Mix.Quartz.Interfaces; using Mix.Queue.Interfaces; +using Mix.Shared.Extensions; using Mix.SignalR.Constants; using Mix.SignalR.Hubs; using Mix.Tenancy.Domain.Dtos; +using Mix.Tenancy.Domain.Interfaces; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using Mix.Lib.Interfaces; -using Mix.Tenancy.Domain.Interfaces; -using Mix.Quartz.Interfaces; -using Mix.Database.Services; -using Mix.Auth.Models; -using Mix.Auth.Constants; -using Mix.Mq.Lib.Models; namespace Mix.Tenancy.Controllers { diff --git a/src/modules/mix.tenancy/Domain/ViewModels/Init/InitTenantViewModel.cs b/src/modules/mix.tenancy/Domain/ViewModels/Init/InitTenantViewModel.cs index 641d06e3c..311dba25c 100644 --- a/src/modules/mix.tenancy/Domain/ViewModels/Init/InitTenantViewModel.cs +++ b/src/modules/mix.tenancy/Domain/ViewModels/Init/InitTenantViewModel.cs @@ -1,4 +1,3 @@ -using Mix.Lib.Services; using Mix.Tenancy.Domain.Dtos; namespace Mix.Tenancy.Domain.ViewModels.Init diff --git a/src/platform/core/mix-heart b/src/platform/core/mix-heart index b1f765bb0..bf81173af 160000 --- a/src/platform/core/mix-heart +++ b/src/platform/core/mix-heart @@ -1 +1 @@ -Subproject commit b1f765bb0df68ae20ecdf0066a3d7203fbe171a8 +Subproject commit bf81173af807c6d96e96829ffb8088f007d4fe64 diff --git a/src/platform/core/mix.mixdb.event/Services/MixDbEventService.cs b/src/platform/core/mix.mixdb.event/Services/MixDbEventService.cs index c0a44dbab..18f7db2b8 100644 --- a/src/platform/core/mix.mixdb.event/Services/MixDbEventService.cs +++ b/src/platform/core/mix.mixdb.event/Services/MixDbEventService.cs @@ -1,7 +1,4 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.Azure.Amqp.Framing; -using Microsoft.CodeAnalysis.Elfie.Serialization; -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Mix.Constant.Constants; using Mix.Database.Constants; @@ -9,11 +6,8 @@ using Mix.Database.Services; using Mix.Heart.Extensions; using Mix.Heart.Services; -using Mix.Heart.UnitOfWork; using Mix.Mixdb.Event.ViewModels; -using Mix.Queue.Models; -using Mix.RepoDb.Services; using Mix.Service.Commands; using Mix.Service.Services; using Mix.Shared.Models; @@ -23,12 +17,6 @@ using Mix.SignalR.Interfaces; using Mix.SignalR.Models; using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; namespace Mix.Mixdb.Event.Services { @@ -75,7 +63,7 @@ public void LoadEvents(IServiceScope? serviceScope = null) } catch (Exception ex) { - + MixLogService.LogExceptionAsync(ex); } } } @@ -85,7 +73,11 @@ public async Task HandleMessage(MixDbEventCommand model) using (var serviceScope = ServicesProvider.CreateScope()) { var _cacheService = serviceScope.ServiceProvider.GetRequiredService(); - await _cacheService.RemoveCacheAsync(model.Data.Value("Id"), $"{MixFolders.MixDbCacheFolder}/{model.MixDbName}"); + if (model.Data != null) + { + var id = model.Data.GetValue("id", StringComparison.OrdinalIgnoreCase)?.Value(); + await _cacheService.RemoveCacheAsync(id, $"{MixFolders.MixDbCacheFolder}/{model.MixDbName}"); + } if (model.MixDbName == MixDatabaseNames.SYSTEM_PERMISSION || model.MixDbName == MixDatabaseNames.SYSTEM_PERMISSION_ENDPOINT) { await _mixPermissionService.Reload(); diff --git a/src/platform/core/mix.mixdb.event/ViewModels/MixDbEventSubscriberViewModel.cs b/src/platform/core/mix.mixdb.event/ViewModels/MixDbEventSubscriberViewModel.cs index 278385360..1fdb83e8f 100644 --- a/src/platform/core/mix.mixdb.event/ViewModels/MixDbEventSubscriberViewModel.cs +++ b/src/platform/core/mix.mixdb.event/ViewModels/MixDbEventSubscriberViewModel.cs @@ -3,11 +3,6 @@ using Mix.Heart.ViewModel; using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Mixdb.Event.ViewModels { diff --git a/src/platform/mix.auth/Common/ExtensionMethods.cs b/src/platform/mix.auth/Common/ExtensionMethods.cs index 837f59ab4..5612f19f9 100644 --- a/src/platform/mix.auth/Common/ExtensionMethods.cs +++ b/src/platform/mix.auth/Common/ExtensionMethods.cs @@ -7,8 +7,6 @@ Everyone is permitted to copy and distribute verbatim copies */ using System.ComponentModel; -using System; -using System.Linq; namespace Mix.Auth.Common { diff --git a/src/platform/mix.auth/Common/OAuth2ServerHelpers.cs b/src/platform/mix.auth/Common/OAuth2ServerHelpers.cs index d2b6ec0f4..679fd3d05 100644 --- a/src/platform/mix.auth/Common/OAuth2ServerHelpers.cs +++ b/src/platform/mix.auth/Common/OAuth2ServerHelpers.cs @@ -6,8 +6,6 @@ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. */ -using System.Collections.Generic; - namespace Mix.Auth.Common { public class OAuth2ServerHelpers diff --git a/src/platform/mix.auth/Dtos/RenewTokenDto.cs b/src/platform/mix.auth/Dtos/RenewTokenDto.cs index 58250d2db..34ae439ab 100644 --- a/src/platform/mix.auth/Dtos/RenewTokenDto.cs +++ b/src/platform/mix.auth/Dtos/RenewTokenDto.cs @@ -1,6 +1,4 @@ -using System; - -namespace Mix.Auth.Dtos +namespace Mix.Auth.Dtos { public class RenewTokenDto { diff --git a/src/platform/mix.auth/Helpers/TokenHelpers.cs b/src/platform/mix.auth/Helpers/TokenHelpers.cs index ea518c1f8..21be2f653 100644 --- a/src/platform/mix.auth/Helpers/TokenHelpers.cs +++ b/src/platform/mix.auth/Helpers/TokenHelpers.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Auth.Helpers +namespace Mix.Auth.Helpers { public static class TokenHelpers { diff --git a/src/platform/mix.auth/Models/ExternalLoginResultModel.cs b/src/platform/mix.auth/Models/ExternalLoginResultModel.cs index a9fc2cc7c..b0b5cfac8 100644 --- a/src/platform/mix.auth/Models/ExternalLoginResultModel.cs +++ b/src/platform/mix.auth/Models/ExternalLoginResultModel.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Auth.Models +namespace Mix.Auth.Models { public class ExternalLoginResultModel { diff --git a/src/platform/mix.auth/Models/LoginRequestModel.cs b/src/platform/mix.auth/Models/LoginRequestModel.cs index b2106b9cb..c8896c647 100644 --- a/src/platform/mix.auth/Models/LoginRequestModel.cs +++ b/src/platform/mix.auth/Models/LoginRequestModel.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.ComponentModel.DataAnnotations; namespace Mix.Auth.Models { diff --git a/src/platform/mix.auth/Models/OAuthCode.cs b/src/platform/mix.auth/Models/OAuthCode.cs index 6ac4afedc..3f47c69db 100644 --- a/src/platform/mix.auth/Models/OAuthCode.cs +++ b/src/platform/mix.auth/Models/OAuthCode.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Security.Claims; +using System.Security.Claims; namespace Mix.Auth.Models { diff --git a/src/platform/mix.auth/Models/OAuthRequests/OAuthTokenRequest.cs b/src/platform/mix.auth/Models/OAuthRequests/OAuthTokenRequest.cs index 8467af5f3..01375fc9f 100644 --- a/src/platform/mix.auth/Models/OAuthRequests/OAuthTokenRequest.cs +++ b/src/platform/mix.auth/Models/OAuthRequests/OAuthTokenRequest.cs @@ -6,9 +6,6 @@ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. */ -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; - namespace Mix.Auth.Models.OAuthRequests { public class OAuthTokenRequest diff --git a/src/platform/mix.auth/Models/OAuthRequests/OpenIdConnectLoginRequest.cs b/src/platform/mix.auth/Models/OAuthRequests/OpenIdConnectLoginRequest.cs index f578c3a61..f0184eefe 100644 --- a/src/platform/mix.auth/Models/OAuthRequests/OpenIdConnectLoginRequest.cs +++ b/src/platform/mix.auth/Models/OAuthRequests/OpenIdConnectLoginRequest.cs @@ -6,8 +6,6 @@ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. */ -using System.Collections.Generic; - namespace Mix.Auth.Models.OAuthRequests { public class OpenIdConnectLoginRequest diff --git a/src/platform/mix.auth/Models/OAuthResponses/AuthorizeResponse.cs b/src/platform/mix.auth/Models/OAuthResponses/AuthorizeResponse.cs index b50506eb3..96d23ea5c 100644 --- a/src/platform/mix.auth/Models/OAuthResponses/AuthorizeResponse.cs +++ b/src/platform/mix.auth/Models/OAuthResponses/AuthorizeResponse.cs @@ -6,8 +6,6 @@ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. */ -using System.Collections.Generic; - namespace Mix.Auth.Models.OAuthResponses { public class AuthorizeResponse diff --git a/src/platform/mix.auth/Models/OAuthResponses/DiscoveryResponse.cs b/src/platform/mix.auth/Models/OAuthResponses/DiscoveryResponse.cs index 99bc9ed15..2184b18f1 100644 --- a/src/platform/mix.auth/Models/OAuthResponses/DiscoveryResponse.cs +++ b/src/platform/mix.auth/Models/OAuthResponses/DiscoveryResponse.cs @@ -6,8 +6,6 @@ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. */ -using System.Collections.Generic; - namespace Mix.Auth.Models.OAuthResponses { public class DiscoveryResponse diff --git a/src/platform/mix.auth/Models/OAuthResponses/OAuthTokenResponse.cs b/src/platform/mix.auth/Models/OAuthResponses/OAuthTokenResponse.cs new file mode 100644 index 000000000..b818e8e67 --- /dev/null +++ b/src/platform/mix.auth/Models/OAuthResponses/OAuthTokenResponse.cs @@ -0,0 +1,38 @@ +using Mix.Auth.Common; +using Mix.Auth.Enums; + +namespace Mix.Auth.Models.OAuthResponses +{ + public class OAuthTokenResponse + { + /// + /// Oauth 2 + /// + public string access_token { get; set; } + + /// + /// OpenId Connect + /// + public string? id_token { get; set; } + public DateTime? expired_at { get; set; } + + /// + /// By default is Bearer + /// + + public string? token_type { get; set; } = TokenTypeEnum.Bearer.GetEnumDescription(); + + /// + /// Authorization Code. This is always returned when using the Hybrid Flow. + /// + public string code { get; set; } + + /// + /// For Error Details if any + /// + public string? Error { get; set; } = string.Empty; + public string ErrorUri { get; set; } + public string? ErrorDescription { get; set; } + public bool HasError => !string.IsNullOrEmpty(Error); + } +} diff --git a/src/platform/mix.auth/Models/OAuthResponses/TokenResult.cs b/src/platform/mix.auth/Models/OAuthResponses/TokenResult.cs index f2a537444..f8f283be2 100644 --- a/src/platform/mix.auth/Models/OAuthResponses/TokenResult.cs +++ b/src/platform/mix.auth/Models/OAuthResponses/TokenResult.cs @@ -6,8 +6,6 @@ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. */ -using System; - namespace Mix.Auth.Models.OAuthResponses { public class TokenResult diff --git a/src/platform/mix.auth/Models/RegisterExternalBindingModel.cs b/src/platform/mix.auth/Models/RegisterExternalBindingModel.cs index 1d0988f14..e6c2bceaa 100644 --- a/src/platform/mix.auth/Models/RegisterExternalBindingModel.cs +++ b/src/platform/mix.auth/Models/RegisterExternalBindingModel.cs @@ -1,9 +1,4 @@ using Mix.Auth.Enums; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Auth.Models { diff --git a/src/platform/mix.auth/Models/ResetPasswordRequestModel.cs b/src/platform/mix.auth/Models/ResetPasswordRequestModel.cs index 75aa31d17..428664243 100644 --- a/src/platform/mix.auth/Models/ResetPasswordRequestModel.cs +++ b/src/platform/mix.auth/Models/ResetPasswordRequestModel.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.ComponentModel.DataAnnotations; namespace Mix.Auth.Models { diff --git a/src/platform/mix.communicator/mix.communicator.csproj b/src/platform/mix.communicator/mix.communicator.csproj index 8e34a4e2c..8e93f75a5 100644 --- a/src/platform/mix.communicator/mix.communicator.csproj +++ b/src/platform/mix.communicator/mix.communicator.csproj @@ -13,8 +13,8 @@ - - + + diff --git a/src/platform/mix.constant/Constants/MixConstants.cs b/src/platform/mix.constant/Constants/MixConstants.cs index e40928ed7..7b6fff560 100644 --- a/src/platform/mix.constant/Constants/MixConstants.cs +++ b/src/platform/mix.constant/Constants/MixConstants.cs @@ -3,6 +3,7 @@ public class MixConstants { public const string CONST_AUDIT_LOG_CONNECTION = "MixAuditLogConnection"; + public const string CONST_QUEUE_LOG_CONNECTION = "MixQueueLogConnection"; public const string CONST_CMS_CONNECTION = "MixCmsConnection"; public const string CONST_QUARTZ_CONNECTION = "MixQuartzConnection"; public const string CONST_ACCOUNT_CONNECTION = "MixAccountConnection"; diff --git a/src/platform/mix.constant/Enums/HttpRequestMethod.cs b/src/platform/mix.constant/Enums/HttpRequestMethod.cs new file mode 100644 index 000000000..6d8ca4237 --- /dev/null +++ b/src/platform/mix.constant/Enums/HttpRequestMethod.cs @@ -0,0 +1,11 @@ +namespace Mix.Constant.Enums +{ + public enum HttpRequestMethod + { + GET, + POST, + PUT, + PATCH, + DELETE + } +} diff --git a/src/platform/mix.constant/Enums/MixDataType.cs b/src/platform/mix.constant/Enums/MixDataType.cs index c60225b0c..797a8e95b 100644 --- a/src/platform/mix.constant/Enums/MixDataType.cs +++ b/src/platform/mix.constant/Enums/MixDataType.cs @@ -26,13 +26,13 @@ public enum MixDataType Upload, Color, - + Reference, Custom, Icon, VideoYoutube, TuiEditor, - + QRCode, BarCode, Tag, diff --git a/src/platform/mix.constant/Enums/MixDatabaseType.cs b/src/platform/mix.constant/Enums/MixDatabaseType.cs index fcf331703..29d29419b 100644 --- a/src/platform/mix.constant/Enums/MixDatabaseType.cs +++ b/src/platform/mix.constant/Enums/MixDatabaseType.cs @@ -4,6 +4,7 @@ public enum MixDatabaseType { System, Service, + GuidService, AdditionalData, GuidAdditionalData, Association diff --git a/src/platform/mix.constant/Enums/MixDbCommandQueueAction.cs b/src/platform/mix.constant/Enums/MixDbCommandQueueAction.cs new file mode 100644 index 000000000..da070d77d --- /dev/null +++ b/src/platform/mix.constant/Enums/MixDbCommandQueueAction.cs @@ -0,0 +1,11 @@ +namespace Mix.Constant.Enums +{ + public enum MixDbCommandQueueAction + { + Create, + Update, + Patch, + Delete, + Read + } +} diff --git a/src/platform/mix.constant/Enums/MixQueueMessageLogState.cs b/src/platform/mix.constant/Enums/MixQueueMessageLogState.cs index a8dc2dced..1d626e1ad 100644 --- a/src/platform/mix.constant/Enums/MixQueueMessageLogState.cs +++ b/src/platform/mix.constant/Enums/MixQueueMessageLogState.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Constant.Enums +namespace Mix.Constant.Enums { public enum MixQueueMessageLogState { diff --git a/src/platform/mix.constant/mix.constant.csproj b/src/platform/mix.constant/mix.constant.csproj index 76c1e0ede..1da3696dc 100644 --- a/src/platform/mix.constant/mix.constant.csproj +++ b/src/platform/mix.constant/mix.constant.csproj @@ -7,10 +7,6 @@ Mix.Constant - - - - diff --git a/src/platform/mix.database/Base/BaseDbContext.cs b/src/platform/mix.database/Base/BaseDbContext.cs index 4d44f474e..53645f63e 100644 --- a/src/platform/mix.database/Base/BaseDbContext.cs +++ b/src/platform/mix.database/Base/BaseDbContext.cs @@ -14,7 +14,7 @@ public abstract class BaseDbContext : DbContext public BaseDbContext() { - + } public BaseDbContext(DatabaseService databaseService, string connectionStringName) { diff --git a/src/platform/mix.database/Entities/Account/EntityConfigurations/OAuthClientConfiguration.cs b/src/platform/mix.database/Entities/Account/EntityConfigurations/OAuthClientConfiguration.cs index aa9157cec..f4615e1d1 100644 --- a/src/platform/mix.database/Entities/Account/EntityConfigurations/OAuthClientConfiguration.cs +++ b/src/platform/mix.database/Entities/Account/EntityConfigurations/OAuthClientConfiguration.cs @@ -20,7 +20,7 @@ public override void Configure(EntityTypeBuilder builder) .HasConversion(new EnumToStringConverter()) .HasColumnType($"{Config.String}{Config.SmallLength}") .HasCharSet(Config.CharSet); - + builder.Property(e => e.Name) .IsRequired() .HasCharSet(Config.CharSet) @@ -48,7 +48,7 @@ public override void Configure(EntityTypeBuilder builder) .HasConversion( v => JArray.FromObject(v).ToString(Newtonsoft.Json.Formatting.None), v => JArray.Parse(v ?? "[]").ToObject>()); - + builder.Property(e => e.AllowedScopes) .HasCharSet(Config.CharSet) .UseCollation(Config.DatabaseCollation) @@ -61,7 +61,7 @@ public override void Configure(EntityTypeBuilder builder) .HasCharSet(Config.CharSet) .UseCollation(Config.DatabaseCollation) .HasColumnType($"{Config.String}{Config.MediumLength}"); - + builder.Property(e => e.RedirectUris) .HasCharSet(Config.CharSet) .UseCollation(Config.DatabaseCollation) diff --git a/src/platform/mix.database/Entities/Account/EntityConfigurations/PermissionConfiguration.cs b/src/platform/mix.database/Entities/Account/EntityConfigurations/PermissionConfiguration.cs new file mode 100644 index 000000000..ea3a91239 --- /dev/null +++ b/src/platform/mix.database/Entities/Account/EntityConfigurations/PermissionConfiguration.cs @@ -0,0 +1,19 @@ +using Mix.Database.EntityConfigurations.Base; +using Mix.Database.Services; + +namespace Mix.Database.Entities.Account.EntityConfigurations +{ + public class PermissionConfiguration : EntityBaseConfiguration + + { + public PermissionConfiguration(DatabaseService databaseService) : base(databaseService) + { + } + + public override void Configure(EntityTypeBuilder builder) + { + builder.ToTable(MixDatabaseNames.SYSTEM_PERMISSION); + base.Configure(builder); + } + } +} diff --git a/src/platform/mix.database/Entities/Account/EntityConfigurations/SysMixDatabaseAssociationConfiguration.cs b/src/platform/mix.database/Entities/Account/EntityConfigurations/SysMixDatabaseAssociationConfiguration.cs new file mode 100644 index 000000000..fb2816282 --- /dev/null +++ b/src/platform/mix.database/Entities/Account/EntityConfigurations/SysMixDatabaseAssociationConfiguration.cs @@ -0,0 +1,28 @@ +using Mix.Database.EntityConfigurations.Base; +using Mix.Database.Services; + +namespace Mix.Database.Entities.Account.EntityConfigurations +{ + public class SysMixDatabaseAssociationConfiguration : EntityBaseConfiguration + + { + public SysMixDatabaseAssociationConfiguration(DatabaseService databaseService) : base(databaseService) + { + } + + public override void Configure(EntityTypeBuilder builder) + { + builder.ToTable(MixDatabaseNames.SYSTEM_DATA_RELATIONSHIP); + base.Configure(builder); + + builder.Property(e => e.ParentDatabaseName) + .HasColumnType($"{Config.NString}{Config.MediumLength}") + .HasCharSet(Config.CharSet) + .UseCollation(Config.DatabaseCollation); + + builder.Property(e => e.ChildDatabaseName) + .HasColumnType($"{Config.NString}{Config.MediumLength}") + .HasCharSet(Config.CharSet); + } + } +} diff --git a/src/platform/mix.database/Entities/Account/OAuthClient.cs b/src/platform/mix.database/Entities/Account/OAuthClient.cs index d986e1f84..30561f195 100644 --- a/src/platform/mix.database/Entities/Account/OAuthClient.cs +++ b/src/platform/mix.database/Entities/Account/OAuthClient.cs @@ -3,7 +3,7 @@ namespace Mix.Database.Entities.Account { - public partial class OAuthClient: EntityBase + public partial class OAuthClient : EntityBase { public string Name { get; set; } public ApplicationType ApplicationType { get; set; } diff --git a/src/platform/mix.database/Entities/Account/OAuthToken.cs b/src/platform/mix.database/Entities/Account/OAuthToken.cs index 875305bd6..a7adce01a 100644 --- a/src/platform/mix.database/Entities/Account/OAuthToken.cs +++ b/src/platform/mix.database/Entities/Account/OAuthToken.cs @@ -1,10 +1,6 @@ -using System; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace Mix.Database.Entities.Account +namespace Mix.Database.Entities.Account { - public class OAuthToken: EntityBase + public class OAuthToken : EntityBase { public string Token { get; set; } public string ClientId { get; set; } diff --git a/src/platform/mix.database/Entities/Account/Permission.cs b/src/platform/mix.database/Entities/Account/Permission.cs new file mode 100644 index 000000000..d2e8f7c28 --- /dev/null +++ b/src/platform/mix.database/Entities/Account/Permission.cs @@ -0,0 +1,10 @@ +namespace Mix.Database.Entities.Account +{ + public class Permission : EntityBase + { + public int MixTenantId { get; set; } + public string DisplayName { get; set; } + public string Group { get; set; } + public string Key { get; set; } + } +} diff --git a/src/platform/mix.database/Entities/Account/SysMixDatabaseAssociation.cs b/src/platform/mix.database/Entities/Account/SysMixDatabaseAssociation.cs new file mode 100644 index 000000000..ea120f2e5 --- /dev/null +++ b/src/platform/mix.database/Entities/Account/SysMixDatabaseAssociation.cs @@ -0,0 +1,13 @@ +namespace Mix.Database.Entities.Account +{ + public class SysMixDatabaseAssociation : EntityBase + { + public int MixTenantId { get; set; } + public string ParentDatabaseName { get; set; } + public string ChildDatabaseName { get; set; } + public Guid? GuidParentId { get; set; } + public Guid? GuidChildId { get; set; } + public int ParentId { get; set; } + public int ChildId { get; set; } + } +} diff --git a/src/platform/mix.database/Entities/Account/_MixCmsAccountContext.cs b/src/platform/mix.database/Entities/Account/_MixCmsAccountContext.cs index 1a0506752..792317ad4 100644 --- a/src/platform/mix.database/Entities/Account/_MixCmsAccountContext.cs +++ b/src/platform/mix.database/Entities/Account/_MixCmsAccountContext.cs @@ -22,7 +22,8 @@ public partial class MixCmsAccountContext : BaseDbContext public virtual DbSet MixRoles { get; set; } public virtual DbSet OAuthClient { get; set; } public virtual DbSet OAuthToken { get; set; } - + public DbSet Permission { get; set; } + public DbSet SysMixDatabaseAssociation { get; set; } /// /// Initializes a new instance of the class. diff --git a/src/platform/mix.database/Entities/AuditLog/AuditLog.cs b/src/platform/mix.database/Entities/AuditLog/AuditLog.cs index ffed174e7..19d72239b 100644 --- a/src/platform/mix.database/Entities/AuditLog/AuditLog.cs +++ b/src/platform/mix.database/Entities/AuditLog/AuditLog.cs @@ -2,7 +2,7 @@ namespace Mix.Database.Entities.AuditLog { - public class AuditLog: EntityBase + public class AuditLog : EntityBase { public bool Success { get; set; } public int StatusCode { get; set; } diff --git a/src/platform/mix.database/Entities/AuditLog/EntityConfigurations/AuditLogConfiguration.cs b/src/platform/mix.database/Entities/AuditLog/EntityConfigurations/AuditLogConfiguration.cs index 2a6d0175b..049b91329 100644 --- a/src/platform/mix.database/Entities/AuditLog/EntityConfigurations/AuditLogConfiguration.cs +++ b/src/platform/mix.database/Entities/AuditLog/EntityConfigurations/AuditLogConfiguration.cs @@ -1,45 +1,18 @@ -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Mix.Database.Entities.Account; -using Mix.Database.EntityConfigurations; +using Mix.Database.EntityConfigurations.Base; using Mix.Database.Services; using Newtonsoft.Json.Linq; - namespace Mix.Database.Entities.AuditLog.EntityConfigurations { - internal class AuditLogConfiguration : IEntityTypeConfiguration + internal class AuditLogConfiguration : EntityBaseConfiguration { - public IDatabaseConstants Config; - public AuditLogConfiguration() + public AuditLogConfiguration(DatabaseService databaseService) : base(databaseService) { - Config = new SqliteDatabaseConstants(); } - public void Configure(EntityTypeBuilder builder) + public override void Configure(EntityTypeBuilder builder) { - builder.Property(e => e.IsDeleted) - .HasColumnType(Config.Boolean); - - builder.Property(e => e.CreatedDateTime) - .HasColumnType(Config.DateTime); - - builder.Property(e => e.LastModified) - .HasColumnType(Config.DateTime); - - builder.Property(e => e.CreatedBy) - .HasColumnType($"{Config.String}{Config.MediumLength}"); - - builder.Property(e => e.ModifiedBy) - .HasColumnType($"{Config.String}{Config.MediumLength}"); - - builder.Property(e => e.Priority) - .HasColumnType(Config.Integer); - - builder.Property(e => e.Status) - .IsRequired() - .HasConversion(new EnumToStringConverter()) - .HasColumnType($"{Config.String}{Config.SmallLength}") - .HasCharSet(Config.CharSet); + base.Configure(builder); builder.Property(e => e.Body) .HasConversion( diff --git a/src/platform/mix.database/Entities/AuditLog/_AuditLogDbContext.cs b/src/platform/mix.database/Entities/AuditLog/_AuditLogDbContext.cs index f39c9af98..be891d8be 100644 --- a/src/platform/mix.database/Entities/AuditLog/_AuditLogDbContext.cs +++ b/src/platform/mix.database/Entities/AuditLog/_AuditLogDbContext.cs @@ -1,30 +1,21 @@ -using Mix.Database.Entities.AuditLog.EntityConfigurations; -using Mix.Heart.Services; +using Mix.Database.Services; namespace Mix.Database.Entities.AuditLog { - public class AuditLogDbContext : DbContext + public class AuditLogDbContext : BaseDbContext { - private string _folder = DateTime.UtcNow.ToString("MM_yyyy"); - private string _cnn; - public AuditLogDbContext() + public AuditLogDbContext(DatabaseService databaseService) : base(databaseService, MixConstants.CONST_AUDIT_LOG_CONNECTION) { - _cnn = $"Data Source={MixFolders.MixAuditLogFolder}/{_folder}/auditlog_{DateTime.Now.ToString("dd_MM_yyyy")}.sqlite"; } - public AuditLogDbContext(DateTime date) - { - _folder = date.ToString("MM_yyyy"); - _cnn = $"Data Source={MixFolders.MixAuditLogFolder}/{_folder}/auditlog_{date.ToString("dd_MM_yyyy")}.sqlite"; - } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + + public AuditLogDbContext(DatabaseService databaseService, string connectionStringName) : base(databaseService, connectionStringName) { - MixFileHelper.CreateFolderIfNotExist($"{MixFolders.MixAuditLogFolder}/{_folder}"); - optionsBuilder.UseSqlite(_cnn); } - protected override void OnModelCreating(ModelBuilder modelBuilder) + + public AuditLogDbContext(string connectionString, MixDatabaseProvider databaseProvider) : base(connectionString, databaseProvider) { - modelBuilder.ApplyConfiguration(new AuditLogConfiguration()); } + public virtual DbSet AuditLog { get; set; } } diff --git a/src/platform/mix.database/Entities/AuditLog/_MySqlAuditLogDbContext.cs b/src/platform/mix.database/Entities/AuditLog/_MySqlAuditLogDbContext.cs new file mode 100644 index 000000000..25ebf57a1 --- /dev/null +++ b/src/platform/mix.database/Entities/AuditLog/_MySqlAuditLogDbContext.cs @@ -0,0 +1,11 @@ +using Mix.Database.Services; + +namespace Mix.Database.Entities.AuditLog +{ + public class MySqlAuditLogDbContext : AuditLogDbContext + { + public MySqlAuditLogDbContext(DatabaseService databaseService) : base(databaseService) + { + } + } +} diff --git a/src/platform/mix.database/Entities/AuditLog/_PostgresAuditLogDbContext.cs b/src/platform/mix.database/Entities/AuditLog/_PostgresAuditLogDbContext.cs new file mode 100644 index 000000000..0392e2b02 --- /dev/null +++ b/src/platform/mix.database/Entities/AuditLog/_PostgresAuditLogDbContext.cs @@ -0,0 +1,11 @@ +using Mix.Database.Services; + +namespace Mix.Database.Entities.AuditLog +{ + public class PostgresAuditLogDbContext : AuditLogDbContext + { + public PostgresAuditLogDbContext(DatabaseService databaseService) : base(databaseService) + { + } + } +} diff --git a/src/platform/mix.database/Entities/AuditLog/_SqlServerAuditLogDbContext.cs b/src/platform/mix.database/Entities/AuditLog/_SqlServerAuditLogDbContext.cs new file mode 100644 index 000000000..b985da14b --- /dev/null +++ b/src/platform/mix.database/Entities/AuditLog/_SqlServerAuditLogDbContext.cs @@ -0,0 +1,11 @@ +using Mix.Database.Services; + +namespace Mix.Database.Entities.AuditLog +{ + public class SqlServerAuditLogDbContext : AuditLogDbContext + { + public SqlServerAuditLogDbContext(DatabaseService databaseService) : base(databaseService) + { + } + } +} diff --git a/src/platform/mix.database/Entities/AuditLog/_SqliteAuditLogDbContext.cs b/src/platform/mix.database/Entities/AuditLog/_SqliteAuditLogDbContext.cs new file mode 100644 index 000000000..686dd79c9 --- /dev/null +++ b/src/platform/mix.database/Entities/AuditLog/_SqliteAuditLogDbContext.cs @@ -0,0 +1,11 @@ +using Mix.Database.Services; + +namespace Mix.Database.Entities.AuditLog +{ + public class SqlITEAuditLogDbContext : AuditLogDbContext + { + public SqlITEAuditLogDbContext(DatabaseService databaseService) : base(databaseService) + { + } + } +} diff --git a/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixDatabaseContextConfiguration.cs b/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixDatabaseContextConfiguration.cs index c42c48317..0e7674adb 100644 --- a/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixDatabaseContextConfiguration.cs +++ b/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixDatabaseContextConfiguration.cs @@ -19,7 +19,7 @@ public override void Configure(EntityTypeBuilder builder) .IsRequired() .HasColumnType($"{Config.String}{Config.SmallLength}") .HasCharSet(Config.CharSet); - + builder.Property(e => e.ConnectionString) .IsRequired() .HasColumnType($"{Config.String}{Config.MediumLength}") diff --git a/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixLanguageContentConfiguration.cs b/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixLanguageContentConfiguration.cs index fcca0c7c9..589368763 100644 --- a/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixLanguageContentConfiguration.cs +++ b/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixLanguageContentConfiguration.cs @@ -20,7 +20,7 @@ public override void Configure(EntityTypeBuilder builder) .HasColumnType($"{Config.NString}{Config.MaxLength}") .HasCharSet(Config.CharSet) .UseCollation(Config.DatabaseCollation); - + builder.Property(e => e.Category) .IsRequired(false) .HasColumnType($"{Config.NString}{Config.MediumLength}") diff --git a/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixModuleDataConfiguration.cs b/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixModuleDataConfiguration.cs index 85980a7b0..66ec4a8ac 100644 --- a/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixModuleDataConfiguration.cs +++ b/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixModuleDataConfiguration.cs @@ -13,12 +13,12 @@ public MixModuleDataConfiguration(DatabaseService databaseService) : base(databa public override void Configure(EntityTypeBuilder builder) { base.Configure(builder); - + builder.Property(e => e.SimpleDataColumns) .HasColumnType($"{Config.NString}{Config.MaxLength}") .HasCharSet(Config.CharSet) .UseCollation(Config.DatabaseCollation); - + builder.Property(e => e.Value) .HasColumnType($"{Config.NString}{Config.MaxLength}") .HasCharSet(Config.CharSet) diff --git a/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixThemeConfiguration.cs b/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixThemeConfiguration.cs index 7c0843c86..5806e00d7 100644 --- a/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixThemeConfiguration.cs +++ b/src/platform/mix.database/Entities/Cms/EntityConfigurations/MixThemeConfiguration.cs @@ -1,6 +1,5 @@ using Mix.Database.Base.Cms; using Mix.Database.Services; -using Newtonsoft.Json.Linq; namespace Mix.Database.Entities.Cms.EntityConfigurations { @@ -35,7 +34,7 @@ public override void Configure(EntityTypeBuilder builder) .UseCollation(Config.DatabaseCollation); - + } } } diff --git a/src/platform/mix.database/Entities/Cms/MixDatabase.cs b/src/platform/mix.database/Entities/Cms/MixDatabase.cs index 1e160f6e1..4909814a2 100644 --- a/src/platform/mix.database/Entities/Cms/MixDatabase.cs +++ b/src/platform/mix.database/Entities/Cms/MixDatabase.cs @@ -1,5 +1,4 @@ -using Newtonsoft.Json.Linq; -using System.Collections.Generic; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace Mix.Database.Entities.Cms diff --git a/src/platform/mix.database/Entities/MixDb/EntityConfigurations/ContactAddressConfiguration.cs b/src/platform/mix.database/Entities/MixDb/EntityConfigurations/ContactAddressConfiguration.cs index 2a1d5104c..fa4922c68 100644 --- a/src/platform/mix.database/Entities/MixDb/EntityConfigurations/ContactAddressConfiguration.cs +++ b/src/platform/mix.database/Entities/MixDb/EntityConfigurations/ContactAddressConfiguration.cs @@ -1,7 +1,4 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Mix.Database.Constants; -using Mix.Database.EntityConfigurations.Base; +using Mix.Database.EntityConfigurations.Base; using Mix.Database.Services; namespace Mix.Database.Entities.MixDb.EntityConfigurations diff --git a/src/platform/mix.database/Entities/MixDb/MixDbDbContext.cs b/src/platform/mix.database/Entities/MixDb/MixDbDbContext.cs index a81bd5d7d..9f85da386 100644 --- a/src/platform/mix.database/Entities/MixDb/MixDbDbContext.cs +++ b/src/platform/mix.database/Entities/MixDb/MixDbDbContext.cs @@ -1,8 +1,4 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata; -using Mix.Constant.Constants; -using Mix.Database.Base; -using Mix.Database.Services; +using Mix.Database.Services; namespace Mix.Database.Entities.MixDb { diff --git a/src/platform/mix.database/Entities/MixDb/MixMedia.cs b/src/platform/mix.database/Entities/MixDb/MixMedia.cs index 62b820b64..d5133607c 100644 --- a/src/platform/mix.database/Entities/MixDb/MixMedia.cs +++ b/src/platform/mix.database/Entities/MixDb/MixMedia.cs @@ -1,6 +1,4 @@ -using Mix.Heart.Entities; - -namespace Mix.Database.Entities.MixDb +namespace Mix.Database.Entities.MixDb { public class MixDbMedia : EntityBase { diff --git a/src/platform/mix.database/Entities/MixDb/MixMetadata.cs b/src/platform/mix.database/Entities/MixDb/MixMetadata.cs index 71b8174f9..c886e8b06 100644 --- a/src/platform/mix.database/Entities/MixDb/MixMetadata.cs +++ b/src/platform/mix.database/Entities/MixDb/MixMetadata.cs @@ -1,6 +1,4 @@ -using Mix.Heart.Entities; - -namespace Mix.Database.Entities.MixDb +namespace Mix.Database.Entities.MixDb { public class MixMetadata : EntityBase { diff --git a/src/platform/mix.database/Entities/MixDb/MixMetadataContentAssociation.cs b/src/platform/mix.database/Entities/MixDb/MixMetadataContentAssociation.cs index bf1c7ceab..386e6f5c5 100644 --- a/src/platform/mix.database/Entities/MixDb/MixMetadataContentAssociation.cs +++ b/src/platform/mix.database/Entities/MixDb/MixMetadataContentAssociation.cs @@ -1,7 +1,4 @@ -using Mix.Constant.Enums; -using Mix.Heart.Entities; - -namespace Mix.Database.Entities.MixDb +namespace Mix.Database.Entities.MixDb { public class MixMetadataContentAssociation : EntityBase { diff --git a/src/platform/mix.database/Entities/MixDb/MixPermission.cs b/src/platform/mix.database/Entities/MixDb/MixPermission.cs index d120d26c3..a3ab0b7e6 100644 --- a/src/platform/mix.database/Entities/MixDb/MixPermission.cs +++ b/src/platform/mix.database/Entities/MixDb/MixPermission.cs @@ -2,12 +2,11 @@ { public sealed class MixPermission : EntityBase { - public string Title { get; set; } - public string Type { get; set; } - public string Icon { get; set; } public int MixTenantId { get; set; } + public string DisplayName { get; set; } + public string Group { get; set; } + public string Key { get; set; } } - public sealed class Metadata { public string Description { get; set; } diff --git a/src/platform/mix.database/Entities/MixDb/MixUserPermission.cs b/src/platform/mix.database/Entities/MixDb/MixUserPermission.cs index c72114420..9e06addfa 100644 --- a/src/platform/mix.database/Entities/MixDb/MixUserPermission.cs +++ b/src/platform/mix.database/Entities/MixDb/MixUserPermission.cs @@ -1,6 +1,4 @@ -using Mix.Heart.Entities; - -namespace Mix.Database.Entities.MixDb +namespace Mix.Database.Entities.MixDb { public sealed class MixUserPermission : EntityBase { diff --git a/src/platform/mix.database/Entities/MixDb/MySqlMixDbDbContext.cs b/src/platform/mix.database/Entities/MixDb/MySqlMixDbDbContext.cs index 5955784b9..6d0670cd9 100644 --- a/src/platform/mix.database/Entities/MixDb/MySqlMixDbDbContext.cs +++ b/src/platform/mix.database/Entities/MixDb/MySqlMixDbDbContext.cs @@ -1,9 +1,4 @@ using Mix.Database.Services; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Database.Entities.MixDb { diff --git a/src/platform/mix.database/Entities/MixDb/PostgresSqlMixDbDbContext.cs b/src/platform/mix.database/Entities/MixDb/PostgresSqlMixDbDbContext.cs index 1e0fe2374..62e90078c 100644 --- a/src/platform/mix.database/Entities/MixDb/PostgresSqlMixDbDbContext.cs +++ b/src/platform/mix.database/Entities/MixDb/PostgresSqlMixDbDbContext.cs @@ -1,9 +1,4 @@ using Mix.Database.Services; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Database.Entities.MixDb { diff --git a/src/platform/mix.database/Entities/MixDb/SqliteMixDbDbContext.cs b/src/platform/mix.database/Entities/MixDb/SqliteMixDbDbContext.cs index ac7b62215..9d3b993ea 100644 --- a/src/platform/mix.database/Entities/MixDb/SqliteMixDbDbContext.cs +++ b/src/platform/mix.database/Entities/MixDb/SqliteMixDbDbContext.cs @@ -1,9 +1,4 @@ using Mix.Database.Services; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Database.Entities.MixDb { diff --git a/src/platform/mix.database/Entities/Queue/EntityConfigurations/MixQueueMessageConfiguration.cs b/src/platform/mix.database/Entities/Queue/EntityConfigurations/MixQueueMessageConfiguration.cs index 548f31b5f..569c49a12 100644 --- a/src/platform/mix.database/Entities/Queue/EntityConfigurations/MixQueueMessageConfiguration.cs +++ b/src/platform/mix.database/Entities/Queue/EntityConfigurations/MixQueueMessageConfiguration.cs @@ -1,10 +1,5 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Database.Entities.Queue.EntityConfigurations { @@ -19,16 +14,16 @@ public void Configure(EntityTypeBuilder builder) { builder.Property(e => e.TopicId) .HasColumnType($"{Config.String}{Config.MediumLength}"); - + builder.Property(e => e.SubscriptionId) .HasColumnType($"{Config.String}{Config.MediumLength}"); - + builder.Property(e => e.DataTypeFullName) .HasColumnType($"{Config.String}{Config.MediumLength}"); - + builder.Property(e => e.Action) .HasColumnType($"{Config.String}{Config.MediumLength}"); - + builder.Property(e => e.Note) .HasColumnType($"{Config.String}{Config.MediumLength}"); @@ -71,14 +66,14 @@ public void Configure(EntityTypeBuilder builder) v => !string.IsNullOrEmpty(v) ? JObject.Parse(v) : new()) .IsRequired(false) .HasColumnType(Config.Text); - + builder.Property(e => e.Exception) .HasConversion( v => v.ToString(Newtonsoft.Json.Formatting.None), v => !string.IsNullOrEmpty(v) ? JObject.Parse(v) : new()) .IsRequired(false) .HasColumnType(Config.Text); - + builder.Property(e => e.Subscriptions) .HasConversion( v => v.ToString(Newtonsoft.Json.Formatting.None), diff --git a/src/platform/mix.database/Entities/Queue/MixQueueMessageLog.cs b/src/platform/mix.database/Entities/Queue/MixQueueMessageLog.cs index 6b03f9e50..be03184b0 100644 --- a/src/platform/mix.database/Entities/Queue/MixQueueMessageLog.cs +++ b/src/platform/mix.database/Entities/Queue/MixQueueMessageLog.cs @@ -1,13 +1,8 @@ using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Database.Entities.Queue { - public sealed class MixQueueMessageLog: EntityBase + public sealed class MixQueueMessageLog : EntityBase { public Guid? QueueMessageId { get; set; } public string TopicId { get; set; } diff --git a/src/platform/mix.database/Entities/QueueLog/EntityConfigurations/QueueLogConfiguration.cs b/src/platform/mix.database/Entities/QueueLog/EntityConfigurations/QueueLogConfiguration.cs new file mode 100644 index 000000000..8debda7c7 --- /dev/null +++ b/src/platform/mix.database/Entities/QueueLog/EntityConfigurations/QueueLogConfiguration.cs @@ -0,0 +1,64 @@ +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.EntityConfigurations.Base; +using Mix.Database.Services; +using Newtonsoft.Json.Linq; + +namespace Mix.Database.Entities.QueueLog.EntityConfigurations +{ + internal class QueueLogConfiguration : EntityBaseConfiguration + { + public QueueLogConfiguration(DatabaseService databaseService) : base(databaseService) + { + } + + public override void Configure(EntityTypeBuilder builder) + { + base.Configure(builder); + + builder.Property(e => e.TopicId) + .HasColumnType($"{Config.String}{Config.MediumLength}"); + + builder.Property(e => e.SubscriptionId) + .HasColumnType($"{Config.String}{Config.MediumLength}"); + + builder.Property(e => e.DataTypeFullName) + .HasColumnType($"{Config.String}{Config.MediumLength}"); + + builder.Property(e => e.Action) + .HasColumnType($"{Config.String}{Config.MediumLength}"); + + builder.Property(e => e.Note) + .HasColumnType($"{Config.String}{Config.MediumLength}"); + + builder.Property(e => e.State) + .IsRequired() + .HasConversion(new EnumToStringConverter()) + .HasColumnType($"{Config.String}{Config.SmallLength}") + .HasCharSet(Config.CharSet); + + builder.Property(e => e.StringData) + .HasColumnType(Config.Text); + + builder.Property(e => e.ObjectData) + .HasConversion( + v => v.ToString(Newtonsoft.Json.Formatting.None), + v => !string.IsNullOrEmpty(v) ? JObject.Parse(v) : new()) + .IsRequired(false) + .HasColumnType(Config.Text); + + builder.Property(e => e.Exception) + .HasConversion( + v => v.ToString(Newtonsoft.Json.Formatting.None), + v => !string.IsNullOrEmpty(v) ? JObject.Parse(v) : new()) + .IsRequired(false) + .HasColumnType(Config.Text); + + builder.Property(e => e.Subscriptions) + .HasConversion( + v => v.ToString(Newtonsoft.Json.Formatting.None), + v => !string.IsNullOrEmpty(v) ? JArray.Parse(v) : new()) + .IsRequired(false) + .HasColumnType(Config.Text); + } + } +} diff --git a/src/platform/mix.database/Entities/QueueLog/QueueLog.cs b/src/platform/mix.database/Entities/QueueLog/QueueLog.cs new file mode 100644 index 000000000..2c339de8c --- /dev/null +++ b/src/platform/mix.database/Entities/QueueLog/QueueLog.cs @@ -0,0 +1,20 @@ +using Newtonsoft.Json.Linq; + +namespace Mix.Database.Entities.QueueLog +{ + public sealed class QueueLog : EntityBase + { + public Guid? QueueMessageId { get; set; } + public string TopicId { get; set; } + public string SubscriptionId { get; set; } + public string Action { get; set; } + public string StringData { get; set; } + public JObject ObjectData { get; set; } + public JObject Exception { get; set; } + public JArray Subscriptions { get; set; } + public string DataTypeFullName { get; set; } + public string Note { get; set; } + public MixQueueMessageLogState State { get; set; } + public int TenantId { get; set; } + } +} diff --git a/src/platform/mix.database/Entities/QueueLog/_MySqlQueueLogDbContext.cs b/src/platform/mix.database/Entities/QueueLog/_MySqlQueueLogDbContext.cs new file mode 100644 index 000000000..3c8d52985 --- /dev/null +++ b/src/platform/mix.database/Entities/QueueLog/_MySqlQueueLogDbContext.cs @@ -0,0 +1,11 @@ +using Mix.Database.Services; + +namespace Mix.Database.Entities.QueueLog +{ + public class MySqlQueueLogDbContext : QueueLogDbContext + { + public MySqlQueueLogDbContext(DatabaseService databaseService) : base(databaseService) + { + } + } +} diff --git a/src/platform/mix.database/Entities/QueueLog/_PostgresQueueLogDbContext.cs b/src/platform/mix.database/Entities/QueueLog/_PostgresQueueLogDbContext.cs new file mode 100644 index 000000000..74ddb0ba3 --- /dev/null +++ b/src/platform/mix.database/Entities/QueueLog/_PostgresQueueLogDbContext.cs @@ -0,0 +1,11 @@ +using Mix.Database.Services; + +namespace Mix.Database.Entities.QueueLog +{ + public class PostgresQueueLogDbContext : QueueLogDbContext + { + public PostgresQueueLogDbContext(DatabaseService databaseService) : base(databaseService) + { + } + } +} diff --git a/src/platform/mix.database/Entities/QueueLog/_QueueLogDbContext.cs b/src/platform/mix.database/Entities/QueueLog/_QueueLogDbContext.cs new file mode 100644 index 000000000..b5fe0aedf --- /dev/null +++ b/src/platform/mix.database/Entities/QueueLog/_QueueLogDbContext.cs @@ -0,0 +1,22 @@ +using Mix.Database.Services; + +namespace Mix.Database.Entities.QueueLog +{ + public class QueueLogDbContext : BaseDbContext + { + public QueueLogDbContext(DatabaseService databaseService) : base(databaseService, MixConstants.CONST_QUEUE_LOG_CONNECTION) + { + } + + public QueueLogDbContext(DatabaseService databaseService, string connectionStringName) : base(databaseService, connectionStringName) + { + } + + public QueueLogDbContext(string connectionString, MixDatabaseProvider databaseProvider) : base(connectionString, databaseProvider) + { + } + + public virtual DbSet QueueLog { get; set; } + + } +} diff --git a/src/platform/mix.database/Entities/QueueLog/_SqlServerQueueLogDbContext.cs b/src/platform/mix.database/Entities/QueueLog/_SqlServerQueueLogDbContext.cs new file mode 100644 index 000000000..fb469b364 --- /dev/null +++ b/src/platform/mix.database/Entities/QueueLog/_SqlServerQueueLogDbContext.cs @@ -0,0 +1,11 @@ +using Mix.Database.Services; + +namespace Mix.Database.Entities.QueueLog +{ + public class SqlServerQueueLogDbContext : QueueLogDbContext + { + public SqlServerQueueLogDbContext(DatabaseService databaseService) : base(databaseService) + { + } + } +} diff --git a/src/platform/mix.database/Entities/QueueLog/_SqliteQueueLogDbContext.cs b/src/platform/mix.database/Entities/QueueLog/_SqliteQueueLogDbContext.cs new file mode 100644 index 000000000..4b97ac238 --- /dev/null +++ b/src/platform/mix.database/Entities/QueueLog/_SqliteQueueLogDbContext.cs @@ -0,0 +1,11 @@ +using Mix.Database.Services; + +namespace Mix.Database.Entities.QueueLog +{ + public class SqlITEQueueLogDbContext : QueueLogDbContext + { + public SqlITEQueueLogDbContext(DatabaseService databaseService) : base(databaseService) + { + } + } +} diff --git a/src/platform/mix.database/Migrations/Account/MySqlAccount/20220320105313_Init.cs b/src/platform/mix.database/Migrations/Account/MySqlAccount/20220320105313_Init.cs index a2194c95f..7ffef3011 100644 --- a/src/platform/mix.database/Migrations/Account/MySqlAccount/20220320105313_Init.cs +++ b/src/platform/mix.database/Migrations/Account/MySqlAccount/20220320105313_Init.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Account/MySqlAccount/20231126025334_AddOAuth.cs b/src/platform/mix.database/Migrations/Account/MySqlAccount/20231126025334_AddOAuth.cs index 81dbbe3c8..d8f7c7ea6 100644 --- a/src/platform/mix.database/Migrations/Account/MySqlAccount/20231126025334_AddOAuth.cs +++ b/src/platform/mix.database/Migrations/Account/MySqlAccount/20231126025334_AddOAuth.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Account/PostgresSQLAccount/20221214113845_Init.cs b/src/platform/mix.database/Migrations/Account/PostgresSQLAccount/20221214113845_Init.cs index e8f0dc205..3ed3ef225 100644 --- a/src/platform/mix.database/Migrations/Account/PostgresSQLAccount/20221214113845_Init.cs +++ b/src/platform/mix.database/Migrations/Account/PostgresSQLAccount/20221214113845_Init.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable diff --git a/src/platform/mix.database/Migrations/Account/PostgresSQLAccount/20231126025525_AddOAuth.cs b/src/platform/mix.database/Migrations/Account/PostgresSQLAccount/20231126025525_AddOAuth.cs index 8fd8bd33d..374f3a128 100644 --- a/src/platform/mix.database/Migrations/Account/PostgresSQLAccount/20231126025525_AddOAuth.cs +++ b/src/platform/mix.database/Migrations/Account/PostgresSQLAccount/20231126025525_AddOAuth.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Account/SqlServerAccount/20220322115957_Init.cs b/src/platform/mix.database/Migrations/Account/SqlServerAccount/20220322115957_Init.cs index 80e2e43e9..3faa41767 100644 --- a/src/platform/mix.database/Migrations/Account/SqlServerAccount/20220322115957_Init.cs +++ b/src/platform/mix.database/Migrations/Account/SqlServerAccount/20220322115957_Init.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Account/SqlServerAccount/20231126025942_AddOAuth.cs b/src/platform/mix.database/Migrations/Account/SqlServerAccount/20231126025942_AddOAuth.cs index f66b4707c..d437cb829 100644 --- a/src/platform/mix.database/Migrations/Account/SqlServerAccount/20231126025942_AddOAuth.cs +++ b/src/platform/mix.database/Migrations/Account/SqlServerAccount/20231126025942_AddOAuth.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Account/SqliteAccount/20220320033213_Init.cs b/src/platform/mix.database/Migrations/Account/SqliteAccount/20220320033213_Init.cs index c518c5c9e..730e7497c 100644 --- a/src/platform/mix.database/Migrations/Account/SqliteAccount/20220320033213_Init.cs +++ b/src/platform/mix.database/Migrations/Account/SqliteAccount/20220320033213_Init.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Account/SqliteAccount/20231125060119_AddOAuth.cs b/src/platform/mix.database/Migrations/Account/SqliteAccount/20231125060119_AddOAuth.cs index f21325bd3..f082536cd 100644 --- a/src/platform/mix.database/Migrations/Account/SqliteAccount/20231125060119_AddOAuth.cs +++ b/src/platform/mix.database/Migrations/Account/SqliteAccount/20231125060119_AddOAuth.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/AuditLogDb/20230416100208_AddRespQueryCol.cs b/src/platform/mix.database/Migrations/AuditLogDb/20230416100208_AddRespQueryCol.cs index d74534c59..8bdb333e7 100644 --- a/src/platform/mix.database/Migrations/AuditLogDb/20230416100208_AddRespQueryCol.cs +++ b/src/platform/mix.database/Migrations/AuditLogDb/20230416100208_AddRespQueryCol.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/AuditLogDb/20230627121634_AddStatusCode.cs b/src/platform/mix.database/Migrations/AuditLogDb/20230627121634_AddStatusCode.cs index 614c88d4d..0597a8bd6 100644 --- a/src/platform/mix.database/Migrations/AuditLogDb/20230627121634_AddStatusCode.cs +++ b/src/platform/mix.database/Migrations/AuditLogDb/20230627121634_AddStatusCode.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/AuditLogDb/MySql/20240310051036_InitAuditLog.Designer.cs b/src/platform/mix.database/Migrations/AuditLogDb/MySql/20240310051036_InitAuditLog.Designer.cs new file mode 100644 index 000000000..c8c3b4087 --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/MySql/20240310051036_InitAuditLog.Designer.cs @@ -0,0 +1,91 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.AuditLog; + +#nullable disable + +namespace Mix.Database.Migrations.MySqlAuditLogDb +{ + [DbContext(typeof(MySqlAuditLogDbContext))] + [Migration("20240310051036_InitAuditLog")] + partial class InitAuditLog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("Mix.Database.Entities.AuditLog.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Body") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Endpoint") + .HasColumnType("longtext"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Method") + .HasColumnType("longtext"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueryString") + .HasColumnType("longtext"); + + b.Property("RequestIp") + .HasColumnType("longtext"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)"); + + MySqlPropertyBuilderExtensions.HasCharSet(b.Property("Status"), "utf8"); + + b.Property("StatusCode") + .HasColumnType("int"); + + b.Property("Success") + .HasColumnType("tinyint(1)"); + + b.HasKey("Id") + .HasName("PK_AuditLog"); + + b.ToTable("AuditLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/MySql/20240310051036_InitAuditLog.cs b/src/platform/mix.database/Migrations/AuditLogDb/MySql/20240310051036_InitAuditLog.cs new file mode 100644 index 000000000..a581e13bc --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/MySql/20240310051036_InitAuditLog.cs @@ -0,0 +1,62 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Mix.Database.Migrations.MySqlAuditLogDb +{ + /// + public partial class InitAuditLog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterDatabase() + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "AuditLog", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false, defaultValueSql: "gen_random_uuid()", collation: "ascii_general_ci"), + Success = table.Column(type: "tinyint(1)", nullable: false), + StatusCode = table.Column(type: "int", nullable: false), + RequestIp = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Endpoint = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Method = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + QueryString = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Body = table.Column(type: "text", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Response = table.Column(type: "text", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Exception = table.Column(type: "text", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + CreatedDateTime = table.Column(type: "timestamp with time zone(6)", nullable: false), + LastModified = table.Column(type: "timestamp with time zone(6)", nullable: true), + CreatedBy = table.Column(type: "varchar(250)", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + ModifiedBy = table.Column(type: "varchar(250)", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Priority = table.Column(type: "int", nullable: false), + Status = table.Column(type: "varchar(50)", nullable: false) + .Annotation("MySql:CharSet", "utf8"), + IsDeleted = table.Column(type: "tinyint(1)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AuditLog", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AuditLog"); + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/MySql/MySqlAuditLogDbContextModelSnapshot.cs b/src/platform/mix.database/Migrations/AuditLogDb/MySql/MySqlAuditLogDbContextModelSnapshot.cs new file mode 100644 index 000000000..7662398f7 --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/MySql/MySqlAuditLogDbContextModelSnapshot.cs @@ -0,0 +1,88 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.AuditLog; + +#nullable disable + +namespace Mix.Database.Migrations.MySqlAuditLogDb +{ + [DbContext(typeof(MySqlAuditLogDbContext))] + partial class MySqlAuditLogDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("Mix.Database.Entities.AuditLog.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Body") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Endpoint") + .HasColumnType("longtext"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Method") + .HasColumnType("longtext"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueryString") + .HasColumnType("longtext"); + + b.Property("RequestIp") + .HasColumnType("longtext"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)"); + + MySqlPropertyBuilderExtensions.HasCharSet(b.Property("Status"), "utf8"); + + b.Property("StatusCode") + .HasColumnType("int"); + + b.Property("Success") + .HasColumnType("tinyint(1)"); + + b.HasKey("Id") + .HasName("PK_AuditLog"); + + b.ToTable("AuditLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/Postgresql/20240310045005_InitAuditLog.Designer.cs b/src/platform/mix.database/Migrations/AuditLogDb/Postgresql/20240310045005_InitAuditLog.Designer.cs new file mode 100644 index 000000000..6f0dd6580 --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/Postgresql/20240310045005_InitAuditLog.Designer.cs @@ -0,0 +1,93 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.AuditLog; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Mix.Database.Migrations.PostgresAuditLogDb +{ + [DbContext(typeof(PostgresAuditLogDbContext))] + [Migration("20240310045005_InitAuditLog")] + partial class InitAuditLog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.AuditLog.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Body") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Endpoint") + .HasColumnType("text"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Method") + .HasColumnType("text"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueryString") + .HasColumnType("text"); + + b.Property("RequestIp") + .HasColumnType("text"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StatusCode") + .HasColumnType("integer"); + + b.Property("Success") + .HasColumnType("boolean"); + + b.HasKey("Id") + .HasName("PK_AuditLog"); + + b.ToTable("AuditLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/Postgresql/20240310045005_InitAuditLog.cs b/src/platform/mix.database/Migrations/AuditLogDb/Postgresql/20240310045005_InitAuditLog.cs new file mode 100644 index 000000000..baecd084a --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/Postgresql/20240310045005_InitAuditLog.cs @@ -0,0 +1,48 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Mix.Database.Migrations.PostgresAuditLogDb +{ + /// + public partial class InitAuditLog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AuditLog", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"), + Success = table.Column(type: "boolean", nullable: false), + StatusCode = table.Column(type: "integer", nullable: false), + RequestIp = table.Column(type: "text", nullable: true), + Endpoint = table.Column(type: "text", nullable: true), + Method = table.Column(type: "text", nullable: true), + QueryString = table.Column(type: "text", nullable: true), + Body = table.Column(type: "text", nullable: true), + Response = table.Column(type: "text", nullable: true), + Exception = table.Column(type: "text", nullable: true), + CreatedDateTime = table.Column(type: "timestamp with time zone", nullable: false), + LastModified = table.Column(type: "timestamp with time zone", nullable: true), + CreatedBy = table.Column(type: "varchar(250)", nullable: true), + ModifiedBy = table.Column(type: "varchar(250)", nullable: true), + Priority = table.Column(type: "int", nullable: false), + Status = table.Column(type: "varchar(50)", nullable: false), + IsDeleted = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AuditLog", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AuditLog"); + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/Postgresql/PostgresAuditLogDbContextModelSnapshot.cs b/src/platform/mix.database/Migrations/AuditLogDb/Postgresql/PostgresAuditLogDbContextModelSnapshot.cs new file mode 100644 index 000000000..1a1537488 --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/Postgresql/PostgresAuditLogDbContextModelSnapshot.cs @@ -0,0 +1,90 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.AuditLog; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Mix.Database.Migrations.PostgresAuditLogDb +{ + [DbContext(typeof(PostgresAuditLogDbContext))] + partial class PostgresAuditLogDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.AuditLog.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Body") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Endpoint") + .HasColumnType("text"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Method") + .HasColumnType("text"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueryString") + .HasColumnType("text"); + + b.Property("RequestIp") + .HasColumnType("text"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StatusCode") + .HasColumnType("integer"); + + b.Property("Success") + .HasColumnType("boolean"); + + b.HasKey("Id") + .HasName("PK_AuditLog"); + + b.ToTable("AuditLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/SqlServer/20240310051318_InitAuditLog.Designer.cs b/src/platform/mix.database/Migrations/AuditLogDb/SqlServer/20240310051318_InitAuditLog.Designer.cs new file mode 100644 index 000000000..91c233bcd --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/SqlServer/20240310051318_InitAuditLog.Designer.cs @@ -0,0 +1,93 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.AuditLog; + +#nullable disable + +namespace Mix.Database.Migrations.SqlServerAuditLogDb +{ + [DbContext(typeof(SqlServerAuditLogDbContext))] + [Migration("20240310051318_InitAuditLog")] + partial class InitAuditLog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.AuditLog.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Body") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Endpoint") + .HasColumnType("nvarchar(max)"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Method") + .HasColumnType("nvarchar(max)"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueryString") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestIp") + .HasColumnType("nvarchar(max)"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StatusCode") + .HasColumnType("int"); + + b.Property("Success") + .HasColumnType("bit"); + + b.HasKey("Id") + .HasName("PK_AuditLog"); + + b.ToTable("AuditLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/SqlServer/20240310051318_InitAuditLog.cs b/src/platform/mix.database/Migrations/AuditLogDb/SqlServer/20240310051318_InitAuditLog.cs new file mode 100644 index 000000000..4cba02826 --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/SqlServer/20240310051318_InitAuditLog.cs @@ -0,0 +1,48 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Mix.Database.Migrations.SqlServerAuditLogDb +{ + /// + public partial class InitAuditLog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AuditLog", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false, defaultValueSql: "gen_random_uuid()"), + Success = table.Column(type: "bit", nullable: false), + StatusCode = table.Column(type: "int", nullable: false), + RequestIp = table.Column(type: "nvarchar(max)", nullable: true), + Endpoint = table.Column(type: "nvarchar(max)", nullable: true), + Method = table.Column(type: "nvarchar(max)", nullable: true), + QueryString = table.Column(type: "nvarchar(max)", nullable: true), + Body = table.Column(type: "text", nullable: true), + Response = table.Column(type: "text", nullable: true), + Exception = table.Column(type: "text", nullable: true), + CreatedDateTime = table.Column(type: "timestamp with time zone", nullable: false), + LastModified = table.Column(type: "timestamp with time zone", nullable: true), + CreatedBy = table.Column(type: "varchar(250)", nullable: true), + ModifiedBy = table.Column(type: "varchar(250)", nullable: true), + Priority = table.Column(type: "int", nullable: false), + Status = table.Column(type: "varchar(50)", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AuditLog", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AuditLog"); + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/SqlServer/SqlServerAuditLogDbContextModelSnapshot.cs b/src/platform/mix.database/Migrations/AuditLogDb/SqlServer/SqlServerAuditLogDbContextModelSnapshot.cs new file mode 100644 index 000000000..b7606ca85 --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/SqlServer/SqlServerAuditLogDbContextModelSnapshot.cs @@ -0,0 +1,90 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.AuditLog; + +#nullable disable + +namespace Mix.Database.Migrations.SqlServerAuditLogDb +{ + [DbContext(typeof(SqlServerAuditLogDbContext))] + partial class SqlServerAuditLogDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.AuditLog.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Body") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Endpoint") + .HasColumnType("nvarchar(max)"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Method") + .HasColumnType("nvarchar(max)"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueryString") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestIp") + .HasColumnType("nvarchar(max)"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StatusCode") + .HasColumnType("int"); + + b.Property("Success") + .HasColumnType("bit"); + + b.HasKey("Id") + .HasName("PK_AuditLog"); + + b.ToTable("AuditLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/Sqlite/20240310050457_InitAuditLog.Designer.cs b/src/platform/mix.database/Migrations/AuditLogDb/Sqlite/20240310050457_InitAuditLog.Designer.cs new file mode 100644 index 000000000..ca4472250 --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/Sqlite/20240310050457_InitAuditLog.Designer.cs @@ -0,0 +1,88 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.AuditLog; + +#nullable disable + +namespace Mix.Database.Migrations.SqlITEAuditLogDb +{ + [DbContext(typeof(SqlITEAuditLogDbContext))] + [Migration("20240310050457_InitAuditLog")] + partial class InitAuditLog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "8.0.2"); + + modelBuilder.Entity("Mix.Database.Entities.AuditLog.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Body") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Endpoint") + .HasColumnType("TEXT"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("INTEGER"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Method") + .HasColumnType("TEXT"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueryString") + .HasColumnType("TEXT"); + + b.Property("RequestIp") + .HasColumnType("TEXT"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StatusCode") + .HasColumnType("INTEGER"); + + b.Property("Success") + .HasColumnType("INTEGER"); + + b.HasKey("Id") + .HasName("PK_AuditLog"); + + b.ToTable("AuditLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/Sqlite/20240310050457_InitAuditLog.cs b/src/platform/mix.database/Migrations/AuditLogDb/Sqlite/20240310050457_InitAuditLog.cs new file mode 100644 index 000000000..60f1aa18e --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/Sqlite/20240310050457_InitAuditLog.cs @@ -0,0 +1,48 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Mix.Database.Migrations.SqlITEAuditLogDb +{ + /// + public partial class InitAuditLog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AuditLog", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false, defaultValueSql: "gen_random_uuid()"), + Success = table.Column(type: "INTEGER", nullable: false), + StatusCode = table.Column(type: "INTEGER", nullable: false), + RequestIp = table.Column(type: "TEXT", nullable: true), + Endpoint = table.Column(type: "TEXT", nullable: true), + Method = table.Column(type: "TEXT", nullable: true), + QueryString = table.Column(type: "TEXT", nullable: true), + Body = table.Column(type: "text", nullable: true), + Response = table.Column(type: "text", nullable: true), + Exception = table.Column(type: "text", nullable: true), + CreatedDateTime = table.Column(type: "timestamp with time zone", nullable: false), + LastModified = table.Column(type: "timestamp with time zone", nullable: true), + CreatedBy = table.Column(type: "varchar(250)", nullable: true), + ModifiedBy = table.Column(type: "varchar(250)", nullable: true), + Priority = table.Column(type: "int", nullable: false), + Status = table.Column(type: "varchar(50)", nullable: false), + IsDeleted = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AuditLog", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AuditLog"); + } + } +} diff --git a/src/platform/mix.database/Migrations/AuditLogDb/Sqlite/SqlITEAuditLogDbContextModelSnapshot.cs b/src/platform/mix.database/Migrations/AuditLogDb/Sqlite/SqlITEAuditLogDbContextModelSnapshot.cs new file mode 100644 index 000000000..790f2e1bb --- /dev/null +++ b/src/platform/mix.database/Migrations/AuditLogDb/Sqlite/SqlITEAuditLogDbContextModelSnapshot.cs @@ -0,0 +1,85 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.AuditLog; + +#nullable disable + +namespace Mix.Database.Migrations.SqlITEAuditLogDb +{ + [DbContext(typeof(SqlITEAuditLogDbContext))] + partial class SqlITEAuditLogDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "8.0.2"); + + modelBuilder.Entity("Mix.Database.Entities.AuditLog.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Body") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Endpoint") + .HasColumnType("TEXT"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("INTEGER"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Method") + .HasColumnType("TEXT"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueryString") + .HasColumnType("TEXT"); + + b.Property("RequestIp") + .HasColumnType("TEXT"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StatusCode") + .HasColumnType("INTEGER"); + + b.Property("Success") + .HasColumnType("INTEGER"); + + b.HasKey("Id") + .HasName("PK_AuditLog"); + + b.ToTable("AuditLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20230623093539_AddAssociationGuidId.cs b/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20230623093539_AddAssociationGuidId.cs index fd6e1b8d8..c4ebe2b10 100644 --- a/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20230623093539_AddAssociationGuidId.cs +++ b/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20230623093539_AddAssociationGuidId.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20230911114224_UpdateMixDbContext.cs b/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20230911114224_UpdateMixDbContext.cs index 313d7b5fe..5a018397b 100644 --- a/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20230911114224_UpdateMixDbContext.cs +++ b/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20230911114224_UpdateMixDbContext.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20231016051353_UpdateMixAppBaseHref.cs b/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20231016051353_UpdateMixAppBaseHref.cs index ee4ef42d4..20f402080 100644 --- a/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20231016051353_UpdateMixAppBaseHref.cs +++ b/src/platform/mix.database/Migrations/Cms/MySqlMixCms/20231016051353_UpdateMixAppBaseHref.cs @@ -15,7 +15,7 @@ protected override void Up(MigrationBuilder migrationBuilder) table: "MixApplication", newName: "DeployUrl"); } - + /// protected override void Down(MigrationBuilder migrationBuilder) { diff --git a/src/platform/mix.database/Migrations/Cms/MySqlMixCms/MySqlMixCmsContextModelSnapshot.cs b/src/platform/mix.database/Migrations/Cms/MySqlMixCms/MySqlMixCmsContextModelSnapshot.cs index b5513c111..db11c1d83 100644 --- a/src/platform/mix.database/Migrations/Cms/MySqlMixCms/MySqlMixCmsContextModelSnapshot.cs +++ b/src/platform/mix.database/Migrations/Cms/MySqlMixCms/MySqlMixCmsContextModelSnapshot.cs @@ -17,7 +17,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "8.0.1") + .HasAnnotation("ProductVersion", "7.0.9") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("Mix.Database.Entities.Cms.MixApplication", b => @@ -714,12 +714,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("ModifiedBy") .HasColumnType("varchar(250)"); - b.Property("NamingConvention") - .IsRequired() - .HasColumnType("varchar(50)"); - - MySqlPropertyBuilderExtensions.HasCharSet(b.Property("NamingConvention"), "utf8"); - b.Property("Priority") .HasColumnType("int"); diff --git a/src/platform/mix.database/Migrations/Cms/PostgresqlMixCms/20230911115532_UpdateMixDbContext.cs b/src/platform/mix.database/Migrations/Cms/PostgresqlMixCms/20230911115532_UpdateMixDbContext.cs index eed0e6127..84b736835 100644 --- a/src/platform/mix.database/Migrations/Cms/PostgresqlMixCms/20230911115532_UpdateMixDbContext.cs +++ b/src/platform/mix.database/Migrations/Cms/PostgresqlMixCms/20230911115532_UpdateMixDbContext.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable diff --git a/src/platform/mix.database/Migrations/Cms/SqlServerMixCms/20230911115759_UpdateMixDbContext.cs b/src/platform/mix.database/Migrations/Cms/SqlServerMixCms/20230911115759_UpdateMixDbContext.cs index 524166e89..12e688740 100644 --- a/src/platform/mix.database/Migrations/Cms/SqlServerMixCms/20230911115759_UpdateMixDbContext.cs +++ b/src/platform/mix.database/Migrations/Cms/SqlServerMixCms/20230911115759_UpdateMixDbContext.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Cms/SqlServerMixCms/SqlServerMixCmsContextModelSnapshot.cs b/src/platform/mix.database/Migrations/Cms/SqlServerMixCms/SqlServerMixCmsContextModelSnapshot.cs index dbd4df35c..577495c49 100644 --- a/src/platform/mix.database/Migrations/Cms/SqlServerMixCms/SqlServerMixCmsContextModelSnapshot.cs +++ b/src/platform/mix.database/Migrations/Cms/SqlServerMixCms/SqlServerMixCmsContextModelSnapshot.cs @@ -18,7 +18,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "8.0.1") + .HasAnnotation("ProductVersion", "7.0.9") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); @@ -679,11 +679,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("ModifiedBy") .HasColumnType("varchar(250)"); - b.Property("NamingConvention") - .IsRequired() - .HasColumnType("nvarchar(50)") - .HasAnnotation("MySql:CharSet", "utf8"); - b.Property("Priority") .HasColumnType("int"); diff --git a/src/platform/mix.database/Migrations/Cms/SqliteMixCms/20221110094125_Init.cs b/src/platform/mix.database/Migrations/Cms/SqliteMixCms/20221110094125_Init.cs index 83770d6bd..b53eda804 100644 --- a/src/platform/mix.database/Migrations/Cms/SqliteMixCms/20221110094125_Init.cs +++ b/src/platform/mix.database/Migrations/Cms/SqliteMixCms/20221110094125_Init.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Cms/SqliteMixCms/20230910085616_UpdateMixDatabaseContext.cs b/src/platform/mix.database/Migrations/Cms/SqliteMixCms/20230910085616_UpdateMixDatabaseContext.cs index c04d61c6a..8b441151c 100644 --- a/src/platform/mix.database/Migrations/Cms/SqliteMixCms/20230910085616_UpdateMixDatabaseContext.cs +++ b/src/platform/mix.database/Migrations/Cms/SqliteMixCms/20230910085616_UpdateMixDatabaseContext.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/Cms/SqliteMixCms/SqliteMixCmsContextModelSnapshot.cs b/src/platform/mix.database/Migrations/Cms/SqliteMixCms/SqliteMixCmsContextModelSnapshot.cs index 2813da7dc..b83a65f04 100644 --- a/src/platform/mix.database/Migrations/Cms/SqliteMixCms/SqliteMixCmsContextModelSnapshot.cs +++ b/src/platform/mix.database/Migrations/Cms/SqliteMixCms/SqliteMixCmsContextModelSnapshot.cs @@ -16,7 +16,7 @@ partial class SqliteMixCmsContextModelSnapshot : ModelSnapshot protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 - modelBuilder.HasAnnotation("ProductVersion", "8.0.1"); + modelBuilder.HasAnnotation("ProductVersion", "7.0.9"); modelBuilder.Entity("Mix.Database.Entities.Cms.MixApplication", b => { @@ -658,11 +658,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("ModifiedBy") .HasColumnType("varchar(250)"); - b.Property("NamingConvention") - .IsRequired() - .HasColumnType("varchar(50)") - .HasAnnotation("MySql:CharSet", "utf8"); - b.Property("Priority") .HasColumnType("integer"); diff --git a/src/platform/mix.database/Migrations/MixQueueDb/20230827051050_InitQueue.cs b/src/platform/mix.database/Migrations/MixQueueDb/20230827051050_InitQueue.cs index 9e26c93ce..9953273bc 100644 --- a/src/platform/mix.database/Migrations/MixQueueDb/20230827051050_InitQueue.cs +++ b/src/platform/mix.database/Migrations/MixQueueDb/20230827051050_InitQueue.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/platform/mix.database/Migrations/QueueLog/MySql/20240310062243_InitQueueLog.Designer.cs b/src/platform/mix.database/Migrations/QueueLog/MySql/20240310062243_InitQueueLog.Designer.cs new file mode 100644 index 000000000..5b72c890c --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/MySql/20240310062243_InitQueueLog.Designer.cs @@ -0,0 +1,104 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.QueueLog; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Mix.Database.Migrations.MySqlQueueLogDb +{ + [DbContext(typeof(MySqlQueueLogDbContext))] + [Migration("20240310062243_InitQueueLog")] + partial class InitQueueLog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.QueueLog.QueueLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .HasColumnType("varchar(250)"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("DataTypeFullName") + .HasColumnType("varchar(250)"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Note") + .HasColumnType("varchar(250)"); + + b.Property("ObjectData") + .HasColumnType("text"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueueMessageId") + .HasColumnType("uuid"); + + b.Property("State") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StringData") + .HasColumnType("text"); + + b.Property("SubscriptionId") + .HasColumnType("varchar(250)"); + + b.Property("Subscriptions") + .HasColumnType("text"); + + b.Property("TenantId") + .HasColumnType("integer"); + + b.Property("TopicId") + .HasColumnType("varchar(250)"); + + b.HasKey("Id") + .HasName("PK_QueueLog"); + + b.ToTable("QueueLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/MySql/20240310062243_InitQueueLog.cs b/src/platform/mix.database/Migrations/QueueLog/MySql/20240310062243_InitQueueLog.cs new file mode 100644 index 000000000..8519f746a --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/MySql/20240310062243_InitQueueLog.cs @@ -0,0 +1,51 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Mix.Database.Migrations.MySqlQueueLogDb +{ + /// + public partial class InitQueueLog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "QueueLog", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"), + QueueMessageId = table.Column(type: "uuid", nullable: true), + TopicId = table.Column(type: "varchar(250)", nullable: true), + SubscriptionId = table.Column(type: "varchar(250)", nullable: true), + Action = table.Column(type: "varchar(250)", nullable: true), + StringData = table.Column(type: "text", nullable: true), + ObjectData = table.Column(type: "text", nullable: true), + Exception = table.Column(type: "text", nullable: true), + Subscriptions = table.Column(type: "text", nullable: true), + DataTypeFullName = table.Column(type: "varchar(250)", nullable: true), + Note = table.Column(type: "varchar(250)", nullable: true), + State = table.Column(type: "varchar(50)", nullable: false), + TenantId = table.Column(type: "integer", nullable: false), + CreatedDateTime = table.Column(type: "timestamp with time zone", nullable: false), + LastModified = table.Column(type: "timestamp with time zone", nullable: true), + CreatedBy = table.Column(type: "varchar(250)", nullable: true), + ModifiedBy = table.Column(type: "varchar(250)", nullable: true), + Priority = table.Column(type: "int", nullable: false), + Status = table.Column(type: "varchar(50)", nullable: false), + IsDeleted = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_QueueLog", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "QueueLog"); + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/MySql/MySqlQueueLogDbContextModelSnapshot.cs b/src/platform/mix.database/Migrations/QueueLog/MySql/MySqlQueueLogDbContextModelSnapshot.cs new file mode 100644 index 000000000..be833808e --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/MySql/MySqlQueueLogDbContextModelSnapshot.cs @@ -0,0 +1,101 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.QueueLog; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Mix.Database.Migrations.MySqlQueueLogDb +{ + [DbContext(typeof(MySqlQueueLogDbContext))] + partial class MySqlQueueLogDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.QueueLog.QueueLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .HasColumnType("varchar(250)"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("DataTypeFullName") + .HasColumnType("varchar(250)"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Note") + .HasColumnType("varchar(250)"); + + b.Property("ObjectData") + .HasColumnType("text"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueueMessageId") + .HasColumnType("uuid"); + + b.Property("State") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StringData") + .HasColumnType("text"); + + b.Property("SubscriptionId") + .HasColumnType("varchar(250)"); + + b.Property("Subscriptions") + .HasColumnType("text"); + + b.Property("TenantId") + .HasColumnType("integer"); + + b.Property("TopicId") + .HasColumnType("varchar(250)"); + + b.HasKey("Id") + .HasName("PK_QueueLog"); + + b.ToTable("QueueLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/Postgres/20240310061825_InitQueueLog.Designer.cs b/src/platform/mix.database/Migrations/QueueLog/Postgres/20240310061825_InitQueueLog.Designer.cs new file mode 100644 index 000000000..510696890 --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/Postgres/20240310061825_InitQueueLog.Designer.cs @@ -0,0 +1,104 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.QueueLog; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Mix.Database.Migrations.PostgresQueueLogDb +{ + [DbContext(typeof(PostgresQueueLogDbContext))] + [Migration("20240310061825_InitQueueLog")] + partial class InitQueueLog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.QueueLog.QueueLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .HasColumnType("varchar(250)"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("DataTypeFullName") + .HasColumnType("varchar(250)"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Note") + .HasColumnType("varchar(250)"); + + b.Property("ObjectData") + .HasColumnType("text"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueueMessageId") + .HasColumnType("uuid"); + + b.Property("State") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StringData") + .HasColumnType("text"); + + b.Property("SubscriptionId") + .HasColumnType("varchar(250)"); + + b.Property("Subscriptions") + .HasColumnType("text"); + + b.Property("TenantId") + .HasColumnType("integer"); + + b.Property("TopicId") + .HasColumnType("varchar(250)"); + + b.HasKey("Id") + .HasName("PK_QueueLog"); + + b.ToTable("QueueLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/Postgres/20240310061825_InitQueueLog.cs b/src/platform/mix.database/Migrations/QueueLog/Postgres/20240310061825_InitQueueLog.cs new file mode 100644 index 000000000..c9720cbe6 --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/Postgres/20240310061825_InitQueueLog.cs @@ -0,0 +1,51 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Mix.Database.Migrations.PostgresQueueLogDb +{ + /// + public partial class InitQueueLog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "QueueLog", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"), + QueueMessageId = table.Column(type: "uuid", nullable: true), + TopicId = table.Column(type: "varchar(250)", nullable: true), + SubscriptionId = table.Column(type: "varchar(250)", nullable: true), + Action = table.Column(type: "varchar(250)", nullable: true), + StringData = table.Column(type: "text", nullable: true), + ObjectData = table.Column(type: "text", nullable: true), + Exception = table.Column(type: "text", nullable: true), + Subscriptions = table.Column(type: "text", nullable: true), + DataTypeFullName = table.Column(type: "varchar(250)", nullable: true), + Note = table.Column(type: "varchar(250)", nullable: true), + State = table.Column(type: "varchar(50)", nullable: false), + TenantId = table.Column(type: "integer", nullable: false), + CreatedDateTime = table.Column(type: "timestamp with time zone", nullable: false), + LastModified = table.Column(type: "timestamp with time zone", nullable: true), + CreatedBy = table.Column(type: "varchar(250)", nullable: true), + ModifiedBy = table.Column(type: "varchar(250)", nullable: true), + Priority = table.Column(type: "int", nullable: false), + Status = table.Column(type: "varchar(50)", nullable: false), + IsDeleted = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_QueueLog", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "QueueLog"); + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/Postgres/PostgresQueueLogDbContextModelSnapshot.cs b/src/platform/mix.database/Migrations/QueueLog/Postgres/PostgresQueueLogDbContextModelSnapshot.cs new file mode 100644 index 000000000..f8a7bac8d --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/Postgres/PostgresQueueLogDbContextModelSnapshot.cs @@ -0,0 +1,101 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.QueueLog; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Mix.Database.Migrations.PostgresQueueLogDb +{ + [DbContext(typeof(PostgresQueueLogDbContext))] + partial class PostgresQueueLogDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.QueueLog.QueueLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .HasColumnType("varchar(250)"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("DataTypeFullName") + .HasColumnType("varchar(250)"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Note") + .HasColumnType("varchar(250)"); + + b.Property("ObjectData") + .HasColumnType("text"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueueMessageId") + .HasColumnType("uuid"); + + b.Property("State") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StringData") + .HasColumnType("text"); + + b.Property("SubscriptionId") + .HasColumnType("varchar(250)"); + + b.Property("Subscriptions") + .HasColumnType("text"); + + b.Property("TenantId") + .HasColumnType("integer"); + + b.Property("TopicId") + .HasColumnType("varchar(250)"); + + b.HasKey("Id") + .HasName("PK_QueueLog"); + + b.ToTable("QueueLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/SqlServer/20240310062419_InitQueueLog.Designer.cs b/src/platform/mix.database/Migrations/QueueLog/SqlServer/20240310062419_InitQueueLog.Designer.cs new file mode 100644 index 000000000..700cb0070 --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/SqlServer/20240310062419_InitQueueLog.Designer.cs @@ -0,0 +1,104 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.QueueLog; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Mix.Database.Migrations.SqlServerQueueLogDb +{ + [DbContext(typeof(SqlServerQueueLogDbContext))] + [Migration("20240310062419_InitQueueLog")] + partial class InitQueueLog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.QueueLog.QueueLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .HasColumnType("varchar(250)"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("DataTypeFullName") + .HasColumnType("varchar(250)"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Note") + .HasColumnType("varchar(250)"); + + b.Property("ObjectData") + .HasColumnType("text"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueueMessageId") + .HasColumnType("uuid"); + + b.Property("State") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StringData") + .HasColumnType("text"); + + b.Property("SubscriptionId") + .HasColumnType("varchar(250)"); + + b.Property("Subscriptions") + .HasColumnType("text"); + + b.Property("TenantId") + .HasColumnType("integer"); + + b.Property("TopicId") + .HasColumnType("varchar(250)"); + + b.HasKey("Id") + .HasName("PK_QueueLog"); + + b.ToTable("QueueLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/SqlServer/20240310062419_InitQueueLog.cs b/src/platform/mix.database/Migrations/QueueLog/SqlServer/20240310062419_InitQueueLog.cs new file mode 100644 index 000000000..234a01fd6 --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/SqlServer/20240310062419_InitQueueLog.cs @@ -0,0 +1,51 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Mix.Database.Migrations.SqlServerQueueLogDb +{ + /// + public partial class InitQueueLog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "QueueLog", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"), + QueueMessageId = table.Column(type: "uuid", nullable: true), + TopicId = table.Column(type: "varchar(250)", nullable: true), + SubscriptionId = table.Column(type: "varchar(250)", nullable: true), + Action = table.Column(type: "varchar(250)", nullable: true), + StringData = table.Column(type: "text", nullable: true), + ObjectData = table.Column(type: "text", nullable: true), + Exception = table.Column(type: "text", nullable: true), + Subscriptions = table.Column(type: "text", nullable: true), + DataTypeFullName = table.Column(type: "varchar(250)", nullable: true), + Note = table.Column(type: "varchar(250)", nullable: true), + State = table.Column(type: "varchar(50)", nullable: false), + TenantId = table.Column(type: "integer", nullable: false), + CreatedDateTime = table.Column(type: "timestamp with time zone", nullable: false), + LastModified = table.Column(type: "timestamp with time zone", nullable: true), + CreatedBy = table.Column(type: "varchar(250)", nullable: true), + ModifiedBy = table.Column(type: "varchar(250)", nullable: true), + Priority = table.Column(type: "int", nullable: false), + Status = table.Column(type: "varchar(50)", nullable: false), + IsDeleted = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_QueueLog", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "QueueLog"); + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/SqlServer/SqlServerQueueLogDbContextModelSnapshot.cs b/src/platform/mix.database/Migrations/QueueLog/SqlServer/SqlServerQueueLogDbContextModelSnapshot.cs new file mode 100644 index 000000000..b43055604 --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/SqlServer/SqlServerQueueLogDbContextModelSnapshot.cs @@ -0,0 +1,101 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.QueueLog; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Mix.Database.Migrations.SqlServerQueueLogDb +{ + [DbContext(typeof(SqlServerQueueLogDbContext))] + partial class SqlServerQueueLogDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.QueueLog.QueueLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .HasColumnType("varchar(250)"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("DataTypeFullName") + .HasColumnType("varchar(250)"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Note") + .HasColumnType("varchar(250)"); + + b.Property("ObjectData") + .HasColumnType("text"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueueMessageId") + .HasColumnType("uuid"); + + b.Property("State") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StringData") + .HasColumnType("text"); + + b.Property("SubscriptionId") + .HasColumnType("varchar(250)"); + + b.Property("Subscriptions") + .HasColumnType("text"); + + b.Property("TenantId") + .HasColumnType("integer"); + + b.Property("TopicId") + .HasColumnType("varchar(250)"); + + b.HasKey("Id") + .HasName("PK_QueueLog"); + + b.ToTable("QueueLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/Sqlite/20240310062056_InitQueueLog.Designer.cs b/src/platform/mix.database/Migrations/QueueLog/Sqlite/20240310062056_InitQueueLog.Designer.cs new file mode 100644 index 000000000..b9e9901aa --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/Sqlite/20240310062056_InitQueueLog.Designer.cs @@ -0,0 +1,104 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.QueueLog; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Mix.Database.Migrations.SqlITEQueueLogDb +{ + [DbContext(typeof(SqlITEQueueLogDbContext))] + [Migration("20240310062056_InitQueueLog")] + partial class InitQueueLog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.QueueLog.QueueLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .HasColumnType("varchar(250)"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("DataTypeFullName") + .HasColumnType("varchar(250)"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Note") + .HasColumnType("varchar(250)"); + + b.Property("ObjectData") + .HasColumnType("text"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueueMessageId") + .HasColumnType("uuid"); + + b.Property("State") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StringData") + .HasColumnType("text"); + + b.Property("SubscriptionId") + .HasColumnType("varchar(250)"); + + b.Property("Subscriptions") + .HasColumnType("text"); + + b.Property("TenantId") + .HasColumnType("integer"); + + b.Property("TopicId") + .HasColumnType("varchar(250)"); + + b.HasKey("Id") + .HasName("PK_QueueLog"); + + b.ToTable("QueueLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/Sqlite/20240310062056_InitQueueLog.cs b/src/platform/mix.database/Migrations/QueueLog/Sqlite/20240310062056_InitQueueLog.cs new file mode 100644 index 000000000..d6493ea3b --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/Sqlite/20240310062056_InitQueueLog.cs @@ -0,0 +1,51 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Mix.Database.Migrations.SqlITEQueueLogDb +{ + /// + public partial class InitQueueLog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "QueueLog", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"), + QueueMessageId = table.Column(type: "uuid", nullable: true), + TopicId = table.Column(type: "varchar(250)", nullable: true), + SubscriptionId = table.Column(type: "varchar(250)", nullable: true), + Action = table.Column(type: "varchar(250)", nullable: true), + StringData = table.Column(type: "text", nullable: true), + ObjectData = table.Column(type: "text", nullable: true), + Exception = table.Column(type: "text", nullable: true), + Subscriptions = table.Column(type: "text", nullable: true), + DataTypeFullName = table.Column(type: "varchar(250)", nullable: true), + Note = table.Column(type: "varchar(250)", nullable: true), + State = table.Column(type: "varchar(50)", nullable: false), + TenantId = table.Column(type: "integer", nullable: false), + CreatedDateTime = table.Column(type: "timestamp with time zone", nullable: false), + LastModified = table.Column(type: "timestamp with time zone", nullable: true), + CreatedBy = table.Column(type: "varchar(250)", nullable: true), + ModifiedBy = table.Column(type: "varchar(250)", nullable: true), + Priority = table.Column(type: "int", nullable: false), + Status = table.Column(type: "varchar(50)", nullable: false), + IsDeleted = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_QueueLog", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "QueueLog"); + } + } +} diff --git a/src/platform/mix.database/Migrations/QueueLog/Sqlite/SqlITEQueueLogDbContextModelSnapshot.cs b/src/platform/mix.database/Migrations/QueueLog/Sqlite/SqlITEQueueLogDbContextModelSnapshot.cs new file mode 100644 index 000000000..713fe5586 --- /dev/null +++ b/src/platform/mix.database/Migrations/QueueLog/Sqlite/SqlITEQueueLogDbContextModelSnapshot.cs @@ -0,0 +1,101 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Mix.Database.Entities.QueueLog; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Mix.Database.Migrations.SqlITEQueueLogDb +{ + [DbContext(typeof(SqlITEQueueLogDbContext))] + partial class SqlITEQueueLogDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Mix.Database.Entities.QueueLog.QueueLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .HasColumnType("varchar(250)"); + + b.Property("CreatedBy") + .HasColumnType("varchar(250)"); + + b.Property("CreatedDateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("DataTypeFullName") + .HasColumnType("varchar(250)"); + + b.Property("Exception") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("varchar(250)"); + + b.Property("Note") + .HasColumnType("varchar(250)"); + + b.Property("ObjectData") + .HasColumnType("text"); + + b.Property("Priority") + .HasColumnType("int"); + + b.Property("QueueMessageId") + .HasColumnType("uuid"); + + b.Property("State") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("Status") + .IsRequired() + .HasColumnType("varchar(50)") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("StringData") + .HasColumnType("text"); + + b.Property("SubscriptionId") + .HasColumnType("varchar(250)"); + + b.Property("Subscriptions") + .HasColumnType("text"); + + b.Property("TenantId") + .HasColumnType("integer"); + + b.Property("TopicId") + .HasColumnType("varchar(250)"); + + b.HasKey("Id") + .HasName("PK_QueueLog"); + + b.ToTable("QueueLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/platform/mix.database/Readme.md b/src/platform/mix.database/Readme.md index c8e7bd4b1..9c0abd7ee 100644 --- a/src/platform/mix.database/Readme.md +++ b/src/platform/mix.database/Readme.md @@ -28,4 +28,17 @@ return "Server=localhost;port=3306;Database=mixcore_structure;User=root;Password ``` DatabaseProvider = MixDatabaseProvider.SQLSERVER; return "Server=localhost;Database=mixcore_structure;UID=sa;Pwd=myPassword;MultipleActiveResultSets=true;TrustServerCertificate=True;"; +``` + +``` +Scaffold-DbContext [CONNECTION_STRING] Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models\Cms -force +ex: [CONNECTION_STRING] = "Server=localhost;Database=mixcore_structure;UID=sa;Pwd=myPassword;MultipleActiveResultSets=true;" + +dotnet ef dbcontext scaffold "Host=localhost;Database=mixcore_structure;Username=my_user;Password=myPassword" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models\Cms\PostgreSQL -force +Scaffold-DbContext "Host=localhost;Database=mixcore_structure;Username=postgre;Password=myPassword" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Entities\Cms\PostgreSQL -Context PostgresqlMixCmsContext -f +ex: [CONNECTION_STRING] = "Host=my_host;Database=mixcore_structure;Username=my_user;Password=my_pw" + +Scaffold-DbContext [CONNECTION_STRING] Pomelo.EntityFrameworkCore.MySql -OutputDir [OUTPUT DIRECTORY] -Context [NAME OF CONTEXT CLASS] -f +ex: [CONNECTION_STRING] = "Server=localhost;port=3306;Database=mixcore_structure;User=root;Password=;" + ``` \ No newline at end of file diff --git a/src/platform/mix.database/Services/DatabaseService.cs b/src/platform/mix.database/Services/DatabaseService.cs index 3f4fafc85..af4887a27 100644 --- a/src/platform/mix.database/Services/DatabaseService.cs +++ b/src/platform/mix.database/Services/DatabaseService.cs @@ -1,8 +1,10 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Mix.Database.Entities.Account; +using Mix.Database.Entities.AuditLog; using Mix.Database.Entities.MixDb; using Mix.Database.Entities.Quartz; +using Mix.Database.Entities.QueueLog; using Mix.Heart.Constants; using Mix.Heart.Entities.Cache; using Mix.Heart.Services; @@ -38,6 +40,10 @@ public string GetConnectionString(string name) { case MixConstants.CONST_CMS_CONNECTION: return AppSettings.ConnectionStrings?.MixCmsConnection; + case MixConstants.CONST_AUDIT_LOG_CONNECTION: + return AppSettings.ConnectionStrings?.MixAuditLogConnection; + case MixConstants.CONST_QUEUE_LOG_CONNECTION: + return AppSettings.ConnectionStrings?.MixQueueLogConnection; case MixConstants.CONST_ACCOUNT_CONNECTION: return AppSettings.ConnectionStrings?.MixAccountConnection; case MixConstants.CONST_MIXDB_CONNECTION: @@ -45,7 +51,7 @@ public string GetConnectionString(string name) case MixConstants.CONST_QUARTZ_CONNECTION: return AppSettings.ConnectionStrings?.MixQuartzConnection; default: - return RawSettings.Value("connectionStrings").Value(name) + return RawSettings.Value("connectionStrings").Value(name) ?? Configuration.GetConnectionString(name); } } @@ -122,6 +128,29 @@ public MixCmsAccountContext GetAccountDbContext() }; } + public AuditLogDbContext GetAuditLogDbContext() + { + return DatabaseProvider switch + { + MixDatabaseProvider.SQLSERVER => new SqlServerAuditLogDbContext(this), + MixDatabaseProvider.MySQL => new MySqlAuditLogDbContext(this), + MixDatabaseProvider.SQLITE => new SqlITEAuditLogDbContext(this), + MixDatabaseProvider.PostgreSQL => new PostgresAuditLogDbContext(this), + _ => null, + }; + } + public QueueLogDbContext GetQueueLogDbContext() + { + return DatabaseProvider switch + { + MixDatabaseProvider.SQLSERVER => new SqlServerQueueLogDbContext(this), + MixDatabaseProvider.MySQL => new MySqlQueueLogDbContext(this), + MixDatabaseProvider.SQLITE => new SqlITEQueueLogDbContext(this), + MixDatabaseProvider.PostgreSQL => new PostgresQueueLogDbContext(this), + _ => null, + }; + } + public QuartzDbContext GetQuartzDbContext() { return DatabaseProvider switch @@ -156,12 +185,16 @@ public void InitConnectionStrings(string connectionString, SetConnectionString(MixConstants.CONST_QUARTZ_CONNECTION, connectionString.Replace(".sqlite", "") + "-quartz.sqlite"); SetConnectionString(MixConstants.CONST_ACCOUNT_CONNECTION, connectionString.Replace(".sqlite", "") + "-account.sqlite"); SetConnectionString(MixConstants.CONST_MIXDB_CONNECTION, connectionString.Replace(".sqlite", "") + "-mixdb.sqlite"); + SetConnectionString(MixConstants.CONST_AUDIT_LOG_CONNECTION, connectionString.Replace(".sqlite", "") + "-audit-log.sqlite"); + SetConnectionString(MixConstants.CONST_QUEUE_LOG_CONNECTION, connectionString.Replace(".sqlite", "") + "-queue-log.sqlite"); } else { SetConnectionString(MixConstants.CONST_QUARTZ_CONNECTION, connectionString); SetConnectionString(MixConstants.CONST_ACCOUNT_CONNECTION, connectionString); SetConnectionString(MixConstants.CONST_MIXDB_CONNECTION, connectionString); + SetConnectionString(MixConstants.CONST_AUDIT_LOG_CONNECTION, connectionString); + SetConnectionString(MixConstants.CONST_QUEUE_LOG_CONNECTION, connectionString); } AppSettings.DatabaseProvider = databaseProvider; @@ -193,6 +226,12 @@ public void UpdateMixCmsContext() using var mixdbCtx = GetMixDbDbContext(); if (mixdbCtx.Database.GetPendingMigrations().Count() > 0) mixdbCtx.Database.Migrate(); + using var auditlogCtx = GetAuditLogDbContext(); + if (auditlogCtx.Database.GetPendingMigrations().Count() > 0) + auditlogCtx.Database.Migrate(); + using var queuelogCtx = GetQueueLogDbContext(); + if (queuelogCtx.Database.GetPendingMigrations().Count() > 0) + queuelogCtx.Database.Migrate(); } public async Task InitQuartzContextAsync() diff --git a/src/platform/mix.database/Startup.cs b/src/platform/mix.database/Startup.cs index c37246ef4..810acdc34 100644 --- a/src/platform/mix.database/Startup.cs +++ b/src/platform/mix.database/Startup.cs @@ -1,5 +1,4 @@ using Mix.Database.Entities.Account; -using Mix.Database.Entities.AuditLog; namespace Microsoft.Extensions.DependencyInjection { diff --git a/src/platform/mix.database/mix.database.csproj b/src/platform/mix.database/mix.database.csproj index a84253c13..cc6d04984 100644 --- a/src/platform/mix.database/mix.database.csproj +++ b/src/platform/mix.database/mix.database.csproj @@ -16,10 +16,10 @@ - - - - + + + + @@ -41,7 +41,7 @@ - + diff --git a/src/platform/mix.identity/Dtos/GrantPermissionsDto.cs b/src/platform/mix.identity/Dtos/GrantPermissionsDto.cs new file mode 100644 index 000000000..ddb8484f5 --- /dev/null +++ b/src/platform/mix.identity/Dtos/GrantPermissionsDto.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; + +namespace Mix.Identity.Dtos +{ + public sealed class GrantPermissionsDto + { + public List Permissions { get; set; } + public bool IsActive { get; set; } + public string? RequestedBy { get; set; } + } + public sealed class PermissionDto + { + public Guid RoleId { get; set; } + public int PermissionId { get; set; } + } +} diff --git a/src/platform/mix.identity/Interfaces/IOAuthClientService.cs b/src/platform/mix.identity/Interfaces/IOAuthClientService.cs index e99e104c5..dcb20651e 100644 --- a/src/platform/mix.identity/Interfaces/IOAuthClientService.cs +++ b/src/platform/mix.identity/Interfaces/IOAuthClientService.cs @@ -7,6 +7,6 @@ public interface IOAuthClientService { List Clients { get; set; } - List LoadClients(bool isReload = false); + List LoadClients(MixCmsAccountContext accContext, bool isReload = false); } } \ No newline at end of file diff --git a/src/platform/mix.identity/Interfaces/IOAuthTokenRevocationService.cs b/src/platform/mix.identity/Interfaces/IOAuthTokenRevocationService.cs index e2a5e6ecd..63f1a903e 100644 --- a/src/platform/mix.identity/Interfaces/IOAuthTokenRevocationService.cs +++ b/src/platform/mix.identity/Interfaces/IOAuthTokenRevocationService.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Http; -using Mix.Auth.Models.OAuthResponses; using System.Threading.Tasks; namespace Mix.Identity.Interfaces diff --git a/src/platform/mix.identity/Interfaces/IOAuthTokenService.cs b/src/platform/mix.identity/Interfaces/IOAuthTokenService.cs index ea3b40f17..cc0bc178a 100644 --- a/src/platform/mix.identity/Interfaces/IOAuthTokenService.cs +++ b/src/platform/mix.identity/Interfaces/IOAuthTokenService.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Http; using Mix.Auth.Models; -using Mix.Auth.Models.OAuthRequests; using Mix.Database.Entities.Account; using System.Collections.Generic; @@ -10,6 +9,6 @@ public interface IOAuthTokenService { AuthorizeResponse AuthorizeRequest(IHttpContextAccessor httpContextAccessor, OAuthRequest authorizationRequest); TokenResult GenerateJWTToken(IEnumerable scopes, string tokenType, OAuthClient client); - TokenResponse GenerateToken(OAuthTokenRequest tokenRequest); + OAuthTokenResponse GenerateToken(OAuthTokenRequest tokenRequest); } } \ No newline at end of file diff --git a/src/platform/mix.identity/Models/JwtSecurityKey.cs b/src/platform/mix.identity/Models/JwtSecurityKey.cs index 13a266ec6..43f3b930c 100644 --- a/src/platform/mix.identity/Models/JwtSecurityKey.cs +++ b/src/platform/mix.identity/Models/JwtSecurityKey.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Identity.Models +namespace Mix.Identity.Models { internal class JwtSecurityKey { diff --git a/src/platform/mix.identity/Models/RoleBOModel.cs b/src/platform/mix.identity/Models/RoleBOModel.cs new file mode 100644 index 000000000..08db5b9e6 --- /dev/null +++ b/src/platform/mix.identity/Models/RoleBOModel.cs @@ -0,0 +1,16 @@ +using Mix.Database.Entities.Account; +using System; +using System.Collections.Generic; + +namespace Mix.Identity.Models +{ + public sealed class RoleBOModel + { + public Guid Id { get; set; } + public string Name { get; set; } + public string NormalizedName { get; set; } + public string ConcurrencyStamp { get; set; } + + public List Permissions { get; set; } + } +} diff --git a/src/platform/mix.identity/Services/OAuthClientService.cs b/src/platform/mix.identity/Services/OAuthClientService.cs index fbef3ff7d..e5023427a 100644 --- a/src/platform/mix.identity/Services/OAuthClientService.cs +++ b/src/platform/mix.identity/Services/OAuthClientService.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Identity.Services { @@ -17,21 +15,22 @@ public sealed class OAuthClientService : IOAuthClientService public OAuthClientService(IServiceProvider serviceProvider) { this._serviceProvider = serviceProvider; - LoadClients(); + + using (var scope = _serviceProvider.CreateScope()) + { + var accContext = scope.ServiceProvider.GetService(); + LoadClients(accContext); + } } - public List LoadClients(bool isReload = false) + public List LoadClients(MixCmsAccountContext accContext, bool isReload = false) { - using (var scope = _serviceProvider.CreateScope()) + if (isReload || Clients == null) { - var _accContext = scope.ServiceProvider.GetService(); - if (isReload || Clients == null) - { - Clients = _accContext.OAuthClient.ToList(); - } - _accContext.Dispose(); - return Clients; + Clients = accContext.OAuthClient.ToList(); + accContext.Dispose(); } + return Clients; } } } diff --git a/src/platform/mix.identity/Services/OAuthTokenRevocationService.cs b/src/platform/mix.identity/Services/OAuthTokenRevocationService.cs index 8d8534eb0..93aa71cd0 100644 --- a/src/platform/mix.identity/Services/OAuthTokenRevocationService.cs +++ b/src/platform/mix.identity/Services/OAuthTokenRevocationService.cs @@ -1,11 +1,10 @@ using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; +using Mix.Auth.Common; using Mix.Database.Entities.Account; using Mix.Identity.Interfaces; -using Mix.Auth.Models.OAuthResponses; -using System.Threading.Tasks; using System.Linq; -using Mix.Auth.Common; +using System.Threading.Tasks; namespace Mix.Identity.Services { diff --git a/src/platform/mix.identity/Services/OAuthTokenService.cs b/src/platform/mix.identity/Services/OAuthTokenService.cs index cb87618f0..20d4302f5 100644 --- a/src/platform/mix.identity/Services/OAuthTokenService.cs +++ b/src/platform/mix.identity/Services/OAuthTokenService.cs @@ -1,7 +1,12 @@ using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; +using Mix.Auth.Common; +using Mix.Auth.Enums; +using Mix.Auth.Models; using Mix.Database.Entities.Account; +using Mix.Identity.Interfaces; using Mix.Shared.Models.Configurations; using System; using System.Collections.Generic; @@ -10,11 +15,6 @@ using System.Security.Claims; using System.Security.Cryptography; using System.Text; -using Microsoft.Extensions.Configuration; -using Mix.Auth.Models; -using Mix.Identity.Interfaces; -using Mix.Auth.Common; -using Mix.Auth.Enums; namespace Mix.Identity.Services { @@ -24,7 +24,6 @@ public sealed class OAuthTokenService : IOAuthTokenService private readonly IOAuthClientService _clientService; private readonly IOAuthCodeStoreService _codeStoreService; private readonly OAuthServerOptions _options; - private readonly MixCmsAccountContext _context; private readonly MixAuthenticationConfigurations _authConfigs; public OAuthTokenService(IOAuthCodeStoreService codeStoreService, @@ -163,16 +162,16 @@ private CheckOAuthClientResult VerifyClientById(Guid clientId, bool checkWithSec } - public TokenResponse GenerateToken(OAuthTokenRequest tokenRequest) + public OAuthTokenResponse GenerateToken(OAuthTokenRequest tokenRequest) { - var result = new TokenResponse(); + var result = new OAuthTokenResponse(); var serchBySecret = SearchForClientBySecret(tokenRequest.grant_type); var checkClientResult = VerifyClientById(tokenRequest.client_id, serchBySecret, tokenRequest.client_secret, tokenRequest.grant_type); if (!checkClientResult.IsSuccess) { - return new TokenResponse { Error = checkClientResult.Error, ErrorDescription = checkClientResult.ErrorDescription }; + return new OAuthTokenResponse { Error = checkClientResult.Error, ErrorDescription = checkClientResult.ErrorDescription }; } // Check first if the authorization_grant is client_credentials... @@ -190,6 +189,7 @@ public TokenResponse GenerateToken(OAuthTokenRequest tokenRequest) var clientCredentialAccessTokenResult = GenerateJWTToken(scopes, OAuthConstants.TokenTypes.JWTAcceseccToken, checkClientResult.Client); result.access_token = clientCredentialAccessTokenResult.AccessToken; + result.expired_at = clientCredentialAccessTokenResult.ExpirationDate; result.id_token = null; // I have to use data shaping here to remove this property or I can customize the return data in the json result, but for now null is ok. result.code = tokenRequest.code; return result; @@ -199,13 +199,13 @@ public TokenResponse GenerateToken(OAuthTokenRequest tokenRequest) // check code from the Concurrent Dictionary var clientCodeChecker = _codeStoreService.GetClientDataByCode(tokenRequest.code); if (clientCodeChecker == null) - return new TokenResponse { Error = ErrorTypeEnum.InvalidGrant.GetEnumDescription() }; + return new OAuthTokenResponse { Error = ErrorTypeEnum.InvalidGrant.GetEnumDescription() }; // check if the current client who is one made this authentication request if (tokenRequest.client_id != clientCodeChecker.ClientId) - return new TokenResponse { Error = ErrorTypeEnum.InvalidGrant.GetEnumDescription() }; + return new OAuthTokenResponse { Error = ErrorTypeEnum.InvalidGrant.GetEnumDescription() }; // TODO: // also I have to check the rediret uri @@ -217,7 +217,7 @@ public TokenResponse GenerateToken(OAuthTokenRequest tokenRequest) clientCodeChecker.CodeChallenge, clientCodeChecker.CodeChallengeMethod); if (!pkceResult) - return new TokenResponse { Error = ErrorTypeEnum.InvalidGrant.GetEnumDescription() }; + return new OAuthTokenResponse { Error = ErrorTypeEnum.InvalidGrant.GetEnumDescription() }; } @@ -226,14 +226,14 @@ public TokenResponse GenerateToken(OAuthTokenRequest tokenRequest) { if (!clientCodeChecker.Subject.Identity!.IsAuthenticated) // I have to inform the caller to redirect the user to the login page - return new TokenResponse { Error = ErrorTypeEnum.InvalidGrant.GetEnumDescription() }; + return new OAuthTokenResponse { Error = ErrorTypeEnum.InvalidGrant.GetEnumDescription() }; var currentUserName = clientCodeChecker.Subject.Identity.Name; var userId = clientCodeChecker.Subject.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(currentUserName)) - return new TokenResponse { Error = ErrorTypeEnum.InvalidGrant.GetEnumDescription() }; + return new OAuthTokenResponse { Error = ErrorTypeEnum.InvalidGrant.GetEnumDescription() }; // Generate Identity Token int iat = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; diff --git a/src/platform/mix.identity/ViewModels/OAuthClientViewModel.cs b/src/platform/mix.identity/ViewModels/OAuthClientViewModel.cs index 670e83db4..6d45458b3 100644 --- a/src/platform/mix.identity/ViewModels/OAuthClientViewModel.cs +++ b/src/platform/mix.identity/ViewModels/OAuthClientViewModel.cs @@ -2,9 +2,6 @@ using Mix.Shared.Enums; using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Identity.ViewModels { diff --git a/src/platform/mix.identity/ViewModels/PermissionViewModel.cs b/src/platform/mix.identity/ViewModels/PermissionViewModel.cs new file mode 100644 index 000000000..c57323611 --- /dev/null +++ b/src/platform/mix.identity/ViewModels/PermissionViewModel.cs @@ -0,0 +1,32 @@ +using Mix.Database.Entities.Account; + +namespace Mix.Identity.ViewModels +{ + public class PermissionViewModel : ViewModelBase + { + #region Contructors + + public PermissionViewModel() + { + } + public PermissionViewModel(UnitOfWorkInfo unitOfWorkInfo) : base(unitOfWorkInfo) + { + } + + public PermissionViewModel(Permission entity, UnitOfWorkInfo uowInfo) : base(entity, uowInfo) + { + } + + #endregion + + #region Properties + + public int MixTenantId { get; set; } + public string Title { get; set; } + public string Name { get; set; } + public string Icon { get; set; } + public string Type { get; set; } + + #endregion + } +} diff --git a/src/platform/mix.identity/mix.identity.csproj b/src/platform/mix.identity/mix.identity.csproj index ce3fdc1ac..d7b3b691d 100644 --- a/src/platform/mix.identity/mix.identity.csproj +++ b/src/platform/mix.identity/mix.identity.csproj @@ -21,16 +21,15 @@ - - - - - - - + + + + + + - + diff --git a/src/platform/mix.library/Attributes/CacheWebApiAttribute.cs b/src/platform/mix.library/Attributes/CacheWebApiAttribute.cs index 9d3156e42..2b5ccc7bf 100644 --- a/src/platform/mix.library/Attributes/CacheWebApiAttribute.cs +++ b/src/platform/mix.library/Attributes/CacheWebApiAttribute.cs @@ -1,11 +1,5 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Filters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; namespace Mix.Lib.Attributes { diff --git a/src/platform/mix.library/Attributes/MixAuthorizeAttribute.cs b/src/platform/mix.library/Attributes/MixAuthorizeAttribute.cs index f34eaad17..269209ffd 100644 --- a/src/platform/mix.library/Attributes/MixAuthorizeAttribute.cs +++ b/src/platform/mix.library/Attributes/MixAuthorizeAttribute.cs @@ -48,7 +48,7 @@ public void OnAuthorization(AuthorizationFilterContext context) if (!IsInRoles()) { //_logger.LogError("Not in role"); - if (!ValidEnpointPermission(context)) + if (!ValidEndpointPermission(context)) { //_logger.LogError("forbidden"); context.Result = new ForbidResult(); @@ -66,7 +66,7 @@ public void OnAuthorization(AuthorizationFilterContext context) #region Privates - private bool ValidEnpointPermission(AuthorizationFilterContext context) + private bool ValidEndpointPermission(AuthorizationFilterContext context) { return _permissionService.CheckEndpointPermissionAsync(UserRoles, context.HttpContext.Request.Path, context.HttpContext.Request.Method).Result; } diff --git a/src/platform/mix.library/Base/MixAssociationApiControllerBase.cs b/src/platform/mix.library/Base/MixAssociationApiControllerBase.cs index ab3af0373..ede8e72e1 100644 --- a/src/platform/mix.library/Base/MixAssociationApiControllerBase.cs +++ b/src/platform/mix.library/Base/MixAssociationApiControllerBase.cs @@ -19,8 +19,8 @@ public class MixAssociationApiControllerBase { public MixAssociationApiControllerBase(IHttpContextAccessor httpContextAccessor, IConfiguration configuration, MixCacheService cacheService, TranslatorService translator, MixIdentityService mixIdentityService, UnitOfWorkInfo uow, IMemoryQueueService queueService, IPortalHubClientService portalHub, - IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + IMixTenantService mixTenantService) + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { } diff --git a/src/platform/mix.library/Base/MixBaseContentController.cs b/src/platform/mix.library/Base/MixBaseContentController.cs index 001fdf01b..91ed9f62d 100644 --- a/src/platform/mix.library/Base/MixBaseContentController.cs +++ b/src/platform/mix.library/Base/MixBaseContentController.cs @@ -34,7 +34,7 @@ protected MixBaseContentController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cmsUow, queueService, portalHub, mixTenantService) { ContentType = contentType; diff --git a/src/platform/mix.library/Base/MixControllerBase.cs b/src/platform/mix.library/Base/MixControllerBase.cs index d0b42fb6e..f7fd25ac1 100644 --- a/src/platform/mix.library/Base/MixControllerBase.cs +++ b/src/platform/mix.library/Base/MixControllerBase.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Mix.Lib.Interfaces; using Mix.Shared.Models.Configurations; -using RepoDb; using System.Globalization; namespace Mix.Lib.Base @@ -105,7 +104,7 @@ public override Task OnActionExecutionAsync(ActionExecutingContext context, Acti public override void OnActionExecuting(ActionExecutingContext context) { ValidateRequest(); - + if (!string.IsNullOrEmpty(Culture)) { ViewData["Culture"] = Culture; diff --git a/src/platform/mix.library/Base/MixQueryApiControllerBase.cs b/src/platform/mix.library/Base/MixQueryApiControllerBase.cs index 3c3a1b5a1..468b42027 100644 --- a/src/platform/mix.library/Base/MixQueryApiControllerBase.cs +++ b/src/platform/mix.library/Base/MixQueryApiControllerBase.cs @@ -26,7 +26,7 @@ public MixQueryApiControllerBase( UnitOfWorkInfo uow, IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { } diff --git a/src/platform/mix.library/Base/MixQueryEntityApiControllerBase.cs b/src/platform/mix.library/Base/MixQueryEntityApiControllerBase.cs index 320151d60..f4b284458 100644 --- a/src/platform/mix.library/Base/MixQueryEntityApiControllerBase.cs +++ b/src/platform/mix.library/Base/MixQueryEntityApiControllerBase.cs @@ -32,7 +32,7 @@ public MixQueryEntityApiControllerBase( TDbContext context, IMemoryQueueService queueService, MixCacheDbContext cacheDbContext, IMixTenantService mixTenantService) - : base(httpContextAccessor, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, queueService, mixTenantService) { Context = context; @@ -64,28 +64,19 @@ public override void OnActionExecuted(ActionExecutedContext context) [HttpGet] public virtual async Task>> Get([FromQuery] SearchRequestDto req) + { + var result = await GetHandler(req); + return Ok(result); + } + + protected virtual async Task> GetHandler(SearchRequestDto req) { var searchRequest = BuildSearchRequest(req); if (!string.IsNullOrEmpty(req.Columns)) { Repository.SetSelectedMembers(req.Columns.Replace(" ", string.Empty).Split(',')); } - var result = await Repository.GetPagingAsync(searchRequest.Predicate, searchRequest.PagingData); - if (!string.IsNullOrEmpty(req.Columns)) - { - List objects = new(); - foreach (var item in result.Items) - { - objects.Add(ReflectionHelper.GetMembers(item, Repository.SelectedMembers)); - } - return Ok(new PagingResponseModel() - { - Items = objects, - PagingData = result.PagingData - }); - } - - return result; + return await Repository.GetPagingAsync(searchRequest.Predicate, searchRequest.PagingData); } [HttpGet("{id}")] diff --git a/src/platform/mix.library/Base/MixRestApiControllerBase.cs b/src/platform/mix.library/Base/MixRestApiControllerBase.cs index c2cb5235f..c55665850 100644 --- a/src/platform/mix.library/Base/MixRestApiControllerBase.cs +++ b/src/platform/mix.library/Base/MixRestApiControllerBase.cs @@ -30,7 +30,7 @@ public MixRestHandlerApiControllerBase( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, queueService, mixTenantService) { Context = (TDbContext)uow.ActiveDbContext; diff --git a/src/platform/mix.library/Base/MixRestfulApiControllerBase.cs b/src/platform/mix.library/Base/MixRestfulApiControllerBase.cs index 8de3707a8..ba91027ba 100644 --- a/src/platform/mix.library/Base/MixRestfulApiControllerBase.cs +++ b/src/platform/mix.library/Base/MixRestfulApiControllerBase.cs @@ -31,7 +31,7 @@ public MixRestfulApiControllerBase( UnitOfWorkInfo uow, IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { } diff --git a/src/platform/mix.library/Controllers/MixAutoGenerateAuthorizedQueryApiController.cs b/src/platform/mix.library/Controllers/MixAutoGenerateAuthorizedQueryApiController.cs index f48b99c3f..4542435da 100644 --- a/src/platform/mix.library/Controllers/MixAutoGenerateAuthorizedQueryApiController.cs +++ b/src/platform/mix.library/Controllers/MixAutoGenerateAuthorizedQueryApiController.cs @@ -26,7 +26,7 @@ public MixAutoGenerateAuthorizedQueryApiController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { } diff --git a/src/platform/mix.library/Controllers/MixAutoGenerateAuthorizedRestApiController.cs b/src/platform/mix.library/Controllers/MixAutoGenerateAuthorizedRestApiController.cs index 5e6b767c7..0b27bd0c9 100644 --- a/src/platform/mix.library/Controllers/MixAutoGenerateAuthorizedRestApiController.cs +++ b/src/platform/mix.library/Controllers/MixAutoGenerateAuthorizedRestApiController.cs @@ -28,7 +28,7 @@ public MixAutoGenerateAuthorizedRestApiController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { } diff --git a/src/platform/mix.library/Controllers/MixAutoGenerateQueryApiController.cs b/src/platform/mix.library/Controllers/MixAutoGenerateQueryApiController.cs index 978f96461..78e7c17e7 100644 --- a/src/platform/mix.library/Controllers/MixAutoGenerateQueryApiController.cs +++ b/src/platform/mix.library/Controllers/MixAutoGenerateQueryApiController.cs @@ -25,7 +25,7 @@ public MixAutoGenerateQueryApiController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { } diff --git a/src/platform/mix.library/Controllers/MixAutoGenerateRestApiController.cs b/src/platform/mix.library/Controllers/MixAutoGenerateRestApiController.cs index 1cc5cd1a3..f4dc21683 100644 --- a/src/platform/mix.library/Controllers/MixAutoGenerateRestApiController.cs +++ b/src/platform/mix.library/Controllers/MixAutoGenerateRestApiController.cs @@ -19,8 +19,8 @@ public class MixAutoGenerateRestApiController uow, IMemoryQueueService queueService, IPortalHubClientService portalHub, - IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + IMixTenantService mixTenantService) + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { } diff --git a/src/platform/mix.library/Conventions/ControllerDocumentationConvention.cs b/src/platform/mix.library/Conventions/ControllerDocumentationConvention.cs index 7a3be330c..bdd2e5fca 100644 --- a/src/platform/mix.library/Conventions/ControllerDocumentationConvention.cs +++ b/src/platform/mix.library/Conventions/ControllerDocumentationConvention.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc.ApplicationModels; -using Mix.Heart.Extensions; namespace Mix.Lib.Conventions { diff --git a/src/platform/mix.library/Filters/HttpResponseExceptionFilter.cs b/src/platform/mix.library/Filters/HttpResponseExceptionFilter.cs index 79586dcfd..719da32a3 100644 --- a/src/platform/mix.library/Filters/HttpResponseExceptionFilter.cs +++ b/src/platform/mix.library/Filters/HttpResponseExceptionFilter.cs @@ -15,33 +15,34 @@ public void OnActionExecuted(ActionExecutedContext context) if (context.Exception != null) { - var auditlogData = context.HttpContext.RequestServices.GetService(typeof(AuditLogDataModel)) as AuditLogDataModel; - auditlogData.Exception = ReflectionHelper.ParseObject(context.Exception); + var auditLogData = context.HttpContext.RequestServices.GetService(typeof(AuditLogDataModel)) as AuditLogDataModel; + auditLogData.Exception = ReflectionHelper.ParseObject(context.Exception); if (context.Exception is MixException exception) { + var result = new ExceptionResponseResult(exception.GetType().Name, exception.Errors, exception.Message, exception.StackTrace); context.Result = exception.Status switch { - MixErrorStatus.UnAuthorized => new UnauthorizedObjectResult(exception.Errors) + MixErrorStatus.UnAuthorized => new UnauthorizedObjectResult(result) { StatusCode = (int)exception.Status, }, MixErrorStatus.Forbidden => new ForbidResult() { }, - MixErrorStatus.Badrequest => new BadRequestObjectResult(exception.Errors) + MixErrorStatus.Badrequest => new BadRequestObjectResult(result) { StatusCode = (int)exception.Status, }, - MixErrorStatus.ServerError => new ObjectResult(exception.Errors) + MixErrorStatus.ServerError => new ObjectResult(result) { StatusCode = (int)exception.Status, }, - MixErrorStatus.NotFound => new NotFoundObjectResult(exception.Errors) + MixErrorStatus.NotFound => new NotFoundObjectResult(result) { StatusCode = (int)exception.Status, }, - _ => new ObjectResult(exception.Value) + _ => new ObjectResult(result) { StatusCode = (int)exception.Status, }, @@ -50,7 +51,15 @@ public void OnActionExecuted(ActionExecutedContext context) } context.ExceptionHandled = true; } - + } } + + public class ExceptionResponseResult(string code, string[] errors, string message, string stackTrace) + { + public string Code { get; set; } = code; + public string Message { get; set; } = message; // TODO: must be ignored in production + public string[] Errors { get; set; } = errors; + public string StackTrace { get; set; } = stackTrace; // TODO: must be ignored in production + } } diff --git a/src/platform/mix.library/Helpers/MixCmsHelper.cs b/src/platform/mix.library/Helpers/MixCmsHelper.cs index 2fc54dfff..103284ac9 100644 --- a/src/platform/mix.library/Helpers/MixCmsHelper.cs +++ b/src/platform/mix.library/Helpers/MixCmsHelper.cs @@ -73,21 +73,21 @@ public static WebApplicationBuilder CreateWebApplicationBuilder(string[] args) builder.WebHost.UseContentRoot(Directory.GetCurrentDirectory()); builder.Configuration - .AddJsonFile("appsettings.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/global.json", true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/ocelot.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/storage.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/azure.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/queue.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/mix_heart.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/authentication.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/google_credential.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/google_firebase.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/smtp.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/payments.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/redis.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/log.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/rate_limit.json",true, true) + .AddJsonFile("appsettings.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/global.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/ocelot.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/storage.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/azure.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/queue.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/mix_heart.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/authentication.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/google_credential.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/google_firebase.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/smtp.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/payments.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/redis.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/log.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/rate_limit.json", true, false) .AddEnvironmentVariables(); return builder; } @@ -107,21 +107,21 @@ public static IHostBuilder CreateHostBuilder(string[] args) where TSta { config .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) - .AddJsonFile("appsettings.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/global.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/azure.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/ocelot.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/storage.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/queue.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/mix_heart.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/authentication.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/google_credential.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/google_firebase.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/smtp.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/payments.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/redis.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/log.json",true, true) - .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/rate_limit.json",true, true) + .AddJsonFile("appsettings.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/global.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/azure.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/ocelot.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/storage.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/queue.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/mix_heart.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/authentication.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/google_credential.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/google_firebase.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/smtp.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/payments.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/redis.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/log.json", true, false) + .AddJsonFile($"{Environment.CurrentDirectory}/{MixAppConfigFilePaths.Shared}/appconfigs/rate_limit.json", true, false) .AddEnvironmentVariables(); }) .ConfigureWebHostDefaults(webBuilder => @@ -276,7 +276,7 @@ public static List LoadExcelFileData(IFormFile file) return excelData; } } - + } } } diff --git a/src/platform/mix.library/Middlewares/AuditlogMiddleware.cs b/src/platform/mix.library/Middlewares/AuditlogMiddleware.cs index 4cbcebd49..510f9c3e7 100644 --- a/src/platform/mix.library/Middlewares/AuditlogMiddleware.cs +++ b/src/platform/mix.library/Middlewares/AuditlogMiddleware.cs @@ -4,9 +4,7 @@ using Mix.Lib.Services; using Mix.Log.Lib.Interfaces; using Mix.Log.Lib.Models; -using Mix.Service.Interfaces; using Mix.Shared.Models.Configurations; -using System.Configuration; using System.Text; namespace Mix.Lib.Middlewares diff --git a/src/platform/mix.library/Models/Common/SearchPostQueryModel.cs b/src/platform/mix.library/Models/Common/SearchPostQueryModel.cs index c5f39082d..1ce2cd82e 100644 --- a/src/platform/mix.library/Models/Common/SearchPostQueryModel.cs +++ b/src/platform/mix.library/Models/Common/SearchPostQueryModel.cs @@ -27,7 +27,7 @@ private void ApplyMetadataFilter(HttpRequest httpRequest) { string seoContent = arr[2]; var contents = httpRequest.Query[key].ToString().TrimEnd(',').Split(',', StringSplitOptions.TrimEntries); - + MetadataQueries.Add(new() { FieldName = seoContent, diff --git a/src/platform/mix.library/Models/Common/SiteMapModels.cs b/src/platform/mix.library/Models/Common/SiteMapModels.cs index 04d80dce0..a72a73e91 100644 --- a/src/platform/mix.library/Models/Common/SiteMapModels.cs +++ b/src/platform/mix.library/Models/Common/SiteMapModels.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml.Linq; +using System.Xml.Linq; namespace Mix.Lib.Models.Common { diff --git a/src/platform/mix.library/Policies/OutputCacheWithAuthPolicy.cs b/src/platform/mix.library/Policies/OutputCacheWithAuthPolicy.cs index 69cec6c12..b57c2419a 100644 --- a/src/platform/mix.library/Policies/OutputCacheWithAuthPolicy.cs +++ b/src/platform/mix.library/Policies/OutputCacheWithAuthPolicy.cs @@ -1,10 +1,5 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.OutputCaching; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Lib.Policies { diff --git a/src/platform/mix.library/Publishers/MixPublisher.cs b/src/platform/mix.library/Publishers/MixPublisher.cs index acea1ae20..c133972c2 100644 --- a/src/platform/mix.library/Publishers/MixPublisher.cs +++ b/src/platform/mix.library/Publishers/MixPublisher.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.ObjectPool; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; -using Mix.Queue.Engines.MixQueue; using Mix.RepoDb.Publishers; using RabbitMQ.Client; diff --git a/src/platform/mix.library/Publishers/MixViewModelChangedPublisher.cs b/src/platform/mix.library/Publishers/MixViewModelChangedPublisher.cs index 501cf1498..3f890bbcb 100644 --- a/src/platform/mix.library/Publishers/MixViewModelChangedPublisher.cs +++ b/src/platform/mix.library/Publishers/MixViewModelChangedPublisher.cs @@ -3,8 +3,6 @@ using Microsoft.Extensions.ObjectPool; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; -using Mix.Queue.Engines.MixQueue; -using Mix.RepoDb.Publishers; namespace Mix.Lib.Publishers { diff --git a/src/platform/mix.library/Readme.md b/src/platform/mix.library/Readme.md index 157df01c1..55023882e 100644 --- a/src/platform/mix.library/Readme.md +++ b/src/platform/mix.library/Readme.md @@ -4,3 +4,4 @@ TView vm = new(); vm.SetDbContext(injectedContext); ``` + diff --git a/src/platform/mix.library/Services/MixCmsService.cs b/src/platform/mix.library/Services/MixCmsService.cs index 03f3984a2..0f5f8410b 100644 --- a/src/platform/mix.library/Services/MixCmsService.cs +++ b/src/platform/mix.library/Services/MixCmsService.cs @@ -1,7 +1,5 @@ using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore.Storage; using Mix.Database.Entities.MixDb; -using Mix.Identity.ViewModels; using Mix.Lib.Interfaces; using Mix.Lib.Models.Common; using Mix.Mixdb.ViewModels; diff --git a/src/platform/mix.library/Services/MixConfigurationService.cs b/src/platform/mix.library/Services/MixConfigurationService.cs index f850a6492..a6f5d8cfe 100644 --- a/src/platform/mix.library/Services/MixConfigurationService.cs +++ b/src/platform/mix.library/Services/MixConfigurationService.cs @@ -12,9 +12,9 @@ public sealed class MixConfigurationService : TenantServiceBase, IMixConfigurati public List Configs { get; set; } public MixConfigurationService( - IHttpContextAccessor httpContextAccessor, + IHttpContextAccessor httpContextAccessor, DatabaseService databaseService, MixCacheService cacheService, - IMixTenantService mixTenantService) + IMixTenantService mixTenantService) : base(httpContextAccessor, cacheService, mixTenantService) { _databaseService = databaseService; @@ -80,7 +80,7 @@ public async Task GetConfig(string name, string culture, T defaultValue = await Reload(); } var config = Configs.FirstOrDefault(m => m.Specificulture == culture && m.SystemName == name); - return config != null ? config.GetValue(): defaultValue; + return config != null ? config.GetValue() : defaultValue; } } } diff --git a/src/platform/mix.library/Services/MixEdmService.cs b/src/platform/mix.library/Services/MixEdmService.cs index 40e8e9855..a55153d43 100644 --- a/src/platform/mix.library/Services/MixEdmService.cs +++ b/src/platform/mix.library/Services/MixEdmService.cs @@ -23,7 +23,7 @@ public MixEdmService( public async Task GetEdmTemplate(string filename) { - if (_uow == null ) + if (_uow == null) { return string.Empty; } @@ -64,7 +64,7 @@ public virtual async Task SendMailWithEdmTemplate( }; _queueService.PushMemoryQueue(CurrentTenant.Id, MixQueueTopics.MixBackgroundTasks, MixQueueActions.SendMail, msg); } - + public virtual async Task SendMailWithTemplate( string subject, string template, JObject data, string to, diff --git a/src/platform/mix.library/Services/MixIdentityService.cs b/src/platform/mix.library/Services/MixIdentityService.cs index 5b29fde41..12d1a1be1 100644 --- a/src/platform/mix.library/Services/MixIdentityService.cs +++ b/src/platform/mix.library/Services/MixIdentityService.cs @@ -169,7 +169,7 @@ public virtual async Task LoginAsync(LoginRequestModel model, Cancellat { throw; } - catch(Exception ex) + catch (Exception ex) { throw new MixException(MixErrorStatus.ServerError, ex); } @@ -534,7 +534,7 @@ public async Task VerifyExternalAccessTokenAsync( return parsedToken; } - public async Task GenerateTokenAsync( + public virtual async Task GenerateTokenAsync( MixUser user, JObject info, DateTime expires, diff --git a/src/platform/mix.library/Services/MixThemeImportService.cs b/src/platform/mix.library/Services/MixThemeImportService.cs index f3dff291a..a2ef39c69 100644 --- a/src/platform/mix.library/Services/MixThemeImportService.cs +++ b/src/platform/mix.library/Services/MixThemeImportService.cs @@ -1,8 +1,4 @@ -using DocumentFormat.OpenXml.Vml; -using DocumentFormat.OpenXml.Wordprocessing; -using Google.Protobuf.WellKnownTypes; -using Humanizer; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Mix.Database.Base; @@ -18,7 +14,7 @@ namespace Mix.Lib.Services public class MixThemeImportService : IMixThemeImportService { private MixRepoDbRepository _repository { get; set; } - private MixCacheService _cacheService{ get; set; } + private MixCacheService _cacheService { get; set; } private readonly CancellationTokenSource _cts; private readonly DatabaseService _databaseService; private readonly IDatabaseConstants _databaseConstant; @@ -107,22 +103,15 @@ public Task LoadSchema() public async Task LoadSchema(string folder) { - try - { - using (var serviceScope = _serviceProvider.CreateScope()) - { - _uow = serviceScope.ServiceProvider.GetRequiredService>(); - _context = _uow.DbContext; - var strSchema = MixFileHelper.GetFile(MixThemePackageConstants.SchemaFilename, MixFileExtensions.Json, folder); - var siteStructures = JObject.Parse(strSchema.Content).ToObject(); - await ValidateSiteData(siteStructures); - serviceScope.Dispose(); - return siteStructures; - } - } - catch(Exception ex) + using (var serviceScope = _serviceProvider.CreateScope()) { - throw new MixException(MixErrorStatus.ServerError, ex); + _uow = serviceScope.ServiceProvider.GetRequiredService>(); + _context = _uow.DbContext; + var strSchema = MixFileHelper.GetFile(MixThemePackageConstants.SchemaFilename, MixFileExtensions.Json, folder); + var siteStructures = JObject.Parse(strSchema.Content).ToObject(); + await ValidateSiteData(siteStructures); + serviceScope.Dispose(); + return siteStructures; } } diff --git a/src/platform/mix.library/Services/RestApiService.cs b/src/platform/mix.library/Services/RestApiService.cs index 9ca280777..2db968a9f 100644 --- a/src/platform/mix.library/Services/RestApiService.cs +++ b/src/platform/mix.library/Services/RestApiService.cs @@ -7,7 +7,6 @@ using Mix.SignalR.Enums; using Mix.SignalR.Interfaces; using Mix.SignalR.Models; -using NuGet.Protocol; namespace Mix.Lib.Services { diff --git a/src/platform/mix.library/Startup/AuthServiceCollectionExtensions.cs b/src/platform/mix.library/Startup/AuthServiceCollectionExtensions.cs index f39129673..de4a6ab6e 100644 --- a/src/platform/mix.library/Startup/AuthServiceCollectionExtensions.cs +++ b/src/platform/mix.library/Startup/AuthServiceCollectionExtensions.cs @@ -17,7 +17,6 @@ using Mix.Identity.Services; using Mix.Lib.Services; using Mix.Shared.Models.Configurations; -using System.Reflection; using System.Text; namespace Microsoft.Extensions.DependencyInjection { @@ -27,15 +26,25 @@ public static class AuthServiceCollectionExtensions public static IServiceCollection AddMixAuthorize(this IServiceCollection services, IConfiguration configuration) where TDbContext : DbContext { - AuthConfigService authConfigService = services.GetService(); var _globalConfig = configuration.Get()!; + var authConfigService = services.GetService(); if (_globalConfig.IsInit) { authConfigService.AppSettings.SecretKey = Guid.NewGuid().ToString("N"); authConfigService.SaveSettings(); } + services.AddMixIdentityConfigurations(configuration); - var authConfigurations = authConfigService.AppSettings; + services.AddMixIdentityServices(); + return services; + } + + public static IServiceCollection AddMixIdentityConfigurations(this IServiceCollection services, IConfiguration configuration) + where TDbContext : DbContext + { + + + var authConfigurations = configuration.GetSection(MixAppSettingsSection.Authentication).Get(); PasswordOptions pOpt = new() { RequireDigit = false, @@ -116,16 +125,20 @@ public static IServiceCollection AddMixAuthorize(this IServiceCollec // options.SlidingExpiration = true; //}); // Firebase service must be singleton (only one firebase default instance) + + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); + return services; + } + + public static IServiceCollection AddMixIdentityServices(this IServiceCollection services) + { services.TryAddSingleton(); services.TryAddScoped(); services.TryAddScoped>(); - services.AddSingleton(); - services.AddSingleton(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - - + services.TryAddScoped(); return services; } diff --git a/src/platform/mix.library/Startup/Migration.cs b/src/platform/mix.library/Startup/Migration.cs index 9eb2f6d06..d4d87ec9d 100644 --- a/src/platform/mix.library/Startup/Migration.cs +++ b/src/platform/mix.library/Startup/Migration.cs @@ -1,8 +1,4 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Mix.Database.Services; -using Mix.RepoDb.Interfaces; -using Mix.RepoDb.Services; +using Mix.Database.Services; using Mix.Shared.Models.Configurations; namespace Microsoft.Extensions.DependencyInjection diff --git a/src/platform/mix.library/Startup/MixCommonService.cs b/src/platform/mix.library/Startup/MixCommonService.cs index b7aeabd2c..6b32a9193 100644 --- a/src/platform/mix.library/Startup/MixCommonService.cs +++ b/src/platform/mix.library/Startup/MixCommonService.cs @@ -4,11 +4,8 @@ using Mix.Communicator.Services; using Mix.Database.Services; using Mix.Lib.Interfaces; -using Mix.Lib.Publishers; using Mix.Lib.Services; -using Mix.Lib.Subscribers; using Mix.SignalR.Interfaces; -using System.Reflection; namespace Microsoft.Extensions.DependencyInjection { @@ -27,13 +24,13 @@ public static IServiceCollection AddMixCommonServices(this IServiceCollection se services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); - + services.TryAddSingleton(); services.TryAddScoped(); - + services.TryAddScoped(); services.TryAddScoped(); - + return services; } } diff --git a/src/platform/mix.library/Startup/MixModules.cs b/src/platform/mix.library/Startup/MixModules.cs index 1a2841e91..fb7c9e8e9 100644 --- a/src/platform/mix.library/Startup/MixModules.cs +++ b/src/platform/mix.library/Startup/MixModules.cs @@ -1,9 +1,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection.Extensions; using Mix.Lib.Conventions; using Mix.Lib.Filters; -using Mix.Service.Interfaces; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Reflection; diff --git a/src/platform/mix.library/Startup/MixTenant.cs b/src/platform/mix.library/Startup/MixTenant.cs index 77802e0d8..7d3270382 100644 --- a/src/platform/mix.library/Startup/MixTenant.cs +++ b/src/platform/mix.library/Startup/MixTenant.cs @@ -6,8 +6,6 @@ using Mix.Lib.Middlewares; using Mix.Lib.Services; using Mix.Shared.Models.Configurations; -using RepoDb; -using RepoDb.Interfaces; namespace Microsoft.Extensions.DependencyInjection { diff --git a/src/platform/mix.library/Startup/Queue.cs b/src/platform/mix.library/Startup/Queue.cs index d48cbd6f3..d3902baff 100644 --- a/src/platform/mix.library/Startup/Queue.cs +++ b/src/platform/mix.library/Startup/Queue.cs @@ -1,7 +1,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection.Extensions; using Mix.Mq.Lib.Models; -using Mix.Queue.Engines.MixQueue; using Mix.Queue.Services; using System.Reflection; diff --git a/src/platform/mix.library/Startup/RateLimiting.cs b/src/platform/mix.library/Startup/RateLimiting.cs index e1270f7c5..a063ae579 100644 --- a/src/platform/mix.library/Startup/RateLimiting.cs +++ b/src/platform/mix.library/Startup/RateLimiting.cs @@ -1,10 +1,8 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.RateLimiting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Mix.Shared.Models.Configurations; -using System.Configuration; using System.Globalization; using System.Net; using System.Threading.RateLimiting; @@ -78,7 +76,7 @@ public static IServiceCollection AddMixRateLimiter(this IServiceCollection servi return RateLimitPartition.GetNoLimiter(IPAddress.Loopback); }); }); - + return services; } static string GetUserEndPoint(HttpContext context) => diff --git a/src/platform/mix.library/Startup/ResponseCaching.cs b/src/platform/mix.library/Startup/ResponseCaching.cs index 23c82eac0..d3c4ae6c0 100644 --- a/src/platform/mix.library/Startup/ResponseCaching.cs +++ b/src/platform/mix.library/Startup/ResponseCaching.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Mix.Lib.Policies; diff --git a/src/platform/mix.library/Startup/Swagger.cs b/src/platform/mix.library/Startup/Swagger.cs index 4f8f0af09..2f788ac27 100644 --- a/src/platform/mix.library/Startup/Swagger.cs +++ b/src/platform/mix.library/Startup/Swagger.cs @@ -59,23 +59,23 @@ public static IApplicationBuilder UseMixSwaggerApps(this IApplicationBuilder app //if (isDevelop) //{ - var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; - app.UseSwagger(opt => - { - opt.RouteTemplate = routeTemplate; - }); - app.UseSwaggerUI(c => - { - c.InjectStylesheet("/mix-app/css/swagger.css"); - c.InjectJavascript("/mix-app/js/swagger.js"); - c.SwaggerEndpoint(endPoint, $"{title} {version}"); - c.RoutePrefix = routePrefix; - c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.List); - c.DocumentTitle = "Mixcore - API Specification"; - c.EnableFilter(); - c.EnableDeepLinking(); - }); + app.UseSwagger(opt => + { + opt.RouteTemplate = routeTemplate; + }); + app.UseSwaggerUI(c => + { + c.InjectStylesheet("/mix-app/css/swagger.css"); + c.InjectJavascript("/mix-app/js/swagger.js"); + c.SwaggerEndpoint(endPoint, $"{title} {version}"); + c.RoutePrefix = routePrefix; + c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.List); + c.DocumentTitle = "Mixcore - API Specification"; + c.EnableFilter(); + c.EnableDeepLinking(); + }); //} return app; } diff --git a/src/platform/mix.library/Startup/UnitOfWorks.cs b/src/platform/mix.library/Startup/UnitOfWorks.cs index ac06c77bb..879c67f38 100644 --- a/src/platform/mix.library/Startup/UnitOfWorks.cs +++ b/src/platform/mix.library/Startup/UnitOfWorks.cs @@ -2,7 +2,7 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Mix.Database.Entities.Account; using Mix.Database.Entities.AuditLog; -using Mix.Database.Entities.Queue; +using Mix.Database.Entities.QueueLog; using Mix.Lib.Middlewares; namespace Microsoft.Extensions.DependencyInjection @@ -12,18 +12,18 @@ public static partial class ServiceCollectionExtensions public static IServiceCollection AddUoWs(this IServiceCollection services) { services.AddDbContext(); - services.AddDbContext(); + services.AddDbContext(); services.TryAddScoped>(); services.TryAddScoped>(); services.TryAddScoped>(); services.TryAddScoped>(); - services.TryAddScoped>(); + services.TryAddScoped>(); UnitOfWorkMiddleware.AddUnitOfWork>(); UnitOfWorkMiddleware.AddUnitOfWork>(); UnitOfWorkMiddleware.AddUnitOfWork>(); UnitOfWorkMiddleware.AddUnitOfWork>(); - UnitOfWorkMiddleware.AddUnitOfWork>(); + UnitOfWorkMiddleware.AddUnitOfWork>(); return services; } diff --git a/src/platform/mix.library/Startup/_ServiceCollectionExtensions.cs b/src/platform/mix.library/Startup/_ServiceCollectionExtensions.cs index 3105ff721..1c0cc4db5 100644 --- a/src/platform/mix.library/Startup/_ServiceCollectionExtensions.cs +++ b/src/platform/mix.library/Startup/_ServiceCollectionExtensions.cs @@ -1,16 +1,12 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.ResponseCompression; using Microsoft.AspNetCore.StaticFiles; -using Microsoft.Azure.Amqp.Framing; -using Microsoft.Build.Framework; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Options; using Mix.Lib.Interfaces; using Mix.Lib.Middlewares; using Mix.Lib.Services; @@ -38,10 +34,10 @@ public static IServiceCollection AddMixServices(this IServiceCollection services { var globalConfig = configuration.GetSection(MixAppSettingsSection.GlobalSettings) .Get(); - + var authConfig = configuration.GetSection(MixAppSettingsSection.Authentication) .Get(); - + var redisCnn = configuration.GetSection("Redis").GetValue("ConnectionString"); services.Configure(options => { @@ -75,7 +71,7 @@ public static IServiceCollection AddMixServices(this IServiceCollection services .SetApplicationName(authConfig.Issuer); } - + services.AddMixCommonServices(configuration); services.TryAddScoped(); services.TryAddScoped(); @@ -121,9 +117,9 @@ public static IServiceCollection AddMixTestServices(this IServiceCollection serv // Clone Settings from shared folder var globalConfig = configuration.GetSection(MixAppSettingsSection.GlobalSettings).Get()!; var authConfig = configuration.GetSection(MixAppSettingsSection.Authentication) - .Get(); + .Get(); services.AddMvc().AddSessionStateTempDataProvider(); - + services.AddMixCommonServices(configuration); services.TryAddScoped(); diff --git a/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixDatabaseColumnViewModelHandler.cs b/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixDatabaseColumnViewModelHandler.cs index 0beb8bdc7..c65543e35 100644 --- a/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixDatabaseColumnViewModelHandler.cs +++ b/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixDatabaseColumnViewModelHandler.cs @@ -1,20 +1,12 @@ -using Mix.Lib.Interfaces; -using Mix.Lib.Services; -using Mix.Mq.Lib.Models; +using Mix.Mq.Lib.Models; using Mix.RepoDb.Interfaces; -using Mix.RepoDb.Services; using Mix.RepoDb.ViewModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Lib.Subscribers.Handlers.MixViewModelChangedHandlers { public class MixDatabaseColumnViewModelHandler { - + public static async Task MessageQueueHandler(MessageQueueModel data, IMixDbService mixDbService) { switch (data.Action) diff --git a/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixDomainViewModelHandler.cs b/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixDomainViewModelHandler.cs index c2b18b49b..49948046f 100644 --- a/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixDomainViewModelHandler.cs +++ b/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixDomainViewModelHandler.cs @@ -1,11 +1,5 @@ using Mix.Lib.Interfaces; -using Mix.Lib.Services; using Mix.Mq.Lib.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Lib.Subscribers.Handlers.MixViewModelChangedHandlers { diff --git a/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixTenantSystemViewModelHandler.cs b/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixTenantSystemViewModelHandler.cs index 12831086c..8ac6e52de 100644 --- a/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixTenantSystemViewModelHandler.cs +++ b/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/MixTenantSystemViewModelHandler.cs @@ -1,11 +1,5 @@ using Mix.Lib.Interfaces; -using Mix.Lib.Services; using Mix.Mq.Lib.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Lib.Subscribers.Handlers.MixViewModelChangedHandlers { diff --git a/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/TemplateHandler.cs b/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/TemplateHandler.cs index 54327274b..19e03f2c6 100644 --- a/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/TemplateHandler.cs +++ b/src/platform/mix.library/Subscribers/Handlers/MixViewModelChangedHandlers/TemplateHandler.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Mix.Mq.Lib.Models; +using Mix.Mq.Lib.Models; namespace Mix.Lib.Subscribers.Handlers.MixViewModelChangedHandlers { diff --git a/src/platform/mix.library/Subscribers/MixBackgroundTaskSubscriber.cs b/src/platform/mix.library/Subscribers/MixBackgroundTaskSubscriber.cs index ada869dc1..7bb9dd4fc 100644 --- a/src/platform/mix.library/Subscribers/MixBackgroundTaskSubscriber.cs +++ b/src/platform/mix.library/Subscribers/MixBackgroundTaskSubscriber.cs @@ -4,16 +4,12 @@ using Microsoft.Extensions.ObjectPool; using Mix.Communicator.Models; using Mix.Communicator.Services; -using Mix.Database.Entities.Account; using Mix.Lib.Interfaces; using Mix.Mixdb.Event.Services; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; -using Mix.Queue.Engines.MixQueue; using Mix.Service.Commands; -using Mix.Service.Interfaces; using Mix.SignalR.Enums; -using Mix.SignalR.Hubs; using Mix.SignalR.Interfaces; using Mix.SignalR.Models; @@ -47,7 +43,7 @@ public MixBackgroundTaskSubscriber( public override Task StartAsync(CancellationToken cancellationToken = default) { base.StartAsync(cancellationToken); - + return Task.Run(async () => { while (PortalHub.Connection == null || PortalHub.Connection.State != Microsoft.AspNetCore.SignalR.Client.HubConnectionState.Connected) @@ -59,7 +55,7 @@ public override Task StartAsync(CancellationToken cancellationToken = default) } catch (Exception ex) { - _logger.LogError(GetType().Name, ex); + Logger.LogError(GetType().Name, ex); } } }); diff --git a/src/platform/mix.library/Subscribers/MixDbCommandSubscriber.cs b/src/platform/mix.library/Subscribers/MixDbCommandSubscriber.cs index 24f853217..370660031 100644 --- a/src/platform/mix.library/Subscribers/MixDbCommandSubscriber.cs +++ b/src/platform/mix.library/Subscribers/MixDbCommandSubscriber.cs @@ -1,19 +1,11 @@ using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; -using Mix.Communicator.Models; -using Mix.Communicator.Services; using Mix.Database.Entities.MixDb; -using Mix.Mixdb.Event.Services; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; -using Mix.Queue.Engines.MixQueue; using Mix.RepoDb.Interfaces; -using Mix.Service.Commands; -using Mix.Service.Interfaces; using Mix.SignalR.Enums; -using Mix.SignalR.Hubs; using Mix.SignalR.Interfaces; using Mix.SignalR.Models; @@ -21,6 +13,7 @@ namespace Mix.Lib.Subscribers { public class MixDbCommandSubscriber : SubscriberBase { + private readonly string[] _allowActions; private const string TopicId = MixQueueTopics.MixDbCommand; public MixDbCommandSubscriber( @@ -31,17 +24,24 @@ public MixDbCommandSubscriber( IPooledObjectPolicy rabbitMqObjectPolicy = null) : base(TopicId, nameof(MixDbCommandSubscriber), 20, serviceProvider, configuration, queueService, logger, rabbitMqObjectPolicy) { + _allowActions = [.. Enum.GetNames(typeof(MixDbCommandQueueAction))]; } public override async Task Handler(MessageQueueModel model) { + if (!_allowActions.Contains(model.Action)) + { + return; + } + IMixDbDataService mixDbDataService = GetRequiredService(); IMixDbCommandHubClientService mixDbCommandHub = GetRequiredService(); UnitOfWorkInfo uow = GetRequiredService>(); mixDbDataService.SetUOW(uow); - switch (model.Action) + Enum.TryParse(model.Action, out MixDbCommandQueueAction action); + switch (action) { - case MixDbCommandQueueActions.Create: + case MixDbCommandQueueAction.Create: var cmd = model.ParseData(); if (cmd != null) { @@ -53,7 +53,7 @@ await mixDbCommandHub.SendPrivateMessageAsync( } } break; - case MixDbCommandQueueActions.Update: + case MixDbCommandQueueAction.Update: var updCmd = model.ParseData(); if (updCmd != null) { diff --git a/src/platform/mix.library/Subscribers/MixViewModelChangedSubscriber.cs b/src/platform/mix.library/Subscribers/MixViewModelChangedSubscriber.cs index ee9e9a8a1..b7a1235bc 100644 --- a/src/platform/mix.library/Subscribers/MixViewModelChangedSubscriber.cs +++ b/src/platform/mix.library/Subscribers/MixViewModelChangedSubscriber.cs @@ -7,9 +7,7 @@ using Mix.Lib.Subscribers.Handlers.MixViewModelChangedHandlers; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; -using Mix.Queue.Engines.MixQueue; using Mix.RepoDb.Interfaces; -using Org.BouncyCastle.Asn1.X509.Qualified; namespace Mix.Lib.Subscribers { @@ -49,8 +47,9 @@ public override async Task Handler(MessageQueueModel data) break; case var m when m == typeof(MixDatabaseColumnViewModel).FullName: var mixDbService = GetRequiredService(); - if (mixDbService != null) { - await MixDatabaseColumnViewModelHandler.MessageQueueHandler(data,mixDbService); + if (mixDbService != null) + { + await MixDatabaseColumnViewModelHandler.MessageQueueHandler(data, mixDbService); } break; default: diff --git a/src/platform/mix.library/ViewModels/MixDatabaseColumnViewModel.cs b/src/platform/mix.library/ViewModels/MixDatabaseColumnViewModel.cs index 42faa9f48..9722b842c 100644 --- a/src/platform/mix.library/ViewModels/MixDatabaseColumnViewModel.cs +++ b/src/platform/mix.library/ViewModels/MixDatabaseColumnViewModel.cs @@ -1,5 +1,4 @@ using Mix.Shared.Models; -using Newtonsoft.Json; namespace Mix.Lib.ViewModels { @@ -30,7 +29,7 @@ public MixDatabaseColumnViewModel(UnitOfWorkInfo unitOfWorkInfo) : base(unitOfWo { } - public MixDatabaseColumnViewModel(MixDatabaseColumn entity, UnitOfWorkInfo uowInfo) + public MixDatabaseColumnViewModel(MixDatabaseColumn entity, UnitOfWorkInfo uowInfo) : base(entity, uowInfo) { } diff --git a/src/platform/mix.library/ViewModels/MixDatabaseRelationshipViewModel.cs b/src/platform/mix.library/ViewModels/MixDatabaseRelationshipViewModel.cs index e3b16d0d5..bae44dda7 100644 --- a/src/platform/mix.library/ViewModels/MixDatabaseRelationshipViewModel.cs +++ b/src/platform/mix.library/ViewModels/MixDatabaseRelationshipViewModel.cs @@ -1,5 +1,4 @@ using System.ComponentModel.DataAnnotations; -using System.Text.Json.Serialization; namespace Mix.Lib.ViewModels { diff --git a/src/platform/mix.library/ViewModels/MixDatabaseViewModel.cs b/src/platform/mix.library/ViewModels/MixDatabaseViewModel.cs index dc08bfbdb..97da57d3e 100644 --- a/src/platform/mix.library/ViewModels/MixDatabaseViewModel.cs +++ b/src/platform/mix.library/ViewModels/MixDatabaseViewModel.cs @@ -1,9 +1,6 @@ -using DocumentFormat.OpenXml.Vml.Spreadsheet; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Mix.Lib.ViewModels.ReadOnly; -using Mix.Service.Services; using System.ComponentModel.DataAnnotations; -using System.Threading; namespace Mix.Lib.ViewModels { @@ -71,7 +68,7 @@ public override async Task ExpandView(CancellationToken cancellationToken = defa protected override async Task SaveEntityRelationshipAsync(MixDatabase parentEntity, CancellationToken cancellationToken = default) { var fieldNameService = GetFielNameService(); - + if (Columns != null) { @@ -143,7 +140,7 @@ private async Task CreateRefColumn(MixDatabaseRelationshipViewModel item, FieldN if (item.Type == MixDatabaseRelationshipType.OneToMany) { var referenceColumnName = fieldNameService.GetParentId(item.SourceDatabaseName); - + if (!Context.MixDatabaseColumn.Any(m => m.MixDatabaseName == item.DestinateDatabaseName && m.SystemName == referenceColumnName)) { var srcDb = Context.MixDatabase.FirstOrDefault(m => m.SystemName == item.SourceDatabaseName); @@ -152,7 +149,7 @@ private async Task CreateRefColumn(MixDatabaseRelationshipViewModel item, FieldN { MixDatabaseName = item.DestinateDatabaseName, MixDatabaseId = destDb.Id, - DataType = MixDataType.Reference, + DataType = srcDb.Type == MixDatabaseType.GuidService ? MixDataType.Guid : MixDataType.Integer, CreatedBy = CreatedBy, DisplayName = item.ReferenceColumnName.ToTitleCase(), SystemName = referenceColumnName diff --git a/src/platform/mix.library/ViewModels/MixTenantSystemViewModel.cs b/src/platform/mix.library/ViewModels/MixTenantSystemViewModel.cs index 17328c348..307cc70d0 100644 --- a/src/platform/mix.library/ViewModels/MixTenantSystemViewModel.cs +++ b/src/platform/mix.library/ViewModels/MixTenantSystemViewModel.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Mix.Lib.Services; namespace Mix.Lib.ViewModels { diff --git a/src/platform/mix.library/ViewModels/MixUserViewModel.cs b/src/platform/mix.library/ViewModels/MixUserViewModel.cs index 4b903f425..9677b853a 100644 --- a/src/platform/mix.library/ViewModels/MixUserViewModel.cs +++ b/src/platform/mix.library/ViewModels/MixUserViewModel.cs @@ -4,9 +4,6 @@ using Mix.Identity.Models.ManageViewModels; using Mix.RepoDb.Interfaces; using Mix.RepoDb.Repositories; -using Mix.RepoDb.Services; -using RepoDb; -using System.Text.Json.Serialization; namespace Mix.Lib.ViewModels { @@ -63,7 +60,7 @@ public async Task LoadUserDataAsync(int tenantId, IMixDbDataService mixDbService try { UserData = await mixDbService.GetSingleByGuidParent(MixDatabaseNames.SYSTEM_USER_DATA, MixContentType.User, Id, true); - + var roles = from ur in accContext.AspNetUserRoles join r in accContext.MixRoles on ur.RoleId equals r.Id diff --git a/src/platform/mix.library/ViewModels/ReadOnly/MixDatabaseReadViewModel.cs b/src/platform/mix.library/ViewModels/ReadOnly/MixDatabaseReadViewModel.cs index 0b750477b..8b92c5211 100644 --- a/src/platform/mix.library/ViewModels/ReadOnly/MixDatabaseReadViewModel.cs +++ b/src/platform/mix.library/ViewModels/ReadOnly/MixDatabaseReadViewModel.cs @@ -1,7 +1,4 @@ -using Microsoft.EntityFrameworkCore; -using System.ComponentModel.DataAnnotations; - -namespace Mix.Lib.ViewModels.ReadOnly +namespace Mix.Lib.ViewModels.ReadOnly { public sealed class MixDatabaseContextReadViewModel : TenantDataViewModelBase diff --git a/src/platform/mix.library/mix.library.csproj b/src/platform/mix.library/mix.library.csproj index 028856d00..c2865cc23 100644 --- a/src/platform/mix.library/mix.library.csproj +++ b/src/platform/mix.library/mix.library.csproj @@ -41,7 +41,6 @@ - @@ -82,9 +81,9 @@ - - - + + + diff --git a/src/platform/mix.log/Interfaces/IAuditLogService.cs b/src/platform/mix.log/Interfaces/IAuditLogService.cs index 1be143c52..e453dad0e 100644 --- a/src/platform/mix.log/Interfaces/IAuditLogService.cs +++ b/src/platform/mix.log/Interfaces/IAuditLogService.cs @@ -1,6 +1,4 @@ -using Microsoft.AspNetCore.Http; -using Mix.Log.Lib.Models; -using Newtonsoft.Json.Linq; +using Mix.Log.Lib.Models; namespace Mix.Log.Lib.Interfaces { diff --git a/src/platform/mix.log/Interfaces/IMixQueueLog.cs b/src/platform/mix.log/Interfaces/IMixQueueLog.cs index c5458459a..d5904f87a 100644 --- a/src/platform/mix.log/Interfaces/IMixQueueLog.cs +++ b/src/platform/mix.log/Interfaces/IMixQueueLog.cs @@ -1,8 +1,4 @@ -using Microsoft.AspNetCore.Http; -using Mix.Database.Entities.Queue; -using Mix.Mq.Lib.Models; -using Mix.Service.Models; -using Newtonsoft.Json.Linq; +using Mix.Mq.Lib.Models; namespace Mix.Log.Lib.Interfaces { diff --git a/src/platform/mix.log/Models/AuditLogDataModel.cs b/src/platform/mix.log/Models/AuditLogDataModel.cs index f9ec1fcee..bd6f4c952 100644 --- a/src/platform/mix.log/Models/AuditLogDataModel.cs +++ b/src/platform/mix.log/Models/AuditLogDataModel.cs @@ -1,14 +1,7 @@ using Microsoft.AspNetCore.Http; using Mix.Log.Lib.Services; -using Mix.Service.Services; -using Mix.Shared.Models; using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Text.Json.Nodes; -using System.Threading.Tasks; namespace Mix.Log.Lib.Models { diff --git a/src/platform/mix.log/Models/SearchLogResponseModel.cs b/src/platform/mix.log/Models/SearchLogResponseModel.cs index 76dbac459..e76c5636a 100644 --- a/src/platform/mix.log/Models/SearchLogResponseModel.cs +++ b/src/platform/mix.log/Models/SearchLogResponseModel.cs @@ -1,9 +1,4 @@ using Mix.Heart.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Log.Lib.Models { diff --git a/src/platform/mix.log/Publishers/MixLogPublisher.cs b/src/platform/mix.log/Publishers/MixLogPublisher.cs index 7589c641b..b7d124763 100644 --- a/src/platform/mix.log/Publishers/MixLogPublisher.cs +++ b/src/platform/mix.log/Publishers/MixLogPublisher.cs @@ -4,7 +4,6 @@ using Mix.Constant.Constants; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; -using Mix.Queue.Engines.MixQueue; using Mix.Queue.Interfaces; using Mix.Shared.Services; diff --git a/src/platform/mix.log/ServiceCollectionExtension.cs b/src/platform/mix.log/ServiceCollectionExtension.cs index d45e5258e..ead17b437 100644 --- a/src/platform/mix.log/ServiceCollectionExtension.cs +++ b/src/platform/mix.log/ServiceCollectionExtension.cs @@ -1,32 +1,23 @@ -using Google.Api; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Mix.Constant.Constants; using Mix.Database.Entities.AuditLog; -using Mix.Database.Entities.Queue; +using Mix.Database.Entities.QueueLog; using Mix.Database.Services; using Mix.Lib.Interfaces; using Mix.Log.Lib.Interfaces; using Mix.Log.Lib.Models; using Mix.Log.Lib.Publishers; using Mix.Log.Lib.Services; -using Mix.Log.Lib.Subscribers; using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; using Mix.Queue.Services; using Mix.Service.Services; -using Mix.Shared.Interfaces; using Mix.Shared.Models.Configurations; using Mix.Shared.Services; using Mix.SignalR.Interfaces; -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Log.Lib { @@ -46,7 +37,7 @@ public static IServiceCollection AddMixLog(this IServiceCollection services, ICo services.AddDbContext(); - services.AddDbContext(); + services.AddDbContext(); services.TryAddScoped(); services.TryAddSingleton(); if (!globalConfigs!.IsInit) diff --git a/src/platform/mix.log/Services/AuditLogService.cs b/src/platform/mix.log/Services/AuditLogService.cs index a86ce271e..c763ee234 100644 --- a/src/platform/mix.log/Services/AuditLogService.cs +++ b/src/platform/mix.log/Services/AuditLogService.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using Mix.Constant.Constants; +using Mix.Constant.Constants; using Mix.Database.Entities.AuditLog; +using Mix.Database.Services; using Mix.Heart.Enums; using Mix.Heart.Helpers; using Mix.Log.Lib.Commands; @@ -17,27 +17,24 @@ namespace Mix.Log.Lib.Services { public class AuditLogService : IAuditLogService { + private readonly DatabaseService _databaseService; private readonly ILogStreamHubClientService _logStreamHub; private readonly IMemoryQueueService _queueService; private AuditLogDbContext _dbContext; public int TenantId { get; set; } - public AuditLogService(IMemoryQueueService queueService, ILogStreamHubClientService logStreamHub) + public AuditLogService(IMemoryQueueService queueService, ILogStreamHubClientService logStreamHub, DatabaseService databaseService) { _queueService = queueService; _logStreamHub = logStreamHub; + _databaseService = databaseService; } public async Task SaveRequestAsync(AuditLogDataModel request) { try { - using (_dbContext = new()) + using (_dbContext = _databaseService.GetAuditLogDbContext()) { - if (_dbContext.Database.GetPendingMigrations().Any()) - { - _dbContext.Database.Migrate(); - } - var log = new AuditLog() { Id = Guid.NewGuid(), diff --git a/src/platform/mix.log/Services/MixQueueLogService.cs b/src/platform/mix.log/Services/MixQueueLogService.cs index b10c6e20d..26609a250 100644 --- a/src/platform/mix.log/Services/MixQueueLogService.cs +++ b/src/platform/mix.log/Services/MixQueueLogService.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Mix.Constant.Enums; -using Mix.Database.Entities.Queue; +using Mix.Database.Entities.QueueLog; +using Mix.Database.Services; using Mix.Heart.Enums; using Mix.Heart.Extensions; using Mix.Heart.Helpers; @@ -13,12 +14,14 @@ namespace Mix.Log.Lib.Services { public class MixQueueLogService : IMixQueueLog { - private MixQueueDbContext _dbContext; + private QueueLogDbContext _dbContext; + private readonly DatabaseService _databaseService; private MixQueueMessages _mixQueueService; public int TenantId { get; set; } - public MixQueueLogService() + public MixQueueLogService(DatabaseService databaseService) { _mixQueueService = new(); + _databaseService = databaseService; } @@ -26,12 +29,12 @@ public async Task EnqueueMessageAsync(MessageQueueModel queueMessage) { try { - using (_dbContext = new()) + using (_dbContext = _databaseService.GetQueueLogDbContext()) { InitDbContext(); if (queueMessage != null) { - var queueLog = new MixQueueMessageLog() + var queueLog = new QueueLog() { Id = queueMessage.Id, QueueMessageId = queueMessage.Id, @@ -51,7 +54,7 @@ public async Task EnqueueMessageAsync(MessageQueueModel queueMessage) { queueLog.StringData = queueMessage.Data; } - _dbContext.MixQueueMessage.Add(queueLog); + _dbContext.QueueLog.Add(queueLog); await _dbContext.SaveChangesAsync(); } @@ -67,11 +70,11 @@ public async Task AckQueueMessage(MessageQueueModel ackQueueMessage) { try { - using (_dbContext = new()) + using (_dbContext = _databaseService.GetQueueLogDbContext()) { InitDbContext(); - var rootLog = await _dbContext.MixQueueMessage.FirstOrDefaultAsync(m => m.Id == ackQueueMessage.Id); + var rootLog = await _dbContext.QueueLog.FirstOrDefaultAsync(m => m.Id == ackQueueMessage.Id); if (rootLog != null) { var subs = rootLog.Subscriptions.FirstOrDefault(m => @@ -86,7 +89,7 @@ public async Task AckQueueMessage(MessageQueueModel ackQueueMessage) rootLog.State = MixQueueMessageLogState.ACK; } rootLog.LastModified = DateTime.UtcNow; - _dbContext.MixQueueMessage.Update(rootLog); + _dbContext.QueueLog.Update(rootLog); await _dbContext.SaveChangesAsync(); } } @@ -101,11 +104,11 @@ public async Task FailedQueueMessage(MessageQueueModel log) { try { - using (_dbContext = new()) + using (_dbContext = _databaseService.GetQueueLogDbContext()) { InitDbContext(); - var rootLog = await _dbContext.MixQueueMessage.FirstOrDefaultAsync(m => m.Id == log.Id); + var rootLog = await _dbContext.QueueLog.FirstOrDefaultAsync(m => m.Id == log.Id); if (rootLog != null) { var subs = rootLog.Subscriptions.FirstOrDefault(m => m.Value("id") == log.Sender) as JObject; @@ -117,7 +120,7 @@ public async Task FailedQueueMessage(MessageQueueModel log) rootLog.State = MixQueueMessageLogState.FAILED; } rootLog.LastModified = DateTime.UtcNow; - _dbContext.MixQueueMessage.Update(rootLog); + _dbContext.QueueLog.Update(rootLog); await _dbContext.SaveChangesAsync(); } } @@ -132,11 +135,11 @@ public async Task DeadLetterMessageAsync(MessageQueueModel deadLetterQueueMessag { try { - using (_dbContext = new()) + using (_dbContext = _databaseService.GetQueueLogDbContext()) { InitDbContext(); - var rootLog = await _dbContext.MixQueueMessage.FirstOrDefaultAsync(m => m.Id == deadLetterQueueMessage.Id); + var rootLog = await _dbContext.QueueLog.FirstOrDefaultAsync(m => m.Id == deadLetterQueueMessage.Id); if (rootLog != null) { var subs = rootLog.Subscriptions.FirstOrDefault(m => m.Value("id") == deadLetterQueueMessage.Sender); @@ -147,7 +150,7 @@ public async Task DeadLetterMessageAsync(MessageQueueModel deadLetterQueueMessag } rootLog.State = MixQueueMessageLogState.DEADLETTER; rootLog.LastModified = DateTime.UtcNow; - _dbContext.MixQueueMessage.Update(rootLog); + _dbContext.QueueLog.Update(rootLog); await _dbContext.SaveChangesAsync(); } } diff --git a/src/platform/mix.log/Subscribers/MixLogSubscriber.cs b/src/platform/mix.log/Subscribers/MixLogSubscriber.cs index f3d49e6af..7e91a8ced 100644 --- a/src/platform/mix.log/Subscribers/MixLogSubscriber.cs +++ b/src/platform/mix.log/Subscribers/MixLogSubscriber.cs @@ -2,23 +2,15 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; using Mix.Constant.Constants; -using Mix.Constant.Enums; -using Mix.Database.Entities.Queue; -using Mix.Heart.Enums; -using Mix.Heart.Extensions; -using Mix.Heart.Helpers; using Mix.Log.Lib.Commands; using Mix.Log.Lib.Interfaces; -using Mix.Log.Lib.Models; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; -using Mix.Queue.Engines.MixQueue; using Mix.Queue.Interfaces; using Mix.Service.Services; using Mix.SignalR.Enums; using Mix.SignalR.Interfaces; using Mix.SignalR.Models; -using Newtonsoft.Json.Linq; namespace Mix.Log.Lib.Subscribers { @@ -55,7 +47,7 @@ public MixLogSubscriber( public override Task StartAsync(CancellationToken cancellationToken = default) { base.StartAsync(cancellationToken); - + return Task.Run(async () => { while (_portalHub.Connection == null || _portalHub.Connection.State != Microsoft.AspNetCore.SignalR.Client.HubConnectionState.Connected) @@ -65,9 +57,9 @@ public override Task StartAsync(CancellationToken cancellationToken = default) await Task.Delay(5000); await _portalHub.StartConnection(); } - catch(Exception ex) + catch (Exception ex) { - _logger.LogError(GetType().Name, ex); + Logger.LogError(GetType().Name, ex); } } }); @@ -127,7 +119,7 @@ public override async Task Handler(MessageQueueModel model) if (deadLetterMsg != null) { deadLetterMsg.Sender = model.Sender; - + await _queueMessageLogService.DeadLetterMessageAsync(deadLetterMsg); } break; diff --git a/src/platform/mix.log/ViewModels/MixQueueMessageLogViewModel.cs b/src/platform/mix.log/ViewModels/MixQueueMessageLogViewModel.cs index 5b3bdd86a..cee7456cd 100644 --- a/src/platform/mix.log/ViewModels/MixQueueMessageLogViewModel.cs +++ b/src/platform/mix.log/ViewModels/MixQueueMessageLogViewModel.cs @@ -1,5 +1,5 @@ using Mix.Constant.Enums; -using Mix.Database.Entities.Queue; +using Mix.Database.Entities.QueueLog; using Mix.Heart.UnitOfWork; using Mix.Heart.ViewModel; using Newtonsoft.Json.Linq; @@ -7,7 +7,7 @@ namespace Mix.Log.Lib.ViewModels { public sealed class MixQueueMessageLogViewModel - : ViewModelBase + : ViewModelBase { #region Properties public Guid? QueueMessageId { get; set; } @@ -31,7 +31,7 @@ public MixQueueMessageLogViewModel() { } - public MixQueueMessageLogViewModel(MixQueueMessageLog entity, UnitOfWorkInfo? uowInfo) + public MixQueueMessageLogViewModel(QueueLog entity, UnitOfWorkInfo? uowInfo) : base(entity, uowInfo) { } diff --git a/src/platform/mix.mixdb/Services/RuntimeDbContextService.cs b/src/platform/mix.mixdb/Services/RuntimeDbContextService.cs index 8019d2684..3a0a1cc78 100644 --- a/src/platform/mix.mixdb/Services/RuntimeDbContextService.cs +++ b/src/platform/mix.mixdb/Services/RuntimeDbContextService.cs @@ -14,10 +14,10 @@ using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; -using Mix.Constant.Constants; using Mix.Database.Entities.Cms; using Mix.Database.Services; using Mix.Heart.Enums; +using Mix.Heart.Models; using Mix.Service.Services; using Npgsql.EntityFrameworkCore.PostgreSQL.Diagnostics.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.Scaffolding.Internal; @@ -42,23 +42,22 @@ public RuntimeDbContextService(IHttpContextAccessor httpContextAccessor, Databas { _httpContextAccessor = httpContextAccessor; _databaseService = databaseService; - LoadDbContextAssembly(); } - public void Reload() + public void Reload(string cnnString) { _assemblyLoadContext.Unload(); - LoadDbContextAssembly(); + LoadDbContextAssembly(cnnString); } #region Create Dynamic Context - public void LoadDbContextAssembly() + public void LoadDbContextAssembly(string cnnString) { - if (!string.IsNullOrEmpty(_databaseService.GetConnectionString(MixConstants.CONST_MIXDB_CONNECTION))) + if (!string.IsNullOrEmpty(cnnString)) { - var sourceFiles = CreateDynamicDbContext(); + var sourceFiles = CreateDynamicDbContext(cnnString); using var peStream = new MemoryStream(); var enableLazyLoading = false; var result = GenerateCode(sourceFiles, enableLazyLoading).Emit(peStream); @@ -80,13 +79,13 @@ public void LoadDbContextAssembly() } } - public DbContext? GetMixDatabaseDbContext() + public DbContext? GetMixDatabaseDbContext(string cnnString) { - if (!string.IsNullOrEmpty(_databaseService.GetConnectionString(MixConstants.CONST_MIXDB_CONNECTION))) + if (!string.IsNullOrEmpty(cnnString)) { if (_assembly == null) { - LoadDbContextAssembly(); + LoadDbContextAssembly(cnnString); } if (_assembly != null) { @@ -102,9 +101,9 @@ public void LoadDbContextAssembly() return default; } - public List CreateDynamicDbContext() + public List CreateDynamicDbContext(string cnnString) { - var sourceFiles = new List(); + var sourceFiles = new List(); using var _cmsContext = new MixCmsContext(_databaseService); var scaffolder = CreateScaffolder(); var databaseNames = _cmsContext.MixDatabase.Select(m => m.SystemName.ToLower()).ToList(); @@ -126,11 +125,12 @@ public List CreateDynamicDbContext() ContextName = "DataContext", ContextNamespace = "TypedDataContext.Context", //ModelNamespace = "TypedDataContext.Models", - SuppressConnectionStringWarning = true + SuppressConnectionStringWarning = true, + }; var scaffoldedModelSources = scaffolder.ScaffoldModel( - _databaseService.GetConnectionString(MixConstants.CONST_MIXDB_CONNECTION), + cnnString, dbOpts, modelOpts, codeGenOpts); @@ -142,13 +142,21 @@ public List CreateDynamicDbContext() { ReplaceEntityNaming(item, ref contextFileCode); } - sourceFiles.Add(item.Code); + sourceFiles.Add(new FileModel() + { + Filename = item.Path, + Content = item.Code + }); } if (_databaseService.DatabaseProvider == MixDatabaseProvider.PostgreSQL) { contextFileCode = $"using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;{contextFileCode}"; } - sourceFiles.Add(contextFileCode); + sourceFiles.Add(new FileModel() + { + Filename = scaffoldedModelSources.ContextFile.Path, + Content = contextFileCode + }); return sourceFiles; } @@ -256,11 +264,11 @@ List CompilationReferences(bool enableLazyLoading) return refs; } - public CSharpCompilation GenerateCode(List sourceFiles, bool enableLazyLoading) + public CSharpCompilation GenerateCode(List sourceFiles, bool enableLazyLoading) { var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp11); - var parsedSyntaxTrees = sourceFiles.Select(f => SyntaxFactory.ParseSyntaxTree(f, options)); + var parsedSyntaxTrees = sourceFiles.Select(f => SyntaxFactory.ParseSyntaxTree(f.Content, options)); return CSharpCompilation.Create($"DataContext.dll", parsedSyntaxTrees, diff --git a/src/platform/mix.mixdb/ViewModels/MixContactAddressViewModel.cs b/src/platform/mix.mixdb/ViewModels/MixContactAddressViewModel.cs index 40e9b1224..b93a288a1 100644 --- a/src/platform/mix.mixdb/ViewModels/MixContactAddressViewModel.cs +++ b/src/platform/mix.mixdb/ViewModels/MixContactAddressViewModel.cs @@ -1,5 +1,4 @@ -using Mix.Database.Entities.MixDb; -using Mix.Heart.UnitOfWork; +using Mix.Heart.UnitOfWork; using Mix.Heart.ViewModel; namespace Mix.Mixdb.ViewModels diff --git a/src/platform/mix.mixdb/ViewModels/MixPermissionViewModel.cs b/src/platform/mix.mixdb/ViewModels/MixPermissionViewModel.cs index 69b3056e1..975e579fb 100644 --- a/src/platform/mix.mixdb/ViewModels/MixPermissionViewModel.cs +++ b/src/platform/mix.mixdb/ViewModels/MixPermissionViewModel.cs @@ -6,10 +6,10 @@ namespace Mix.Mixdb.ViewModels public class MixPermissionViewModel : ViewModelBase { #region Properties - public string Title { get; set; } - public string Type { get; set; } - public string Icon { get; set; } public int MixTenantId { get; set; } + public string DisplayName { get; set; } + public string Group { get; set; } + public string Key { get; set; } public Metadata? Metadata { get; set; } public List Endpoints { get; set; } #endregion diff --git a/src/platform/mix.mixdb/ViewModels/MixUserDataViewModel.cs b/src/platform/mix.mixdb/ViewModels/MixUserDataViewModel.cs index db4b8ac83..a737ed6f5 100644 --- a/src/platform/mix.mixdb/ViewModels/MixUserDataViewModel.cs +++ b/src/platform/mix.mixdb/ViewModels/MixUserDataViewModel.cs @@ -1,5 +1,4 @@ using Mix.Constant.Enums; -using Mix.Database.Entities.MixDb; using Mix.Heart.UnitOfWork; using Mix.Heart.ViewModel; using Newtonsoft.Json.Linq; diff --git a/src/platform/mix.mixdb/mix.mixdb.csproj b/src/platform/mix.mixdb/mix.mixdb.csproj index 865937440..45b7ca398 100644 --- a/src/platform/mix.mixdb/mix.mixdb.csproj +++ b/src/platform/mix.mixdb/mix.mixdb.csproj @@ -8,12 +8,12 @@ - - + + all - - + + diff --git a/src/platform/mix.quartz/Extensions/ServiceCollectionExtensions.cs b/src/platform/mix.quartz/Extensions/ServiceCollectionExtensions.cs index f6456380f..aff726e8b 100644 --- a/src/platform/mix.quartz/Extensions/ServiceCollectionExtensions.cs +++ b/src/platform/mix.quartz/Extensions/ServiceCollectionExtensions.cs @@ -1,10 +1,10 @@ using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection.Extensions; using Mix.Quartz.Interfaces; using Mix.Quartz.Services; using Mix.Shared; using System.Linq; using System.Reflection; -using Microsoft.Extensions.DependencyInjection.Extensions; namespace Microsoft.Extensions.DependencyInjection { diff --git a/src/platform/mix.quartz/Services/QuartzService.cs b/src/platform/mix.quartz/Services/QuartzService.cs index eb0e23a2c..9aa22f2c6 100644 --- a/src/platform/mix.quartz/Services/QuartzService.cs +++ b/src/platform/mix.quartz/Services/QuartzService.cs @@ -11,7 +11,6 @@ using Quartz.Impl; using Quartz.Impl.Matchers; using System; -using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; diff --git a/src/platform/mix.quartz/mix.quartz.csproj b/src/platform/mix.quartz/mix.quartz.csproj index 84c9610c4..9babc9e07 100644 --- a/src/platform/mix.quartz/mix.quartz.csproj +++ b/src/platform/mix.quartz/mix.quartz.csproj @@ -6,11 +6,11 @@ - - - - - + + + + + diff --git a/src/platform/mix.queue/Engines/Azure/AzureQueueSubscriber.cs b/src/platform/mix.queue/Engines/Azure/AzureQueueSubscriber.cs index e5fac140e..47a265fbd 100644 --- a/src/platform/mix.queue/Engines/Azure/AzureQueueSubscriber.cs +++ b/src/platform/mix.queue/Engines/Azure/AzureQueueSubscriber.cs @@ -1,7 +1,6 @@ using Azure.Messaging.ServiceBus; using Azure.Messaging.ServiceBus.Administration; using Mix.Queue.Interfaces; -using Mix.Queue.Models; using Mix.Queue.Models.QueueSetting; using Newtonsoft.Json; using System; diff --git a/src/platform/mix.queue/Engines/Google/GoogleQueueSubscriber.cs b/src/platform/mix.queue/Engines/Google/GoogleQueueSubscriber.cs index 3b9107ce3..7cc6e99c3 100644 --- a/src/platform/mix.queue/Engines/Google/GoogleQueueSubscriber.cs +++ b/src/platform/mix.queue/Engines/Google/GoogleQueueSubscriber.cs @@ -1,6 +1,5 @@ using Google.Apis.Auth.OAuth2; using Google.Cloud.PubSub.V1; -using Grpc.Auth; using Grpc.Core; using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; diff --git a/src/platform/mix.queue/Engines/PublisherBase.cs b/src/platform/mix.queue/Engines/PublisherBase.cs index 3a0ccda21..94aa75c22 100644 --- a/src/platform/mix.queue/Engines/PublisherBase.cs +++ b/src/platform/mix.queue/Engines/PublisherBase.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.ObjectPool; using Mix.Heart.Exceptions; using Mix.Mq.Lib.Models; -using Mix.Queue.Engines.MixQueue; using Mix.Queue.Interfaces; using Mix.Queue.Models.QueueSetting; using Mix.Shared.Services; @@ -132,7 +131,8 @@ protected virtual Task StartMixQueueEngine(CancellationToken cancellationToken = await publisher.SendMessages(inQueueItems); publishing = false; } - catch (Exception ex) { + catch (Exception ex) + { _logger.LogError(ex, $"{_logger.GetType().FullName}: Cannot Send message to queue"); await Task.Delay(1000, cancellationToken); } diff --git a/src/platform/mix.queue/Engines/RabitMq/RabbitModelPooledObjectPolicy.cs b/src/platform/mix.queue/Engines/RabitMq/RabbitModelPooledObjectPolicy.cs index bca6397b2..1a00f8ac9 100644 --- a/src/platform/mix.queue/Engines/RabitMq/RabbitModelPooledObjectPolicy.cs +++ b/src/platform/mix.queue/Engines/RabitMq/RabbitModelPooledObjectPolicy.cs @@ -29,12 +29,12 @@ private IConnection GetConnection() factory.Port = _options.Port.Value; } - if (!string.IsNullOrEmpty(_options.UserName) && !string.IsNullOrEmpty(_options.UserName)) + if (!string.IsNullOrEmpty(_options.UserName) && !string.IsNullOrEmpty(_options.Password)) { factory.UserName = _options.UserName; factory.Password = _options.Password; } - + if (!string.IsNullOrEmpty(_options.VHost)) { factory.VirtualHost = _options.VHost; diff --git a/src/platform/mix.queue/Engines/RabitMq/RabitMQSubscriber.cs b/src/platform/mix.queue/Engines/RabitMq/RabitMQSubscriber.cs index 8d37b8359..db6e1759c 100644 --- a/src/platform/mix.queue/Engines/RabitMq/RabitMQSubscriber.cs +++ b/src/platform/mix.queue/Engines/RabitMq/RabitMQSubscriber.cs @@ -1,16 +1,11 @@ -using Google.Cloud.PubSub.V1; -using Microsoft.Extensions.ObjectPool; +using Microsoft.Extensions.ObjectPool; using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; -using Mix.Queue.Models.QueueSetting; using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; -using System.Linq; -using System.Text; using System.Threading; -using System.Threading.Channels; using System.Threading.Tasks; namespace Mix.Queue.Engines.RabitMQ diff --git a/src/platform/mix.queue/Engines/RabitMq/RabitMqPublisher.cs b/src/platform/mix.queue/Engines/RabitMq/RabitMqPublisher.cs index 87a095ece..a359e8b0b 100644 --- a/src/platform/mix.queue/Engines/RabitMq/RabitMqPublisher.cs +++ b/src/platform/mix.queue/Engines/RabitMq/RabitMqPublisher.cs @@ -1,19 +1,16 @@ -using Mix.Mq.Lib.Models; +using Microsoft.Extensions.ObjectPool; +using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; -using System.Collections.Generic; -using System.Threading.Tasks; +using Newtonsoft.Json; using RabbitMQ.Client; -using Mix.Queue.Models.QueueSetting; using System; -using System.Threading.Channels; +using System.Collections.Generic; using System.Text; -using Microsoft.Extensions.ObjectPool; -using Google.Api; -using Newtonsoft.Json; +using System.Threading.Tasks; namespace Mix.Queue.Engines.RabitMQ { - public class RabitMQPublisher : IQueuePublisher + public class RabitMQPublisher : IQueuePublisher where T : MessageQueueModel { private DefaultObjectPool _objectPool; diff --git a/src/platform/mix.queue/Engines/SubscriberBase.cs b/src/platform/mix.queue/Engines/SubscriberBase.cs index b90fa8e35..f98d484ef 100644 --- a/src/platform/mix.queue/Engines/SubscriberBase.cs +++ b/src/platform/mix.queue/Engines/SubscriberBase.cs @@ -1,13 +1,8 @@ -using Azure.Core; -using Google.Api; -using Google.Apis.Logging; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; -using Mix.Heart.Enums; using Mix.Heart.Exceptions; using Mix.Heart.Helpers; using Mix.Heart.Services; @@ -16,8 +11,6 @@ using Mix.Queue.Engines.RabitMQ; using Mix.Queue.Interfaces; using Mix.Queue.Models.QueueSetting; -using Mix.Queue.Services; -using Mix.Shared.Helpers; using Mix.Shared.Services; using System; using System.Threading; @@ -36,7 +29,7 @@ public abstract class SubscriberBase : BackgroundService protected MixCacheService CacheService; protected readonly IServiceProvider ServicesProvider; protected IServiceScope ServiceScope { get; set; } - protected ILogger _logger { get; set; } + protected ILogger Logger { get; set; } private readonly IPooledObjectPolicy _rabbitMqObjectPolicy; protected SubscriberBase( @@ -47,7 +40,7 @@ protected SubscriberBase( IConfiguration configuration, IMemoryQueueService queueService, ILogger logger, - IPooledObjectPolicy rabbitMqObjectPolicy) + IPooledObjectPolicy? rabbitMqObjectPolicy) { _timeout = timeout; _configuration = configuration; @@ -55,7 +48,7 @@ protected SubscriberBase( _moduleName = moduleName; _memQueueService = queueService; ServicesProvider = servicesProvider; - _logger = logger; + Logger = logger; _rabbitMqObjectPolicy = rabbitMqObjectPolicy; } protected async override Task ExecuteAsync(CancellationToken cancellationToken) @@ -73,14 +66,14 @@ public virtual async Task StopAsync(CancellationToken cancellationToken) Console.Error.WriteLine($"{_subscriber.SubscriptionId} stopped at {DateTime.UtcNow}"); if (_subscriber is MixQueueSubscriber) { - await (_subscriber as MixQueueSubscriber).Disconnect(); + await (_subscriber as MixQueueSubscriber).Disconnect(cancellationToken); } } #region Privates private async Task StartProcessQueue(CancellationToken cancellationToken) { - _logger.LogInformation($"StartProcessQueue: {_subscriber.SubscriptionId} started at {DateTime.UtcNow.AddHours(7)}"); + Logger.LogInformation($"StartProcessQueue: {_subscriber.SubscriptionId} started at {DateTime.UtcNow.AddHours(7)}"); while (!cancellationToken.IsCancellationRequested) { try @@ -88,14 +81,8 @@ private async Task StartProcessQueue(CancellationToken cancellationToken) if (_subscriber != null) { - await _subscriber.ProcessQueue(cancellationToken); } - await Task.Delay(1000, cancellationToken); - if (_subscriber is MixQueueSubscriber) - { - await (_subscriber as MixQueueSubscriber).Disconnect(); - } } catch (Exception ex) { @@ -104,14 +91,19 @@ private async Task StartProcessQueue(CancellationToken cancellationToken) await (_subscriber as MixQueueSubscriber).Disconnect(); } - _logger.LogError($"StartProcessQueue: {_subscriber.SubscriptionId} is broken at {DateTime.UtcNow.AddHours(7)}, Trying to reconnect from client: {ex.Message}", ex); + Logger.LogError($"StartProcessQueue: {_subscriber.SubscriptionId} is broken at {DateTime.UtcNow.AddHours(7)}, Trying to reconnect from client: {ex.Message}", ex); await Task.Delay(2000, cancellationToken); - _subscriber = CreateSubscriber(_topicId, $"{_topicId}_{_moduleName}"); + _subscriber = CreateSubscriber(_topicId, _subscriber.SubscriptionId); await StartProcessQueue(cancellationToken); } } - _logger.LogInformation($"StartProcessQueue: {_subscriber.SubscriptionId} stopped at {DateTime.UtcNow.AddHours(7)}"); + await Task.Delay(1000, cancellationToken); + if (_subscriber is MixQueueSubscriber) + { + await (_subscriber as MixQueueSubscriber).Disconnect(); + } + Logger.LogInformation($"StartProcessQueue: {_subscriber.SubscriptionId} stopped at {DateTime.UtcNow.AddHours(7)}"); } private IQueueSubscriber CreateSubscriber(string topicId, string subscriptionId) @@ -142,7 +134,7 @@ private IQueueSubscriber CreateSubscriber(string topicId, string subscriptionId) return QueueEngineFactory.CreateSubscriber( provider, googleSetting, topicId, subscriptionId, MessageHandler, _memQueueService, mixEndpointService); case MixQueueProvider.RABBITMQ: - return QueueEngineFactory.CreateRabbitMQSubscriber(_rabbitMqObjectPolicy, topicId,subscriptionId, MessageHandler); + return QueueEngineFactory.CreateRabbitMQSubscriber(_rabbitMqObjectPolicy, topicId, subscriptionId, MessageHandler); case MixQueueProvider.MIX: if (string.IsNullOrEmpty(mixEndpointService.MixMq)) { @@ -170,7 +162,7 @@ private IQueueSubscriber CreateSubscriber(string topicId, string subscriptionId) return ServiceScope.ServiceProvider.GetRequiredService(); } - public async Task MessageHandler(MessageQueueModel data) + public virtual async Task MessageHandler(MessageQueueModel data) { try { diff --git a/src/platform/mix.queue/Extensions/QueueServiceCollectionExtension.cs b/src/platform/mix.queue/Extensions/QueueServiceCollectionExtension.cs index 752731e2b..e3178a439 100644 --- a/src/platform/mix.queue/Extensions/QueueServiceCollectionExtension.cs +++ b/src/platform/mix.queue/Extensions/QueueServiceCollectionExtension.cs @@ -1,15 +1,10 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.ObjectPool; using Mix.Queue.Engines.RabitMQ; using Mix.Queue.Models.QueueSetting; using RabbitMQ.Client; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Queue.Extensions { @@ -48,14 +43,14 @@ public static IServiceCollection AddGooglePubSub(this IHostApplicationBuilder bu return builder.Services; } - public static IServiceCollection AddMixMQ(this IHostApplicationBuilder builder) + public static IServiceCollection AddMixMQ(this IHostApplicationBuilder builder) { var config = builder.Configuration.GetSection("MessageQueueSetting:Mix"); builder.Services.Configure(config); return builder.Services; } - + public static IServiceCollection AddAzureServiceBus(this IHostApplicationBuilder builder) { var config = builder.Configuration.GetSection("MessageQueueSetting:AzureServiceBus"); @@ -63,7 +58,7 @@ public static IServiceCollection AddAzureServiceBus(this IHostApplicationBuilder return builder.Services; } - + public static IServiceCollection AddRabbit(this IHostApplicationBuilder builder) { var rabbitConfig = builder.Configuration.GetSection("MessageQueueSetting:RabitMqQueueSetting"); diff --git a/src/platform/mix.queue/Models/GrpcChannelModel.cs b/src/platform/mix.queue/Models/GrpcChannelModel.cs index 4f2585465..e8d5c7456 100644 --- a/src/platform/mix.queue/Models/GrpcChannelModel.cs +++ b/src/platform/mix.queue/Models/GrpcChannelModel.cs @@ -1,10 +1,8 @@ -using Grpc.Core; -using Grpc.Net.Client; +using Grpc.Net.Client; +using Grpc.Net.Client.Web; using Microsoft.AspNetCore.Http; using System; using System.Net.Http; -using System.Threading.Tasks; -using Grpc.Net.Client.Web; namespace Mix.Queue.Models { diff --git a/src/platform/mix.queue/Models/MessageQueueModel.cs b/src/platform/mix.queue/Models/MessageQueueModel.cs index ef95bb122..846160af0 100644 --- a/src/platform/mix.queue/Models/MessageQueueModel.cs +++ b/src/platform/mix.queue/Models/MessageQueueModel.cs @@ -1,5 +1,4 @@ using Mix.Heart.Helpers; -using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; diff --git a/src/platform/mix.queue/Models/MixSubscribtionModel.cs b/src/platform/mix.queue/Models/MixSubscribtionModel.cs index ed20e6ff4..1cbc453a1 100644 --- a/src/platform/mix.queue/Models/MixSubscribtionModel.cs +++ b/src/platform/mix.queue/Models/MixSubscribtionModel.cs @@ -1,6 +1,4 @@ -using Mix.Constant.Enums; - -namespace Mix.Mq.Lib.Models +namespace Mix.Mq.Lib.Models { public class MixSubscriptionModel { diff --git a/src/platform/mix.queue/Models/MixTopicModel.cs b/src/platform/mix.queue/Models/MixTopicModel.cs index 4f5626353..7baf613c3 100644 --- a/src/platform/mix.queue/Models/MixTopicModel.cs +++ b/src/platform/mix.queue/Models/MixTopicModel.cs @@ -1,7 +1,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using Mix.Constant.Enums; namespace Mix.Mq.Lib.Models { diff --git a/src/platform/mix.queue/Models/QueueSetting/IQueueSetting.cs b/src/platform/mix.queue/Models/QueueSetting/IQueueSetting.cs index fa03d978a..2ef98eecb 100644 --- a/src/platform/mix.queue/Models/QueueSetting/IQueueSetting.cs +++ b/src/platform/mix.queue/Models/QueueSetting/IQueueSetting.cs @@ -2,6 +2,6 @@ { public interface IQueueSetting { - + } } diff --git a/src/platform/mix.queue/Services/MemoryQueueService.cs b/src/platform/mix.queue/Services/MemoryQueueService.cs index 95a5e5300..9e6fd3c09 100644 --- a/src/platform/mix.queue/Services/MemoryQueueService.cs +++ b/src/platform/mix.queue/Services/MemoryQueueService.cs @@ -77,7 +77,6 @@ public void PushMemoryQueue(MessageQueueModel model) queue.Enqueue(model); EnqueueLog(model); } - } public void PushMemoryQueue(int tenantId, string topicId, string action, object data) diff --git a/src/platform/mix.queue/mix.queue.csproj b/src/platform/mix.queue/mix.queue.csproj index 2490ac833..4049de3f3 100644 --- a/src/platform/mix.queue/mix.queue.csproj +++ b/src/platform/mix.queue/mix.queue.csproj @@ -15,16 +15,15 @@ - + - - - - - - - - + + + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/platform/mix.repodb/Dtos/AlterColumnDto.cs b/src/platform/mix.repodb/Dtos/AlterColumnDto.cs index c073f6834..1e5e69e6b 100644 --- a/src/platform/mix.repodb/Dtos/AlterColumnDto.cs +++ b/src/platform/mix.repodb/Dtos/AlterColumnDto.cs @@ -1,11 +1,11 @@ using Mix.Constant.Enums; using Mix.Shared.Models; -using Newtonsoft.Json.Linq; namespace Mix.RepoDb.Dtos { public class AlterColumnDto { + public bool IsDrop { get; set; } public string SystemName { get; set; } public string DisplayName { get; set; } public string MixDatabaseName { get; set; } diff --git a/src/platform/mix.repodb/Helpers/MixDbHelper.cs b/src/platform/mix.repodb/Helpers/MixDbHelper.cs index 6ddd7c14a..044f90846 100644 --- a/src/platform/mix.repodb/Helpers/MixDbHelper.cs +++ b/src/platform/mix.repodb/Helpers/MixDbHelper.cs @@ -6,7 +6,6 @@ using Mix.RepoDb.ViewModels; using Mix.Service.Services; using Mix.Shared.Services; -using MySqlX.XDevAPI.Common; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -14,7 +13,7 @@ namespace Mix.RepoDb.Helpers { public class MixDbHelper { - public static Task ParseDtoToEntityAsync(JObject dto, List columns, FieldNameService fieldNameService, int? tenantId = null, string? username = null) + public static Task ParseDtoToEntityAsync(JObject dto, MixDatabaseType mixdbType, List columns, FieldNameService fieldNameService, int? tenantId = null, string? username = null) { try { @@ -25,7 +24,7 @@ public static Task ParseDtoToEntityAsync(JObject dto, List c.SystemName.Equals(colName, StringComparison.InvariantCultureIgnoreCase)); if (encryptedColumnNames.Contains(colName)) @@ -50,18 +49,13 @@ public static Task ParseDtoToEntityAsync(JObject dto, List ParseDtoToEntityAsync(JObject dto, List GetSingleByParent(string tableName, MixContentType parentType, int parentId, bool loadNestedData = false); + public Task GetSingleByParent(string tableName, MixContentType parentType, object parentId, bool loadNestedData = false); public Task> GetMyData(string tableName, SearchMixDbRequestDto req, string username); - public Task GetMyDataById(string tableName, string username, int id, bool loadNestedData); + public Task GetMyDataById(string tableName, string username, object id, bool loadNestedData); - public Task GetById(string tableName, int id, bool loadNestedData); + public Task GetById(string tableName, object id, bool loadNestedData); public Task GetSingleBy(string tableName, List queries); - public Task CreateData(string tableName, JObject data); + public Task CreateData(string tableName, JObject data); public Task UpdateData(string tableName, JObject data); - public Task DeleteData(string tableName, int id); + public Task DeleteData(string tableName, object id); void SetUOW(UnitOfWorkInfo uow); Task ParseDataAsync(string tableName, dynamic obj); Task GetSingleByGuidParent(string tableName, MixContentType parentType, Guid parentId, bool loadNestedData = false); - Task CreateDataRelationship(CreateDataRelationshipDto dto, CancellationToken cancellationToken); - Task DeleteDataRelationship(string relTableName, int id, CancellationToken cancellationToken); + Task CreateDataRelationship(CreateDataRelationshipDto dto, CancellationToken cancellationToken); + Task DeleteDataRelationship(string relTableName, object id, CancellationToken cancellationToken); Task> ParseListDataAsync(string tableName, List objs); + Task> LoadNestedData(RepoDbMixDatabaseViewModel database, FieldNameService fieldNameService, object parentId); } } diff --git a/src/platform/mix.repodb/Interfaces/IMixDbService.cs b/src/platform/mix.repodb/Interfaces/IMixDbService.cs index a76df9204..ca30f32b4 100644 --- a/src/platform/mix.repodb/Interfaces/IMixDbService.cs +++ b/src/platform/mix.repodb/Interfaces/IMixDbService.cs @@ -1,10 +1,6 @@ -using Mix.Constant.Enums; -using Mix.Database.Entities.Cms; -using Mix.Heart.Models; +using Mix.Database.Entities.Cms; using Mix.RepoDb.Dtos; using Mix.RepoDb.ViewModels; -using Mix.Shared.Dtos; -using Newtonsoft.Json.Linq; namespace Mix.RepoDb.Interfaces { diff --git a/src/platform/mix.repodb/Publishers/MixRepoDbPublisher.cs b/src/platform/mix.repodb/Publishers/MixRepoDbPublisher.cs index ff9b0ce23..5e1d3425c 100644 --- a/src/platform/mix.repodb/Publishers/MixRepoDbPublisher.cs +++ b/src/platform/mix.repodb/Publishers/MixRepoDbPublisher.cs @@ -4,7 +4,6 @@ using Mix.Constant.Constants; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; -using Mix.Queue.Engines.MixQueue; using Mix.Queue.Interfaces; using Mix.Shared.Services; diff --git a/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs b/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs index 2c2f6a7ed..392f5394c 100644 --- a/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs +++ b/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs @@ -2,7 +2,6 @@ using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; -using Microsoft.Extensions.Options; using Mix.Constant.Constants; using Mix.Constant.Enums; using Mix.Database.Entities.Cms; @@ -26,8 +25,6 @@ using RepoDb.Enumerations; using RepoDb.Interfaces; using System.Data; -using System.Reflection.Metadata; -using static Microsoft.EntityFrameworkCore.DbLoggerCategory; namespace Mix.RepoDb.Repositories { @@ -47,7 +44,7 @@ public class MixRepoDbRepository : IDisposable private bool _isRoot = true; #endregion - public MixRepoDbRepository(ICache cache, DatabaseService databaseService, UnitOfWorkInfo cmsUow) + public MixRepoDbRepository(ICache cache, DatabaseService databaseService) { Cache = cache; _settings = new AppSetting() @@ -129,7 +126,7 @@ public async Task> GetPagingAsync(IEnumerable orderFields = new() { - new OrderField(pagingRequest.SortBy ?? "Id", pagingRequest.SortDirection == SortDirection.Asc ? Order.Ascending: Order.Descending) + new OrderField(pagingRequest.SortBy, pagingRequest.SortDirection == SortDirection.Asc ? Order.Ascending: Order.Descending) }; BeginTransaction(); var count = (int)_connection.Count(_tableName, queryFields, transaction: _dbTransaction); @@ -339,7 +336,7 @@ private Operation ParseMixOperator(SearchQueryField field) } } - public async Task InsertAsync(JObject obj, RepoDbMixDatabaseViewModel mixDb) + public async Task InsertAsync(JObject obj, RepoDbMixDatabaseViewModel mixDb) { try { @@ -347,13 +344,14 @@ public async Task InsertAsync(JObject obj, RepoDbMixDatabaseViewModel mixD Dictionary dicObj = ParseDictionary(obj, mixDb); var fields = dicObj!.Keys.Select(m => new Field(m)).ToList(); - var result = await _connection.InsertAsync( - _tableName, + var result = await _connection.InsertAsync( + mixDb.SystemName, entity: dicObj, fields: fields, commandTimeout: _settings.CommandTimeout, transaction: _dbTransaction, trace: _trace); + CompleteTransaction(); return result; } catch (Exception ex) @@ -387,7 +385,7 @@ public async Task InsertAsync(JObject obj, RepoDbMixDatabaseViewModel mixD BeginTransaction(); var result = await _connection.InsertAllAsync( - _tableName, + mixDb.SystemName, entities: dicObjs, fields: fields, commandTimeout: _settings.CommandTimeout, @@ -426,7 +424,7 @@ public async Task InsertAsync(JObject obj, RepoDbMixDatabaseViewModel mixD } } - public async Task UpdateAsync(int id, JObject entity, RepoDbMixDatabaseViewModel mixDb) + public async Task UpdateAsync(object id, JObject entity, RepoDbMixDatabaseViewModel mixDb) { try { @@ -450,11 +448,11 @@ public async Task InsertAsync(JObject obj, RepoDbMixDatabaseViewModel mixD { RollbackTransaction(); await MixLogService.LogExceptionAsync(ex); - return default; + throw ex; } } - public async Task DeleteAsync(int id, FieldNameService fieldNameService) + public async Task DeleteAsync(object id, FieldNameService fieldNameService) { try { @@ -643,6 +641,7 @@ public void CompleteTransaction() if ((_isRoot || DatabaseProvider == MixDatabaseProvider.SQLITE) && _dbTransaction?.Connection != null) { _dbTransaction.Commit(); + _dbTransaction = null; } } @@ -675,18 +674,23 @@ public void Dispose() } } _connection.Close(); + _connection.Dispose(); } } private Dictionary ParseDictionary(JObject obj, RepoDbMixDatabaseViewModel mixDb) { var dicObj = obj.ToObject>(); - + var fieldNameService = new FieldNameService(mixDb.NamingConvention); // npgsql cannot auto parse from string to Guid var guidCols = mixDb.Columns.Where(c => c.DataType == MixDataType.Guid).ToList(); + if (dicObj != null && mixDb.Type == MixDatabaseType.GuidService && dicObj[fieldNameService.Id] != null) + { + dicObj[fieldNameService.Id] = Guid.Parse(dicObj[fieldNameService.Id].ToString()!); + } foreach (var item in guidCols) { - var colTitle = item.SystemName.ToTitleCase(); + var colTitle = item.SystemName; if (dicObj.ContainsKey(colTitle) && dicObj[colTitle] != null) { dicObj[colTitle] = Guid.Parse(dicObj[colTitle].ToString()!); diff --git a/src/platform/mix.repodb/ServiceCollectionExtensions.cs b/src/platform/mix.repodb/ServiceCollectionExtensions.cs index 6d2a327c4..d6eac8865 100644 --- a/src/platform/mix.repodb/ServiceCollectionExtensions.cs +++ b/src/platform/mix.repodb/ServiceCollectionExtensions.cs @@ -1,11 +1,8 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Mix.RepoDb.Interfaces; -using Mix.RepoDb.Publishers; using Mix.RepoDb.Repositories; using Mix.RepoDb.Services; -using Mix.RepoDb.Subscribers; using Mix.Shared.Models.Configurations; -using Mix.Shared.Services; using RepoDb; using RepoDb.Interfaces; @@ -16,7 +13,7 @@ public static class ServiceCollectionExtensions public static IServiceCollection AddMixRepoDb(this IServiceCollection services, GlobalSettingsModel globalConfig) { services.TryAddScoped(); - + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); diff --git a/src/platform/mix.repodb/Services/MixDbDataService.cs b/src/platform/mix.repodb/Services/MixDbDataService.cs index c2fdd9f87..c8c835bee 100644 --- a/src/platform/mix.repodb/Services/MixDbDataService.cs +++ b/src/platform/mix.repodb/Services/MixDbDataService.cs @@ -1,32 +1,32 @@ using Microsoft.AspNetCore.Http; +using Mix.Constant.Constants; using Mix.Constant.Enums; using Mix.Database.Entities.Cms; +using Mix.Database.Entities.MixDb; using Mix.Database.Services; using Mix.Heart.Enums; +using Mix.Heart.Exceptions; +using Mix.Heart.Extensions; using Mix.Heart.Helpers; using Mix.Heart.Models; +using Mix.Heart.Services; using Mix.Heart.UnitOfWork; +using Mix.Lib.Interfaces; +using Mix.RepoDb.Dtos; +using Mix.RepoDb.Helpers; +using Mix.RepoDb.Interfaces; using Mix.RepoDb.Repositories; using Mix.RepoDb.ViewModels; +using Mix.Service.Interfaces; using Mix.Service.Services; using Mix.Shared.Dtos; using Mix.Shared.Models; +using Mix.Shared.Services; using Newtonsoft.Json.Linq; -using RepoDb.Interfaces; using RepoDb; using RepoDb.Enumerations; -using Mix.Heart.Extensions; -using Mix.RepoDb.Interfaces; -using Mix.Service.Interfaces; -using Mix.Constant.Constants; -using Mix.Heart.Services; -using Mix.Shared.Services; -using Mix.Database.Entities.MixDb; -using Newtonsoft.Json; -using Mix.Lib.Interfaces; -using Mix.Heart.Exceptions; -using Mix.RepoDb.Helpers; -using Mix.RepoDb.Dtos; +using RepoDb.Interfaces; +using System.Linq.Expressions; namespace Mix.RepoDb.Services { @@ -67,7 +67,7 @@ public void SetUOW(UnitOfWorkInfo uow) #region Implements - public async Task GetSingleByParent(string tableName, MixContentType parentType, int parentId, bool loadNestedData = false) + public async Task GetSingleByParent(string tableName, MixContentType parentType, object parentId, bool loadNestedData = false) { await InitRepository(tableName); var data = await _repository.GetSingleByParentAsync(parentType, parentId, _fieldNameService); @@ -77,7 +77,7 @@ public void SetUOW(UnitOfWorkInfo uow) if (loadNestedData) { var id = result.Value(_fieldNameService.Id); - await LoadNestedData(_mixDb, _fieldNameService, id); + result.Add(await LoadNestedData(_mixDb, _fieldNameService, id)); } return result; } @@ -115,7 +115,7 @@ public async Task> GetMyData(string tableName, Sear return await GetResult(tableName, queries, paging, req.LoadNestedData); } - public async Task GetMyDataById(string tableName, string username, int id, bool loadNestedData) + public async Task GetMyDataById(string tableName, string username, object id, bool loadNestedData) { await InitRepository(tableName); var queries = new List() @@ -151,7 +151,7 @@ public async Task> GetMyData(string tableName, Sear return default; } - public async Task GetById(string tableName, int id, bool loadNestedData) + public async Task GetById(string tableName, object id, bool loadNestedData) { await InitRepository(tableName); var obj = await _repository.GetSingleAsync(new QueryField(_fieldNameService.Id, id)); @@ -185,7 +185,7 @@ public async Task> GetMyData(string tableName, Sear return default; } - public async Task CreateData(string tableName, JObject data) + public async Task CreateData(string tableName, JObject data) { try { @@ -225,7 +225,7 @@ public async Task CreateData(string tableName, JObject data) throw new MixException(MixErrorStatus.Badrequest, ex); } } - public async Task DeleteData(string tableName, int id) + public async Task DeleteData(string tableName, object id) { try { @@ -284,27 +284,8 @@ public async Task> ParseListDataAsync(string tableName, List> LoadNestedData(RepoDbMixDatabaseViewModel database, FieldNameService fieldNameService, - int? parentId = null, - Guid? guidParentId = null) + public async Task> LoadNestedData(RepoDbMixDatabaseViewModel database, FieldNameService fieldNameService, + object parentId) { List result = new(); foreach (var item in database.Relationships) @@ -315,24 +296,39 @@ private async Task> LoadNestedData(RepoDbMixDatabaseViewModel da var relDb = await GetMixDatabase(GetRelationshipDbName(_mixDb)); var relFieldName = new FieldNameService(relDb.NamingConvention); _repository.InitTableName(relDb.SystemName); - result.Add(await LoadManyToManyData(relFieldName, item, fieldNameService, parentId, guidParentId: guidParentId)); + result.Add(await LoadManyToManyData(relFieldName, item, fieldNameService, parentId)); } else if (item.Type == MixDatabaseRelationshipType.OneToMany) { - result.Add(await LoadOneToManyData(item, fieldNameService, parentId, guidParentId)); + result.Add(await LoadOneToManyData(item, fieldNameService, parentId)); } } return result; } + #endregion + + #region Helper + private string GetRelationshipDbName(RepoDbMixDatabaseViewModel mixdb) + { + string relName = mixdb.NamingConvention == MixDatabaseNamingConvention.SnakeCase + ? MixDatabaseNames.DATA_RELATIONSHIP_SNAKE_CASE + : MixDatabaseNames.DATA_RELATIONSHIP_TITLE_CASE; + return mixdb.MixDatabaseContextId.HasValue + ? $"{mixdb.MixDatabaseContext.SystemName}_{relName}" + : MixDatabaseNames.SYSTEM_DATA_RELATIONSHIP; + } + public static string GetCacheFolder(string databaseName) + { + return $"{MixFolders.MixDbCacheFolder}/{databaseName}"; + } + - private async Task LoadOneToManyData(MixDatabaseRelationshipViewModel item, FieldNameService fieldNameService, int? parentId, Guid? guidParentId) + + private async Task LoadOneToManyData(MixDatabaseRelationshipViewModel item, FieldNameService fieldNameService, object parentId) { - JObject data = new JObject(); string pIdName = fieldNameService.GetParentId(item.SourceDatabaseName); _repository.InitTableName(item.DestinateDatabaseName); - List query = parentId.HasValue - ? new() { new(pIdName, Operation.Equal, parentId) } - : new() { new(pIdName, Operation.Equal, guidParentId) }; + List query = new() { new(pIdName, Operation.Equal, parentId) }; var nestedData = await _repository.GetListByAsync(query); JArray result = new(); @@ -347,15 +343,19 @@ private async Task LoadOneToManyData(MixDatabaseRelationshipViewModel } - private async Task LoadManyToManyData(FieldNameService relFieldName, MixDatabaseRelationshipViewModel item, FieldNameService fieldNameService, int? parentId, Guid? guidParentId) + private async Task LoadManyToManyData(FieldNameService relFieldName, MixDatabaseRelationshipViewModel item, FieldNameService fieldNameService, + object parentId) { List queries = GetAssociationQueries(relFieldName, item.SourceDatabaseName, item.DestinateDatabaseName, - parentId: parentId, - guidParentId: guidParentId); + parentId: parentId); var associations = await _repository.GetListByAsync(queries); if (associations is { Count: > 0 }) { - var nestedIds = JArray.FromObject(associations).Select(m => m.Value(fieldNameService.ChildId)).ToList(); + var childDb = await GetMixDatabase(item.DestinateDatabaseName); + var nestedIds = + childDb.Type == MixDatabaseType.GuidService + ? JArray.FromObject(associations).Select(m => m.Value(fieldNameService.GuidChildId)).ToList() + : JArray.FromObject(associations).Select(m => m.Value(fieldNameService.ChildId)).ToList(); _repository.InitTableName(item.DestinateDatabaseName); List query = new() { new(fieldNameService.Id, Operation.In, nestedIds) }; var nestedData = await _repository.GetListByAsync(query); @@ -394,7 +394,12 @@ private async Task> GetResult(string tableName, IEn return new PagingResponseModel { Items = items, PagingData = result.PagingData }; } - private List GetAssociationQueries(FieldNameService fieldNameService, string? parentDatabaseName = null, string? childDatabaseName = null, int? parentId = null, int? childId = null, Guid? guidParentId = null, Guid? guidChildId = null) + private List GetAssociationQueries( + FieldNameService fieldNameService, + string? parentDatabaseName = null, + string? childDatabaseName = null, + object? parentId = null, + object? childId = null) { var queries = new List(); if (!string.IsNullOrEmpty(parentDatabaseName)) @@ -405,22 +410,29 @@ private List GetAssociationQueries(FieldNameService fieldNameService { queries.Add(new QueryField(fieldNameService.ChildDatabaseName, childDatabaseName)); } - if (parentId.HasValue) - { - queries.Add(new QueryField(fieldNameService.ParentId, parentId)); - } - if (childId.HasValue) - { - queries.Add(new QueryField(fieldNameService.Id, parentId)); - } - if (guidParentId.HasValue) + if (parentId != null) { - queries.Add(new QueryField(fieldNameService.GuidParentId, guidParentId)); + if (parentId.GetType() == typeof(int)) + { + queries.Add(new QueryField(fieldNameService.ParentId, parentId)); + } + else if (parentId.GetType() == typeof(Guid)) + { + queries.Add(new QueryField(fieldNameService.GuidParentId, parentId)); + } } - if (guidChildId.HasValue) + if (childId != null) { - queries.Add(new QueryField(fieldNameService.GuidChildId, guidChildId)); + if (childId.GetType() == typeof(int)) + { + queries.Add(new QueryField(fieldNameService.Id, parentId)); + } + else if (childId.GetType() == typeof(Guid)) + { + queries.Add(new QueryField(fieldNameService.GuidChildId, childId)); + } } + return queries; } @@ -439,9 +451,10 @@ private List GetAssociationQueries(FieldNameService fieldNameService private async Task> BuildSearchQueryAsync(string tableName, SearchMixDbRequestDto request) { var queries = BuildSearchPredicate(request); - if (request.ParentId.HasValue) + if (request.ObjParentId != null) { var database = await GetMixDatabase(tableName); + var parentDb = await GetMixDatabase(request.ParentName); if (database is null) { return queries; @@ -453,10 +466,24 @@ private async Task> BuildSearchQueryAsync(string tableName, Sea } else { - var allowsIds = _cmsUow.DbContext.MixDatabaseAssociation - .Where(m => m.ParentDatabaseName == request.ParentName && m.ParentId == request.ParentId.Value && m.ChildDatabaseName == tableName) - .Select(m => m.ChildId).ToList(); - queries.Add(new(_fieldNameService.Id, Operation.In, allowsIds)); + Expression> predicate = m => m.ParentDatabaseName == request.ParentName + && m.ChildDatabaseName == tableName; + predicate = predicate.AndAlsoIf(parentDb.Type == MixDatabaseType.GuidService, + m => m.GuidParentId == (Guid)request.ObjParentId); + predicate = predicate.AndAlsoIf(parentDb.Type != MixDatabaseType.GuidService, + m => m.ParentId == (int)request.ObjParentId); + + var childIdsQuery = _cmsUow.DbContext.MixDatabaseAssociation + .Where(predicate); + if (database.Type == MixDatabaseType.GuidService) + { + queries.Add(new(_fieldNameService.Id, Operation.In, childIdsQuery.Select(m => m.GuidChildId).ToList())); + } + else + { + queries.Add(new(_fieldNameService.Id, Operation.In, childIdsQuery.Select(m => m.ChildId).ToList())); + } + } } @@ -603,7 +630,7 @@ private async Task ParseDto(string tableName, JObject dto) } else { - result.Add(new JProperty(pr.Name, col!=null? MixDbHelper.ParseObjectValue(col.DataType, pr.Value): pr.Value)); + result.Add(new JProperty(pr.Name, col != null ? MixDbHelper.ParseObjectValue(col.DataType, pr.Value) : pr.Value)); } } @@ -661,7 +688,7 @@ public void Dispose() _cmsUow.Dispose(); } - public async Task CreateDataRelationship(CreateDataRelationshipDto dto, CancellationToken cancellationToken) + public async Task CreateDataRelationship(CreateDataRelationshipDto dto, CancellationToken cancellationToken) { try { @@ -691,7 +718,7 @@ public void Dispose() } } - public async Task DeleteDataRelationship(string relTableName, int id, CancellationToken cancellationToken) + public async Task DeleteDataRelationship(string relTableName, object id, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try diff --git a/src/platform/mix.repodb/Services/MixDbService.cs b/src/platform/mix.repodb/Services/MixDbService.cs index 79af90a33..ed3eb32ed 100644 --- a/src/platform/mix.repodb/Services/MixDbService.cs +++ b/src/platform/mix.repodb/Services/MixDbService.cs @@ -1,7 +1,5 @@ using Microsoft.AspNetCore.Http; -using Microsoft.Azure.Amqp.Framing; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Internal; using Mix.Constant.Constants; using Mix.Constant.Enums; using Mix.Database.Base; @@ -11,11 +9,10 @@ using Mix.Heart.Enums; using Mix.Heart.Exceptions; using Mix.Heart.Extensions; -using Mix.Heart.Helpers; -using Mix.Heart.Models; using Mix.Heart.Services; using Mix.Heart.UnitOfWork; using Mix.Lib.Interfaces; +using Mix.Mixdb.Services; using Mix.RepoDb.Dtos; using Mix.RepoDb.Entities; using Mix.RepoDb.Interfaces; @@ -24,15 +21,13 @@ using Mix.Service.Interfaces; using Mix.Service.Services; using Mix.Shared.Dtos; -using Mix.Shared.Models; -using MySqlX.XDevAPI.Common; using Newtonsoft.Json.Linq; using RepoDb; using RepoDb.Enumerations; using RepoDb.Interfaces; using System.Dynamic; using System.Linq.Dynamic.Core; -using ZstdSharp.Unsafe; +using System.Linq.Expressions; namespace Mix.RepoDb.Services { @@ -45,6 +40,7 @@ public class MixDbService : TenantServiceBase, IMixDbService, IDisposable private MixRepoDbRepository _repository; private MixRepoDbRepository _backupRepository; private IMixMemoryCacheService _memoryCache; + private RuntimeDbContextService _runtimeDbContextService; private readonly UnitOfWorkInfo _cmsUow; @@ -67,7 +63,7 @@ public MixDbService( _cmsUow = uow; _databaseService = databaseService; _repository = repository; - _backupRepository = new MixRepoDbRepository(cache, databaseService, uow); + _backupRepository = new MixRepoDbRepository(cache, databaseService); _databaseProvider = _databaseService.DatabaseProvider; _databaseConstant = _databaseProvider switch { @@ -78,6 +74,7 @@ public MixDbService( _ => throw new NotImplementedException() }; _memoryCache = memoryCache; + _runtimeDbContextService = new RuntimeDbContextService(httpContextAccessor, databaseService); } #region Methods @@ -121,37 +118,57 @@ public async Task DropColumn(RepoDbMixDatabaseColumnViewModel col) public async Task AlterColumn(AlterColumnDto colDto) { - var database = await GetMixDatabase(colDto.MixDatabaseName); - if (database == null) + try { - throw new MixException(MixErrorStatus.Badrequest, $"Invalid table {colDto.MixDatabaseName}"); + + var database = await GetMixDatabase(colDto.MixDatabaseName); + if (database == null) + { + throw new MixException(MixErrorStatus.Badrequest, $"Invalid table {colDto.MixDatabaseName}"); + } + var col = new RepoDbMixDatabaseColumnViewModel(colDto); + if (database.MixDatabaseContextId.HasValue) + { + await SwitchDbContext(database.MixDatabaseContext); + } + + var alterCommandText = colDto.IsDrop + ? $"{GenerateDropColumnSql(col)}; {GenerateAddColumnSql(col)};" + : GenerateAlterColumnSql(col); + var result = await _repository.ExecuteCommand(alterCommandText); + _repository.CompleteTransaction(); + return result >= 0; } - var col = new RepoDbMixDatabaseColumnViewModel(colDto); - if (database.MixDatabaseContextId.HasValue) + catch (Exception ex) { - await SwitchDbContext(database.MixDatabaseContext); + throw new MixException(MixErrorStatus.ServerError, ex); } - var dropCommandText = GenerateAlterColumnSql(col); - var result = await _repository.ExecuteCommand(dropCommandText); - _repository.CompleteTransaction(); - return result >= 0; } public async Task MigrateDatabase(RepoDbMixDatabaseViewModel database) { - if (database.MixDatabaseContextId.HasValue) + try { - await SwitchDbContext(database.MixDatabaseContext); - } + if (database.MixDatabaseContextId.HasValue) + { + await SwitchDbContext(database.MixDatabaseContext); + } - if (database is { Columns.Count: > 0 }) + if (database is { Columns.Count: > 0 }) + { + await Migrate(database, _databaseProvider, _repository); + _repository.CompleteTransaction(); + return true; + } + return false; + } + catch (Exception ex) { - await Migrate(database, _databaseProvider, _repository); - _repository.CompleteTransaction(); - return true; + throw new MixException(MixErrorStatus.Badrequest, ex); } - return false; } + + public async Task BackupDatabase(RepoDbMixDatabaseViewModel database, CancellationToken cancellationToken = default) { if (database != null) @@ -357,9 +374,10 @@ private string GetRelationshipDbName(RepoDbMixDatabaseViewModel mixDb) private async Task> BuildSearchQueryAsync(string tableName, SearchMixDbRequestDto request, FieldNameService fieldNameService) { var queries = BuildSearchPredicate(request, fieldNameService); - if (request.ParentId.HasValue) + if (request.ObjParentId != null) { var database = await GetMixDatabase(tableName); + var parentDb = await GetMixDatabase(request.ParentName); if (database is null) { return queries; @@ -371,10 +389,23 @@ private async Task> BuildSearchQueryAsync(string tableName, Sea } else { - var allowsIds = _cmsUow.DbContext.MixDatabaseAssociation - .Where(m => m.ParentDatabaseName == request.ParentName && m.ParentId == request.ParentId.Value && m.ChildDatabaseName == tableName) - .Select(m => m.ChildId).ToList(); - queries.Add(new(fieldNameService.Id, Operation.In, allowsIds)); + Expression> predicate = m => m.ParentDatabaseName == request.ParentName + && m.ChildDatabaseName == tableName; + predicate = predicate.AndAlsoIf(parentDb.Type == MixDatabaseType.GuidService, + m => m.GuidParentId == (Guid)request.ObjParentId); + predicate = predicate.AndAlsoIf(parentDb.Type != MixDatabaseType.GuidService, + m => m.ParentId == (int)request.ObjParentId); + + var childIdsQuery = _cmsUow.DbContext.MixDatabaseAssociation + .Where(predicate); + if (database.Type == MixDatabaseType.GuidService) + { + queries.Add(new(fieldNameService.Id, Operation.In, childIdsQuery.Select(m => m.GuidChildId).ToList())); + } + else + { + queries.Add(new(fieldNameService.Id, Operation.In, childIdsQuery.Select(m => m.ChildId).ToList())); + } } } @@ -469,7 +500,7 @@ private Operation ParseSearchOperation(MixCompareOperator? searchMethod) #endregion - private async Task SwitchDbContext(MixDatabaseContextReadViewModel dbContext) + private Task SwitchDbContext(MixDatabaseContextReadViewModel dbContext) { if (dbContext == null) { @@ -485,7 +516,7 @@ private async Task SwitchDbContext(MixDatabaseContextReadViewModel dbContext) _ => throw new NotImplementedException() }; _repository = new MixRepoDbRepository(_cache, dbContext.DatabaseProvider, dbContext.ConnectionString, _cmsUow); - + return Task.CompletedTask; } // Only run after init CMS success @@ -574,7 +605,7 @@ private async Task Migrate(RepoDbMixDatabaseViewModel database, colsSql.Add(GenerateColumnSql(col)); } - var commandText = GetMigrateTableSql(tableName, databaseProvider, colsSql, fieldNameService); + var commandText = GetMigrateTableSql(tableName, databaseProvider, database.Type, colsSql, fieldNameService); if (!string.IsNullOrEmpty(commandText)) { await repo.ExecuteCommand($"DROP TABLE IF EXISTS {_databaseConstant.BacktickOpen}{tableName}{_databaseConstant.BacktickClose};"); @@ -585,10 +616,10 @@ private async Task Migrate(RepoDbMixDatabaseViewModel database, return false; } - private string GetMigrateTableSql(string tableName, MixDatabaseProvider databaseProvider, List colsSql, FieldNameService fieldNameService) + private string GetMigrateTableSql(string tableName, MixDatabaseProvider databaseProvider, MixDatabaseType dbType, List colsSql, FieldNameService fieldNameService) { return $"CREATE TABLE {_databaseConstant.BacktickOpen}{tableName}{_databaseConstant.BacktickClose} " + - $"({_databaseConstant.BacktickOpen}{fieldNameService.Id}{_databaseConstant.BacktickClose} {GetAutoIncreaseIdSyntax(databaseProvider)}, " + + $"({_databaseConstant.BacktickOpen}{fieldNameService.Id}{_databaseConstant.BacktickClose} {GetIdSyntax(databaseProvider, dbType)}, " + $"{_databaseConstant.BacktickOpen}{fieldNameService.CreatedDateTime}{_databaseConstant.BacktickClose} {GetColumnType(MixDataType.DateTime)}, " + $"{_databaseConstant.BacktickOpen}{fieldNameService.LastModified}{_databaseConstant.BacktickClose} {GetColumnType(MixDataType.DateTime)} NULL, " + $"{_databaseConstant.BacktickOpen}{fieldNameService.TenantId}{_databaseConstant.BacktickClose} {GetColumnType(MixDataType.Integer)} NULL, " + @@ -600,8 +631,13 @@ private string GetMigrateTableSql(string tableName, MixDatabaseProvider database $" {string.Join(",", colsSql.ToArray())})"; } - private string GetAutoIncreaseIdSyntax(MixDatabaseProvider databaseProvider) + private string GetIdSyntax(MixDatabaseProvider databaseProvider, MixDatabaseType dbType) { + if (dbType == MixDatabaseType.GuidService) + { + return $"{_databaseConstant.BacktickOpen}{_databaseConstant.Guid}{_databaseConstant.BacktickClose} PRIMARY KEY"; + } + return databaseProvider switch { MixDatabaseProvider.SQLSERVER => $"{GetColumnType(MixDataType.Integer)} IDENTITY(1,1) PRIMARY KEY", diff --git a/src/platform/mix.repodb/Subscribers/MixRepoDbSubscriber.cs b/src/platform/mix.repodb/Subscribers/MixRepoDbSubscriber.cs index dc2034166..75ac2c409 100644 --- a/src/platform/mix.repodb/Subscribers/MixRepoDbSubscriber.cs +++ b/src/platform/mix.repodb/Subscribers/MixRepoDbSubscriber.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; using Mix.Constant.Constants; @@ -8,14 +7,12 @@ using Mix.Heart.UnitOfWork; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; -using Mix.Queue.Engines.MixQueue; using Mix.Queue.Interfaces; using Mix.RepoDb.Interfaces; using Mix.RepoDb.ViewModels; using Mix.SignalR.Enums; using Mix.SignalR.Interfaces; using Mix.SignalR.Models; -using System.Threading; namespace Mix.RepoDb.Subscribers { diff --git a/src/platform/mix.repodb/ViewModels/MixDatabaseContextReadViewModel.cs b/src/platform/mix.repodb/ViewModels/MixDatabaseContextReadViewModel.cs index 5b7b9cad8..51897d89f 100644 --- a/src/platform/mix.repodb/ViewModels/MixDatabaseContextReadViewModel.cs +++ b/src/platform/mix.repodb/ViewModels/MixDatabaseContextReadViewModel.cs @@ -1,10 +1,8 @@ -using Microsoft.EntityFrameworkCore; -using Mix.Constant.Enums; +using Mix.Constant.Enums; using Mix.Database.Entities.Cms; using Mix.Heart.Enums; using Mix.Heart.UnitOfWork; using Mix.RepoDb.Base; -using System.ComponentModel.DataAnnotations; namespace Mix.RepoDb.ViewModels { diff --git a/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs b/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs index 7b70b629a..49b498a87 100644 --- a/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs +++ b/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs @@ -1,6 +1,5 @@ using Mix.Constant.Enums; using Mix.Database.Entities.Cms; -using Mix.Heart.Extensions; using Mix.Heart.UnitOfWork; using Mix.Heart.ViewModel; using Mix.Shared.Helpers; @@ -66,53 +65,6 @@ public override async Task Validate(CancellationToken cancellationToken) await base.Validate(cancellationToken); } - protected override async Task SaveEntityRelationshipAsync(MixDatabaseRelationship parentEntity, CancellationToken cancellationToken = default) - { - string parentColIdName = $"{SourceDatabaseName.ToTitleCase()}Id"; - if (!Context.MixDatabaseColumn.Any(m => m.MixDatabaseName == DestinateDatabaseName && m.SystemName == parentColIdName)) - { - var destDb = Context.MixDatabase.FirstOrDefault(m => m.SystemName == DestinateDatabaseName); - - if (destDb is null) - { - return; - } - - var refCol = new RepoDbMixDatabaseColumnViewModel(UowInfo) - { - MixDatabaseName = DestinateDatabaseName, - MixDatabaseId = destDb.Id, - DataType = MixDataType.Reference, - CreatedBy = CreatedBy, - DisplayName = parentColIdName.ToTitleCase(), - SystemName = parentColIdName - }; - - await refCol.SaveAsync(cancellationToken); - ModifiedEntities.AddRange(refCol.ModifiedEntities); - } - } - - protected override async Task DeleteHandlerAsync(CancellationToken cancellationToken = default) - { - var leftDb = await Context.MixDatabase.FindAsync(new object?[] { ParentId }, cancellationToken: cancellationToken); - var rightDb = await Context.MixDatabase.FindAsync(new object?[] { ChildId }, cancellationToken: cancellationToken); - if (leftDb is null || rightDb is null) - { - return; - } - - string leftColName = $"{leftDb.SystemName}Id"; - string rightColName = $"{rightDb.SystemName}Id"; - await RepoDbMixDatabaseColumnViewModel.GetRepository(UowInfo, CacheService) - .DeleteManyAsync(m => - (m.MixDatabaseId == ParentId && m.SystemName == rightColName) - || (m.MixDatabaseId == ChildId && m.SystemName == leftColName), - cancellationToken); - - await base.DeleteHandlerAsync(cancellationToken); - } - #endregion } } diff --git a/src/platform/mix.repodb/ViewModels/RepoDbMixDatabaseColumnViewModel.cs b/src/platform/mix.repodb/ViewModels/RepoDbMixDatabaseColumnViewModel.cs index d572e159c..1e9320f29 100644 --- a/src/platform/mix.repodb/ViewModels/RepoDbMixDatabaseColumnViewModel.cs +++ b/src/platform/mix.repodb/ViewModels/RepoDbMixDatabaseColumnViewModel.cs @@ -5,7 +5,6 @@ using Mix.Heart.ViewModel; using Mix.RepoDb.Dtos; using Mix.Shared.Models; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Mix.RepoDb.ViewModels @@ -29,7 +28,7 @@ public class RepoDbMixDatabaseColumnViewModel #region Constructors - public RepoDbMixDatabaseColumnViewModel(AlterColumnDto dto ) + public RepoDbMixDatabaseColumnViewModel(AlterColumnDto dto) { ReflectionHelper.Map(dto, this); } diff --git a/src/platform/mix.repodb/mix.repodb.csproj b/src/platform/mix.repodb/mix.repodb.csproj index 28c306918..b1c12f55b 100644 --- a/src/platform/mix.repodb/mix.repodb.csproj +++ b/src/platform/mix.repodb/mix.repodb.csproj @@ -18,6 +18,7 @@ + diff --git a/src/platform/mix.service/Commands/MixDbEventCommand.cs b/src/platform/mix.service/Commands/MixDbEventCommand.cs index 3350f8dd1..6c088ea47 100644 --- a/src/platform/mix.service/Commands/MixDbEventCommand.cs +++ b/src/platform/mix.service/Commands/MixDbEventCommand.cs @@ -1,7 +1,4 @@ -using Mix.Heart.Helpers; -using Mix.Service.Models; -using Mix.Shared.Models; -using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Linq; namespace Mix.Service.Commands { diff --git a/src/platform/mix.service/Models/MixDbCommandModel.cs b/src/platform/mix.service/Models/MixDbCommandModel.cs index 2dfa051ea..a92a094f9 100644 --- a/src/platform/mix.service/Models/MixDbCommandModel.cs +++ b/src/platform/mix.service/Models/MixDbCommandModel.cs @@ -1,13 +1,4 @@ -using Microsoft.AspNetCore.Http; -using Mix.Service.Services; -using Mix.Shared.Models; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Nodes; -using System.Threading.Tasks; +using Newtonsoft.Json.Linq; namespace Mix.Service.Models { diff --git a/src/platform/mix.service/Services/BaseHubClientService.cs b/src/platform/mix.service/Services/BaseHubClientService.cs index b4d7505b5..88a7cdaa6 100644 --- a/src/platform/mix.service/Services/BaseHubClientService.cs +++ b/src/platform/mix.service/Services/BaseHubClientService.cs @@ -1,20 +1,11 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.SignalR.Client; -using Mix.Constant.Constants; -using Mix.Service.Models; -using Mix.Shared.Services; +using Microsoft.AspNetCore.SignalR.Client; +using Microsoft.Extensions.Logging; +using Mix.Heart.Extensions; +using Mix.Heart.Helpers; using Mix.SignalR.Constants; using Mix.SignalR.Enums; -using Mix.SignalR.Models; -using System; -using System.Threading.Tasks; -using Mix.Shared.Extensions; -using System.Drawing.Printing; -using Microsoft.Extensions.Hosting; using Mix.SignalR.Interfaces; -using Mix.Heart.Helpers; -using Mix.Heart.Extensions; -using Microsoft.Extensions.Logging; +using Mix.SignalR.Models; namespace Mix.Service.Services { @@ -41,7 +32,7 @@ public Task SendMessageAsync(string title, string description, object data, Mess }; return SendMessageAsync(msg); } - + public Task SendGroupMessageAsync(string groupName, string title, string description, object data, MessageType messageType = MessageType.Info, bool exceptCaller = true) { var msg = new SignalRMessageModel(data) diff --git a/src/platform/mix.service/Services/FieldNameService.cs b/src/platform/mix.service/Services/FieldNameService.cs index f683a17ef..44bdb1c71 100644 --- a/src/platform/mix.service/Services/FieldNameService.cs +++ b/src/platform/mix.service/Services/FieldNameService.cs @@ -1,11 +1,4 @@ -using Microsoft.Azure.Amqp; -using Mix.Constant.Enums; -using Mix.Heart.Helpers; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Mix.Constant.Enums; namespace Mix.Service.Services { diff --git a/src/platform/mix.service/Services/LogStreamHubClientService.cs b/src/platform/mix.service/Services/LogStreamHubClientService.cs index 56503e4a8..aef1c8692 100644 --- a/src/platform/mix.service/Services/LogStreamHubClientService.cs +++ b/src/platform/mix.service/Services/LogStreamHubClientService.cs @@ -1,10 +1,8 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging; using Mix.Shared.Services; using Mix.SignalR.Constants; using Mix.SignalR.Interfaces; using Mix.SignalR.Models; -using System; namespace Mix.Service.Services { diff --git a/src/platform/mix.service/Services/MixDbCommandHubClientService.cs b/src/platform/mix.service/Services/MixDbCommandHubClientService.cs index 580f7f3e0..c8e9880c1 100644 --- a/src/platform/mix.service/Services/MixDbCommandHubClientService.cs +++ b/src/platform/mix.service/Services/MixDbCommandHubClientService.cs @@ -1,17 +1,15 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging; using Mix.Shared.Services; using Mix.SignalR.Constants; using Mix.SignalR.Interfaces; using Mix.SignalR.Models; -using System; namespace Mix.Service.Services { public class MixDbCommandHubClientService : BaseHubClientService, IMixDbCommandHubClientService { public MixDbCommandHubClientService(MixEndpointService mixEndpointService, ILogger logger) - : base(HubEndpoints.MixDbCommandHub, mixEndpointService.MixMq, logger) + : base(HubEndpoints.MixDbHub, mixEndpointService.MixMq, logger) { } diff --git a/src/platform/mix.service/Services/MixLogService.cs b/src/platform/mix.service/Services/MixLogService.cs index 5d412ccc8..4fe046189 100644 --- a/src/platform/mix.service/Services/MixLogService.cs +++ b/src/platform/mix.service/Services/MixLogService.cs @@ -1,12 +1,4 @@ -using Microsoft.AspNetCore.Http; -using Mix.Heart.Enums; -using Mix.Heart.Helpers; -using Mix.Shared.Services; -using Mix.SignalR.Enums; -using Mix.SignalR.Interfaces; -using Mix.SignalR.Models; -using Newtonsoft.Json.Linq; -using Quartz; +using Mix.Heart.Enums; namespace Mix.Service.Services { diff --git a/src/platform/mix.service/Services/MixPermissionService.cs b/src/platform/mix.service/Services/MixPermissionService.cs index 4e4bf8ea0..44f942ba2 100644 --- a/src/platform/mix.service/Services/MixPermissionService.cs +++ b/src/platform/mix.service/Services/MixPermissionService.cs @@ -5,10 +5,8 @@ using Mix.Database.Entities.Account; using Mix.Database.Entities.Cms; using Mix.Database.Entities.MixDb; -using Mix.Database.Services; using Mix.Heart.Exceptions; using Mix.Heart.UnitOfWork; -using Mix.Shared.Extensions; using Mix.Shared.Services; using System.Linq.Dynamic.Core; using System.Text.RegularExpressions; @@ -99,7 +97,7 @@ private T GetRequiredService() public async Task CheckEndpointPermissionAsync(string[] userRoles, PathString path, string method) { - if(RoleEndpoints == null) + if (RoleEndpoints == null) { await Reload(); } diff --git a/src/platform/mix.service/Services/PortalHubClientService.cs b/src/platform/mix.service/Services/PortalHubClientService.cs index cfaf8d54f..a44299359 100644 --- a/src/platform/mix.service/Services/PortalHubClientService.cs +++ b/src/platform/mix.service/Services/PortalHubClientService.cs @@ -1,13 +1,7 @@ -using MessagePack; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Microsoft.Identity.Web; using Mix.Constant.Constants; using Mix.Database.Entities.Cms; -using Mix.Heart.Enums; -using Mix.Heart.Extensions; -using Mix.Heart.Helpers; using Mix.Heart.Model; using Mix.Heart.Services; using Mix.Lib.Interfaces; @@ -17,7 +11,6 @@ using Mix.SignalR.Interfaces; using Mix.SignalR.Models; using Newtonsoft.Json.Linq; -using System; namespace Mix.Service.Services { diff --git a/src/platform/mix.service/Services/TenantServiceBase.cs b/src/platform/mix.service/Services/TenantServiceBase.cs index 4fdc22ee9..504e0a734 100644 --- a/src/platform/mix.service/Services/TenantServiceBase.cs +++ b/src/platform/mix.service/Services/TenantServiceBase.cs @@ -47,12 +47,12 @@ protected MixTenantSystemModel CurrentTenant return _currentTenant; } } - + public void SetTenant(MixTenantSystemModel tenant) { _currentTenant = tenant; } - + public void SetTenantId(int tenantId) { _currentTenant = new() diff --git a/src/platform/mix.shared/Dtos/FilterContentRequestDto.cs b/src/platform/mix.shared/Dtos/FilterContentRequestDto.cs index fc31125d4..148753aa1 100644 --- a/src/platform/mix.shared/Dtos/FilterContentRequestDto.cs +++ b/src/platform/mix.shared/Dtos/FilterContentRequestDto.cs @@ -1,6 +1,4 @@ -using Microsoft.AspNetCore.Http; - -namespace Mix.Shared.Dtos +namespace Mix.Shared.Dtos { public class FilterContentRequestDto : SearchRequestDto { diff --git a/src/platform/mix.shared/Dtos/SearchMixDbRequestDto.cs b/src/platform/mix.shared/Dtos/SearchMixDbRequestDto.cs index 8d7601fdb..87a74ddad 100644 --- a/src/platform/mix.shared/Dtos/SearchMixDbRequestDto.cs +++ b/src/platform/mix.shared/Dtos/SearchMixDbRequestDto.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Http; +using Mix.Heart.Enums; namespace Mix.Shared.Dtos { @@ -19,22 +20,35 @@ public SearchMixDbRequestDto(SearchRequestDto req, HttpRequest request) OrderBy = req.OrderBy; Direction = req.Direction; Status = req.Status; + } - if (int.TryParse(request.Query[MixRequestQueryKeywords.ParentId], out int parentId)) + public List Queries { get; set; } = new(); + public string? ParentId { get; set; } + public object? ObjParentId => GetParentId(); + public MixDatabaseRelationshipType? Relationship { get; set; } = MixDatabaseRelationshipType.OneToMany; + public string ParentName { get; set; } = default; + + private object? GetParentId() + { + try { - ParentId = parentId; + if (Guid.TryParse(ParentId, out var guidId)) + { + return guidId; + } + else + { + if (int.TryParse(ParentId, out var intId)) + { + return intId; + } + } + return null; } - - if (Guid.TryParse(request.Query[MixRequestQueryKeywords.ParentId], out Guid guidParentId)) + catch (Exception ex) { - GuidParentId = guidParentId; + throw new MixException(MixErrorStatus.Badrequest, ex); } } - - public List Queries { get; set; } = new(); - public int? ParentId { get; set; } - public MixDatabaseRelationshipType? RelationShip { get; set; } = MixDatabaseRelationshipType.OneToMany; - public Guid? GuidParentId { get; set; } - public string ParentName { get; set; } = default; } } diff --git a/src/platform/mix.shared/Enums/ApplicationType.cs b/src/platform/mix.shared/Enums/ApplicationType.cs index b0ab4bc59..3ecf57338 100644 --- a/src/platform/mix.shared/Enums/ApplicationType.cs +++ b/src/platform/mix.shared/Enums/ApplicationType.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Shared.Enums +namespace Mix.Shared.Enums { public enum ApplicationType { diff --git a/src/platform/mix.shared/Models/Configurations/MixRateLimitConfigurations.cs b/src/platform/mix.shared/Models/Configurations/MixRateLimitConfigurations.cs index 5456a5995..52a8df9a3 100644 --- a/src/platform/mix.shared/Models/Configurations/MixRateLimitConfigurations.cs +++ b/src/platform/mix.shared/Models/Configurations/MixRateLimitConfigurations.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Shared.Models.Configurations +namespace Mix.Shared.Models.Configurations { public class MixRateLimitConfigurations { diff --git a/src/platform/mix.shared/Models/Configurations/OcelotConfigurations.cs b/src/platform/mix.shared/Models/Configurations/OcelotConfigurations.cs index 16dc73bcd..eca21ec87 100644 --- a/src/platform/mix.shared/Models/Configurations/OcelotConfigurations.cs +++ b/src/platform/mix.shared/Models/Configurations/OcelotConfigurations.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Shared.Models.Configurations +namespace Mix.Shared.Models.Configurations { public class OcelotConfigurations { diff --git a/src/platform/mix.shared/Models/ConnectionStrings.cs b/src/platform/mix.shared/Models/ConnectionStrings.cs index 0479b1d84..1c4a67fe3 100644 --- a/src/platform/mix.shared/Models/ConnectionStrings.cs +++ b/src/platform/mix.shared/Models/ConnectionStrings.cs @@ -3,6 +3,8 @@ public class ConnectionStrings { public string MixAccountConnection { get; set; } + public string MixAuditLogConnection { get; set; } + public string MixQueueLogConnection { get; set; } public string MixCmsConnection { get; set; } public string MixQuartzConnection { get; set; } public string MixDbConnection { get; set; } diff --git a/src/platform/mix.shared/Models/DataRelationshipModel.cs b/src/platform/mix.shared/Models/DataRelationshipModel.cs index 57b0b186c..ba256dc40 100644 --- a/src/platform/mix.shared/Models/DataRelationshipModel.cs +++ b/src/platform/mix.shared/Models/DataRelationshipModel.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Shared.Models +namespace Mix.Shared.Models { public class DataRelationshipModel { diff --git a/src/platform/mix.shared/Services/HttpService.cs b/src/platform/mix.shared/Services/HttpService.cs index da261ef3b..678da5f76 100644 --- a/src/platform/mix.shared/Services/HttpService.cs +++ b/src/platform/mix.shared/Services/HttpService.cs @@ -5,7 +5,6 @@ using Newtonsoft.Json.Linq; using System.Net; using System.Net.Http.Headers; -using System.Net.Http.Json; using System.Reflection; using System.Text; using System.Text.Json; @@ -182,8 +181,8 @@ private HttpContent CreateHttpContent(T content, string contentType) } case "application/x-www-form-urlencoded": var formData = content.GetType() - .GetProperties(BindingFlags.Instance | BindingFlags.Public) - .ToDictionary(prop => prop.Name, prop => (string)prop.GetValue(content, null)); + .GetProperties(BindingFlags.Instance | BindingFlags.Public) + .ToDictionary(prop => prop.Name, prop => (string)prop.GetValue(content, null)); return new FormUrlEncodedContent(formData); default: return new StringContent( diff --git a/src/platform/mix.signalr.hub/Attributes/MixDbHubAuthorizeAttribute.cs b/src/platform/mix.signalr.hub/Attributes/MixDbHubAuthorizeAttribute.cs new file mode 100644 index 000000000..f466da97e --- /dev/null +++ b/src/platform/mix.signalr.hub/Attributes/MixDbHubAuthorizeAttribute.cs @@ -0,0 +1,150 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Mix.Auth.Constants; +using Mix.Database.Entities.Cms; +using Mix.Service.Services; +using System.Security.Claims; + +namespace Mix.Signalr.Hub.Attributes +{ + public sealed class MixDbHubAuthorizeAttribute : TypeFilterAttribute + { + public MixDbHubAuthorizeAttribute(string tableName) + : base(typeof(DatabaseAuthorizeActionFilter)) + { + Arguments = [tableName]; + } + public class DatabaseAuthorizeActionFilter : IAuthorizationFilter + { + private string _tableName; + public string[] UserRoles { get; set; } + private readonly MixCmsContext _cmsContext; + protected readonly MixPermissionService _permissionService; + private ClaimsPrincipal userPrinciple; + public DatabaseAuthorizeActionFilter( + string tableName, + MixCmsContext cmsContext, + MixPermissionService permissionService) + { + _tableName = tableName; + _cmsContext = cmsContext; + _permissionService = permissionService; + } + + public void OnAuthorization(AuthorizationFilterContext context) + { + userPrinciple = context.HttpContext.User; + if (string.IsNullOrEmpty(_tableName)) + { + _tableName = context.HttpContext.Request.RouteValues["name"]?.ToString(); + } + var database = _cmsContext.MixDatabase.FirstOrDefault(m => m.SystemName == _tableName); + if (database == null) + { + context.Result = new BadRequestResult(); + return; + } + + // Not allow bypass by default for security => if not set, only superadmin can access this database + if (!CheckByPassAuthenticate(context.HttpContext.Request.Method, context.HttpContext.Request.Path, database)) + { + if (ValidToken()) + { + if (!IsInRoles(context.HttpContext.Request.Method, database, context.HttpContext.Request.Path)) + { + if (!ValidEnpointPermission(context)) + { + context.Result = new ForbidResult(); + return; + } + } + } + else + { + context.Result = new UnauthorizedResult(); + return; + } + } + } + + private bool CheckByPassAuthenticate(string method, string path, MixDatabase database) + { + return method switch + { + "GET" => database.ReadPermissions == null + || database.ReadPermissions.Count == 0, + "POST" => (path.EndsWith("filter") && (database.ReadPermissions == null || database.ReadPermissions.Count == 0)) + || (!path.EndsWith("filter") && (database.CreatePermissions == null || database.CreatePermissions.Count == 0)), + "PUT" => database.UpdatePermissions == null + || database.UpdatePermissions.Count == 0, + "PATCH" => database.UpdatePermissions == null + || database.UpdatePermissions.Count == 0, + "DELETE" => database.DeletePermissions == null + || database.DeletePermissions.Count == 0, + _ => false + }; + } + + #region Privates + + private bool ValidEnpointPermission(AuthorizationFilterContext context) + { + return _permissionService.CheckEndpointPermissionAsync( + UserRoles, context.HttpContext.Request.Path, context.HttpContext.Request.Method).Result; + } + + private bool ValidToken() + { + return userPrinciple.Identity.IsAuthenticated + && DateTime.TryParse(GetClaim(userPrinciple, MixClaims.ExpireAt), out var expireAt) + && DateTime.UtcNow < expireAt; + } + + private bool IsInRoles(string method, MixDatabase database, string path) + { + + UserRoles = GetClaim(userPrinciple, MixClaims.Role).Split(',', StringSplitOptions.RemoveEmptyEntries) + .Select(r => r.Trim()).ToArray(); + + if (UserRoles.Any(r => r == MixRoles.SuperAdmin || r == $"{MixRoles.Owner}-1")) + { + return true; + } + + switch (method) + { + case "GET": return CheckUserInRoles(database.ReadPermissions, UserRoles); + case "POST": + if (path.EndsWith("filter")) + { + return CheckUserInRoles(database.ReadPermissions, UserRoles); + } + else + { + return CheckUserInRoles(database.CreatePermissions, UserRoles); + } + case "PATCH": + case "PUT": return CheckUserInRoles(database.UpdatePermissions, UserRoles); + case "DELETE": return CheckUserInRoles(database.DeletePermissions, UserRoles); + default: + return false; + } + } + + private bool CheckUserInRoles(List allowedRoles, string[] userRoles) + { + return allowedRoles == null || allowedRoles.Count == 0 || allowedRoles.Any(r => userRoles.Any(ur => ur == $"{r}-1")); + } + + public string GetClaim(ClaimsPrincipal User, string claimType) + { + if (User == null) + { + return null; + } + return string.Join(',', User.Claims.Where(c => c.Type == claimType).Select(m => m.Value)); + } + #endregion + } + } +} diff --git a/src/platform/mix.signalr.hub/Extensions/ServiceCollectionExtensions.cs b/src/platform/mix.signalr.hub/Extensions/ServiceCollectionExtensions.cs index 00337fef5..4f14cde65 100644 --- a/src/platform/mix.signalr.hub/Extensions/ServiceCollectionExtensions.cs +++ b/src/platform/mix.signalr.hub/Extensions/ServiceCollectionExtensions.cs @@ -10,7 +10,7 @@ public static class ServiceCollectionExtensions public static IEndpointRouteBuilder UseMixSignalRApp(this IEndpointRouteBuilder endpoints) { endpoints.MapHub(HubEndpoints.PortalHub); - endpoints.MapHub(HubEndpoints.MixDbCommandHub); + endpoints.MapHub(HubEndpoints.MixDbHub); endpoints.MapHub(HubEndpoints.LogStreamHub); endpoints.MapHub(HubEndpoints.EditFileHub); endpoints.MapHub(HubEndpoints.MixThemeHub); diff --git a/src/platform/mix.signalr.hub/Hubs/BaseSignalrHub.cs b/src/platform/mix.signalr.hub/Hubs/BaseSignalrHub.cs index 880b53002..c562f3135 100644 --- a/src/platform/mix.signalr.hub/Hubs/BaseSignalrHub.cs +++ b/src/platform/mix.signalr.hub/Hubs/BaseSignalrHub.cs @@ -1,17 +1,13 @@ -using Google.Api; -using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.SignalR; using Mix.Auth.Constants; using Mix.Constant.Constants; using Mix.Heart.Enums; using Mix.Heart.Exceptions; -using Mix.Heart.Helpers; using Mix.Lib.Interfaces; -using Mix.Signalr.Hub.Models; using Mix.SignalR.Constants; using Mix.SignalR.Enums; using Mix.SignalR.Models; -using System.Security.Claims; namespace Mix.SignalR.Hubs { @@ -109,7 +105,7 @@ public virtual Task SendGroupMessage(SignalRMessageModel message, string groupNa } catch (Exception ex) { - throw new MixException(Heart.Enums.MixErrorStatus.ServerError, ex); + throw new MixException(MixErrorStatus.ServerError, ex); } } @@ -138,15 +134,16 @@ protected async Task AddUserToRoom(string roomName) } } - protected HubUserModel GetCurrentUser() { + var userContext = Context.User; return new() { TenantId = TenantId, ConnectionId = Context.ConnectionId, - Username = Context.User?.Identity?.Name ?? "Annonymous", - Avatar = Context.User?.Claims.FirstOrDefault(m => m.Type == MixClaims.Avatar)?.Value ?? MixConstants.CONST_DEFAULT_EXTENSIONS_FILE_PATH, + Username = userContext?.Identity?.Name ?? "Anonymous", + Avatar = userContext?.Claims.FirstOrDefault(m => m.Type == MixClaims.Avatar)?.Value ?? MixConstants.CONST_DEFAULT_EXTENSIONS_FILE_PATH, + Role = userContext?.Claims.FirstOrDefault(m => m.Type == MixClaims.Role)?.Value, }; } #endregion diff --git a/src/platform/mix.signalr.hub/Hubs/EditFileHub.cs b/src/platform/mix.signalr.hub/Hubs/EditFileHub.cs index 41241725d..028f4e112 100644 --- a/src/platform/mix.signalr.hub/Hubs/EditFileHub.cs +++ b/src/platform/mix.signalr.hub/Hubs/EditFileHub.cs @@ -4,7 +4,7 @@ namespace Mix.SignalR.Hubs { public class EditFileHub : BaseSignalRHub { - public EditFileHub(IAuditLogService auditLogService, IMixTenantService mixTenantService) + public EditFileHub(IAuditLogService auditLogService, IMixTenantService mixTenantService) : base(auditLogService, mixTenantService) { } diff --git a/src/platform/mix.signalr.hub/Hubs/LogStreamHub.cs b/src/platform/mix.signalr.hub/Hubs/LogStreamHub.cs index 797ecc784..4bb92bd3a 100644 --- a/src/platform/mix.signalr.hub/Hubs/LogStreamHub.cs +++ b/src/platform/mix.signalr.hub/Hubs/LogStreamHub.cs @@ -1,5 +1,4 @@ using Mix.Lib.Interfaces; -using Mix.Service.Interfaces; namespace Mix.SignalR.Hubs { diff --git a/src/platform/mix.signalr.hub/Hubs/MixDbCommandHub.cs b/src/platform/mix.signalr.hub/Hubs/MixDbCommandHub.cs index 8cdf1302e..700605021 100644 --- a/src/platform/mix.signalr.hub/Hubs/MixDbCommandHub.cs +++ b/src/platform/mix.signalr.hub/Hubs/MixDbCommandHub.cs @@ -1,15 +1,9 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.SignalR; -using Mix.Constant.Constants; +using Mix.Constant.Constants; using Mix.Heart.Helpers; using Mix.Lib.Interfaces; using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; -using Mix.Service.Interfaces; using Mix.Service.Models; -using Mix.Signalr.Hub.Models; -using Mix.SignalR.Constants; -using Mix.SignalR.Models; namespace Mix.SignalR.Hubs { @@ -29,7 +23,7 @@ public virtual void CreateData(string message) obj.ConnectionId = Context.ConnectionId; _queueService.PushMemoryQueue(obj.MixTenantId, MixQueueTopics.MixDbCommand, MixDbCommandQueueActions.Create, obj); } - + public virtual void UpdateData(string message) { var obj = ReflectionHelper.ParseStringToObject(message); diff --git a/src/platform/mix.signalr.hub/Hubs/MixDbHub.cs b/src/platform/mix.signalr.hub/Hubs/MixDbHub.cs new file mode 100644 index 000000000..498ef2358 --- /dev/null +++ b/src/platform/mix.signalr.hub/Hubs/MixDbHub.cs @@ -0,0 +1,213 @@ +using Microsoft.AspNetCore.Authorization; +using Mix.Auth.Constants; +using Mix.Constant.Constants; +using Mix.Constant.Enums; +using Mix.Database.Entities.Cms; +using Mix.Lib.Interfaces; +using Mix.Mq.Lib.Models; +using Mix.Queue.Interfaces; +using Mix.Service.Interfaces; +using Mix.Service.Models; +using Mix.SignalR.Enums; +using Mix.SignalR.Models; +using Newtonsoft.Json.Linq; +using System.Security.Claims; + +namespace Mix.SignalR.Hubs +{ + [Authorize] + public class MixDbHub : BaseSignalRHub + { + private readonly IMixMemoryCacheService _memoryCache; + private readonly MixCmsContext _ctx; + private readonly IMemoryQueueService _queueService; + public MixDbHub(IAuditLogService auditLogService, IMixTenantService mixTenantService, IMemoryQueueService queueService, IMixMemoryCacheService memoryCache, MixCmsContext ctx) : base(auditLogService, mixTenantService) + { + _queueService = queueService; + _memoryCache = memoryCache; + _ctx = ctx; + } + + #region Methods + + public async void JoinRooms(string[] roomNames) + { + foreach (var tableName in roomNames) + { + if (await CheckUserPermission(tableName, "GET")) + { + await AddUserToRoom($"mixdb-{tableName}"); + } + } + } + + public virtual async Task CreateDataAsync(string tableName, JObject data) + { + + if (await CheckUserPermission(tableName, "POST")) + { + var obj = new MixDbCommandModel() + { + MixDbName = tableName, + Body = data, + ConnectionId = Context.ConnectionId, + MixTenantId = 1, + RequestedBy = GetCurrentUser().Username + }; + _queueService.PushMemoryQueue(obj.MixTenantId, MixQueueTopics.MixDbCommand, MixDbCommandQueueAction.Create.ToString(), obj); + } + } + + public virtual async Task DeleteDataAsync(string tableName, JObject data) + { + + if (await CheckUserPermission(tableName, "DELETE")) + { + var obj = new MixDbCommandModel() + { + MixDbName = tableName, + Body = data, + ConnectionId = Context.ConnectionId, + MixTenantId = 1, + RequestedBy = GetCurrentUser().Username + }; + _queueService.PushMemoryQueue(obj.MixTenantId, MixQueueTopics.MixDbCommand, MixDbCommandQueueAction.Delete.ToString(), obj); + } + } + + public virtual async Task UpdateData(string tableName, JObject data) + { + if (await CheckUserPermission(tableName, "PUT")) + { + var obj = new MixDbCommandModel() + { + MixDbName = tableName, + Body = data, + ConnectionId = Context.ConnectionId, + MixTenantId = 1, + RequestedBy = GetCurrentUser().Username + }; + _queueService.PushMemoryQueue(obj.MixTenantId, MixQueueTopics.MixDbCommand, MixDbCommandQueueAction.Update.ToString(), obj); + } + } + #endregion + #region Private + + private async Task CheckUserPermission(string tableName, string action) + { + try + { + var tbl = await GetMixDatabase(tableName); + if (tbl == null) + { + await SendErrorMessageToCaller($"Invalid table name {tableName}"); + return false; + } + + if (CheckByPassAuthenticate(action, tbl)) + { + return true; + } + + if (Context.User == null) + { + await SendErrorMessageToCaller($"Unauthorized"); + return false; + } + + if (!IsInRoles(action, tbl)) + { + await SendErrorMessageToCaller($"You don't have permission to access {tableName}"); + return false; + } + + return true; + } + catch (Exception ex) + { + await SendErrorMessageToCaller(ex.Message); + return false; + } + + } + + private bool IsInRoles(string method, MixDatabase database) + { + + var userRoles = GetClaim(Context.User!, MixClaims.Role).Split(',', StringSplitOptions.RemoveEmptyEntries) + .Select(r => r.Trim()).ToArray(); + + if (userRoles.Any(r => r == MixRoles.SuperAdmin || r == $"{MixRoles.Owner}-1")) + { + return true; + } + + switch (method) + { + case "GET": return CheckUserInRoles(database.ReadPermissions, userRoles); + case "POST": + return CheckUserInRoles(database.CreatePermissions, userRoles); + case "PATCH": + case "PUT": return CheckUserInRoles(database.UpdatePermissions, userRoles); + case "DELETE": return CheckUserInRoles(database.DeletePermissions, userRoles); + default: + return false; + } + } + + private bool CheckUserInRoles(List allowedRoles, string[] userRoles) + { + return allowedRoles == null || allowedRoles.Count == 0 || allowedRoles.Any(r => userRoles.Any(ur => ur == $"{r}-1")); + } + + private string GetClaim(ClaimsPrincipal User, string claimType) + { + if (User == null) + { + return null; + } + return string.Join(',', User.Claims.Where(c => c.Type == claimType).Select(m => m.Value)); + } + + private bool CheckByPassAuthenticate(string method, MixDatabase database) + { + return method switch + { + "GET" => database.ReadPermissions == null + || database.ReadPermissions.Count == 0, + "POST" => database.CreatePermissions == null + || database.CreatePermissions.Count == 0, + "PUT" => database.UpdatePermissions == null + || database.UpdatePermissions.Count == 0, + "PATCH" => database.UpdatePermissions == null + || database.UpdatePermissions.Count == 0, + "DELETE" => database.DeletePermissions == null + || database.DeletePermissions.Count == 0, + _ => false + }; + } + + private async Task SendErrorMessageToCaller(string errMsg) + { + await SendMessageToCaller(new SignalRMessageModel() + { + Type = MessageType.Error, + Message = errMsg, + }); + } + + private async Task GetMixDatabase(string tableName) + { + return await _memoryCache.TryGetValueAsync( + tableName, + cache => + { + cache.SlidingExpiration = TimeSpan.FromSeconds(20); + var db = _ctx.MixDatabase.SingleOrDefault(m => m.SystemName == tableName); + return Task.FromResult(db); + } + ); + } + #endregion + } +} \ No newline at end of file diff --git a/src/platform/mix.signalr.hub/Hubs/MixThemeHub.cs b/src/platform/mix.signalr.hub/Hubs/MixThemeHub.cs index d9da6d739..b4789f335 100644 --- a/src/platform/mix.signalr.hub/Hubs/MixThemeHub.cs +++ b/src/platform/mix.signalr.hub/Hubs/MixThemeHub.cs @@ -1,5 +1,4 @@ using Mix.Lib.Interfaces; -using Mix.Service.Interfaces; namespace Mix.SignalR.Hubs { diff --git a/src/platform/mix.signalr.hub/Hubs/PortalHub.cs b/src/platform/mix.signalr.hub/Hubs/PortalHub.cs index f5fee1d4c..6cc07d2a1 100644 --- a/src/platform/mix.signalr.hub/Hubs/PortalHub.cs +++ b/src/platform/mix.signalr.hub/Hubs/PortalHub.cs @@ -1,5 +1,4 @@ using Mix.Lib.Interfaces; -using Mix.Service.Interfaces; namespace Mix.SignalR.Hubs { diff --git a/src/platform/mix.signalr.hub/Hubs/VideoCallHub.cs b/src/platform/mix.signalr.hub/Hubs/VideoCallHub.cs index 75377379e..3497b1b69 100644 --- a/src/platform/mix.signalr.hub/Hubs/VideoCallHub.cs +++ b/src/platform/mix.signalr.hub/Hubs/VideoCallHub.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.SignalR; using Mix.Lib.Interfaces; -using Mix.Service.Interfaces; using Mix.Signalr.Hub.Models; using Mix.SignalR.Hubs; using Newtonsoft.Json.Linq; diff --git a/src/platform/mix.signalr/Constants/HubEndpoints.cs b/src/platform/mix.signalr/Constants/HubEndpoints.cs index a71b5ba38..33565d3cf 100644 --- a/src/platform/mix.signalr/Constants/HubEndpoints.cs +++ b/src/platform/mix.signalr/Constants/HubEndpoints.cs @@ -4,7 +4,7 @@ public class HubEndpoints { public const string MixThemeHub = "/hub/mixThemeHub"; public const string PortalHub = "/hub/portalhub"; - public const string MixDbCommandHub = "/hub/mixDbCommandHub"; + public const string MixDbHub = "/hub/mixDbHub"; public const string LogStreamHub = "/hub/log-stream-hub"; public const string EditFileHub = "/hub/editFileHub"; public const string HighFrequencyHub = "/hub/highFrequencyHub"; diff --git a/src/platform/mix.signalr/Models/HubUserModel.cs b/src/platform/mix.signalr/Models/HubUserModel.cs index 20c909d3a..1f1bb239e 100644 --- a/src/platform/mix.signalr/Models/HubUserModel.cs +++ b/src/platform/mix.signalr/Models/HubUserModel.cs @@ -6,11 +6,13 @@ public class HubUserModel public string ConnectionId { get; set; } public string Username { get; set; } public string Avatar { get; set; } + public string Role { get; set; } public HubUserModel() { } + public HubUserModel(string fromName) { Username = fromName; diff --git a/src/platform/mix.signalr/Models/SignalRMessageModel.cs b/src/platform/mix.signalr/Models/SignalRMessageModel.cs index 541779086..740b04fe8 100644 --- a/src/platform/mix.signalr/Models/SignalRMessageModel.cs +++ b/src/platform/mix.signalr/Models/SignalRMessageModel.cs @@ -1,9 +1,6 @@ using Mix.Heart.Helpers; using Mix.SignalR.Enums; -using Newtonsoft.Json.Linq; using System; -using System.Collections; -using System.Reflection.Metadata; namespace Mix.SignalR.Models { diff --git a/src/platform/mix.signalr/ServiceCollectionExtensions.cs b/src/platform/mix.signalr/ServiceCollectionExtensions.cs index 5f04b206d..26e400043 100644 --- a/src/platform/mix.signalr/ServiceCollectionExtensions.cs +++ b/src/platform/mix.signalr/ServiceCollectionExtensions.cs @@ -2,9 +2,12 @@ using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Mix.SignalR; +using System; using System.Text.Json.Serialization; +using System.Threading.Tasks; namespace Microsoft.Extensions.DependencyInjection { @@ -13,13 +16,20 @@ public static class ServiceCollectionExtensions public static IServiceCollection AddMixSignalR(this IServiceCollection services, IConfiguration configuration) { string azureConnectionString = configuration.GetSection("Azure")["SignalRConnectionString"]; - services.AddSignalR() - .AddJsonProtocol(options => - { - options.PayloadSerializerOptions.Converters - .Add(new JsonStringEnumConverter()); - }) - .AddAzureSignalRIf(azureConnectionString); + + services + .AddSingleton() + .AddSignalR(options => + { + options.EnableDetailedErrors = true; + options.AddFilter(); + }) + .AddJsonProtocol(options => + { + options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + }) + .AddAzureSignalRIf(azureConnectionString); + services.TryAddEnumerable( ServiceDescriptor.Singleton, ConfigureJwtBearerOptions>()); @@ -35,4 +45,51 @@ private static void AddAzureSignalRIf(this ISignalRServerBuilder builder, string } } } + + public class HubFilter(ILogger logger) : IHubFilter + { + private readonly ILogger _logger = logger; + + public async ValueTask InvokeMethodAsync(HubInvocationContext invocationContext, Func> next) + { + _logger.LogInformation("Calling hub method {HubMethodName}", invocationContext.HubMethodName); + try + { + return await next(invocationContext); + } + catch (Exception ex) + { + _logger.LogError(ex, "Exception Calling hub method {HubMethodName}", invocationContext.HubMethodName); + throw; + } + } + + public Task OnConnectedAsync(HubLifetimeContext context, Func next) + { + _logger.LogInformation("Hub connected"); + try + { + return next(context); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error occurs while connecting hub"); + throw; + } + } + + public Task OnDisconnectedAsync(HubLifetimeContext context, Exception exception, Func next) + { + _logger.LogInformation("Hub disconnected"); + try + { + return next(context, exception); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error occurs while disconnecting hub"); + throw; + } + } + } } diff --git a/src/platform/mix.signalr/mix.signalr.csproj b/src/platform/mix.signalr/mix.signalr.csproj index 4c89adf1c..c47dc2776 100644 --- a/src/platform/mix.signalr/mix.signalr.csproj +++ b/src/platform/mix.signalr/mix.signalr.csproj @@ -7,10 +7,10 @@ - - - - + + + + diff --git a/src/platform/mix.storage.lib/Engines/Aws/AwsUploader.cs b/src/platform/mix.storage.lib/Engines/Aws/AwsUploader.cs index 11c105979..6c40e8734 100644 --- a/src/platform/mix.storage.lib/Engines/Aws/AwsUploader.cs +++ b/src/platform/mix.storage.lib/Engines/Aws/AwsUploader.cs @@ -1,11 +1,10 @@ -using System.Net; -using Amazon; +using Amazon; using Amazon.S3; using Amazon.S3.Model; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; -using Mix.Shared.Helpers; using Mix.Storage.Lib.Engines.Base; +using System.Net; namespace Mix.Storage.Lib.Engines.Aws { diff --git a/src/platform/mix.storage.lib/Engines/AzureStorage/AzureStorageSettings.cs b/src/platform/mix.storage.lib/Engines/AzureStorage/AzureStorageSettings.cs index 2cfb6e3f3..c382e2005 100644 --- a/src/platform/mix.storage.lib/Engines/AzureStorage/AzureStorageSettings.cs +++ b/src/platform/mix.storage.lib/Engines/AzureStorage/AzureStorageSettings.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Storage.Lib.Engines.AzureStorage +namespace Mix.Storage.Lib.Engines.AzureStorage { public sealed class AzureStorageSettings { diff --git a/src/platform/mix.storage.lib/Engines/AzureStorage/AzureStorageUploader.cs b/src/platform/mix.storage.lib/Engines/AzureStorage/AzureStorageUploader.cs index 07e567320..fe759e6d2 100644 --- a/src/platform/mix.storage.lib/Engines/AzureStorage/AzureStorageUploader.cs +++ b/src/platform/mix.storage.lib/Engines/AzureStorage/AzureStorageUploader.cs @@ -1,12 +1,8 @@ using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Microsoft.AspNetCore.Http; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Extensions.Configuration; -using Mix.Shared.Helpers; using Mix.Storage.Lib.Engines.Base; -using Mix.Storage.Lib.Engines.CloudFlare; -using Org.BouncyCastle.Ocsp; namespace Mix.Storage.Lib.Engines.AzureStorage { @@ -80,7 +76,7 @@ private string GetUploadFolder(string filename, string? fileFolder, string? crea { string ext = filename.Split('.')[1].ToLower(); string folder = $"{CurrentTenant.SystemName}/{MixFolders.UploadsFolder}/{ext}"; - + if (!string.IsNullOrEmpty(createdBy)) { folder = $"{folder}/{createdBy}"; diff --git a/src/platform/mix.storage.lib/Engines/Mix/MixUploader.cs b/src/platform/mix.storage.lib/Engines/Mix/MixUploader.cs index 4b45a9d24..866401946 100644 --- a/src/platform/mix.storage.lib/Engines/Mix/MixUploader.cs +++ b/src/platform/mix.storage.lib/Engines/Mix/MixUploader.cs @@ -1,13 +1,9 @@ using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Routing.Constraints; using Microsoft.Extensions.Configuration; -using Mix.Heart.Models; using Mix.Mq.Lib.Models; -using Mix.Shared.Helpers; using Mix.Storage.Lib.Engines.Base; using Mix.Storage.Lib.Helpers; using Mix.Storage.Lib.Models; -using System.IO; namespace Mix.Storage.Lib.Engines.Mix { diff --git a/src/platform/mix.storage.lib/Extensions/ServiceCollectionExtensions.cs b/src/platform/mix.storage.lib/Extensions/ServiceCollectionExtensions.cs index 55771f514..952685592 100644 --- a/src/platform/mix.storage.lib/Extensions/ServiceCollectionExtensions.cs +++ b/src/platform/mix.storage.lib/Extensions/ServiceCollectionExtensions.cs @@ -1,7 +1,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Mix.Storage.Lib.Services; -using Mix.Storage.Lib.Subscribers; namespace Mix.Storage.Lib.Extensions { diff --git a/src/platform/mix.storage.lib/Helpers/ImageHelper.cs b/src/platform/mix.storage.lib/Helpers/ImageHelper.cs index 09d616193..9c93c8bca 100644 --- a/src/platform/mix.storage.lib/Helpers/ImageHelper.cs +++ b/src/platform/mix.storage.lib/Helpers/ImageHelper.cs @@ -1,13 +1,6 @@ -using Mix.Identity.ViewModels; -using Mix.Storage.Lib.Models; -using Org.BouncyCastle.Utilities; -using SixLabors.ImageSharp.Formats; -using System; -using System.Collections.Generic; -using System.Drawing.Imaging; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Mix.Storage.Lib.Models; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Processing; namespace Mix.Storage.Lib.Helpers { diff --git a/src/platform/mix.storage.lib/Models/ImageSettingsModel.cs b/src/platform/mix.storage.lib/Models/ImageSettingsModel.cs index f0f3b7c2e..336f94f01 100644 --- a/src/platform/mix.storage.lib/Models/ImageSettingsModel.cs +++ b/src/platform/mix.storage.lib/Models/ImageSettingsModel.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Storage.Lib.Models +namespace Mix.Storage.Lib.Models { public class ImageSize { diff --git a/src/platform/mix.storage.lib/Models/StorageSettingsModel.cs b/src/platform/mix.storage.lib/Models/StorageSettingsModel.cs index a940cfc04..ed7fc1e08 100644 --- a/src/platform/mix.storage.lib/Models/StorageSettingsModel.cs +++ b/src/platform/mix.storage.lib/Models/StorageSettingsModel.cs @@ -1,11 +1,6 @@ using Mix.Storage.Lib.Engines.Aws; using Mix.Storage.Lib.Engines.AzureStorage; using Mix.Storage.Lib.Engines.CloudFlare; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Mix.Storage.Lib.Models { diff --git a/src/platform/mix.storage.lib/Services/MixStorageService.cs b/src/platform/mix.storage.lib/Services/MixStorageService.cs index d66cc1fb4..fcb1797dd 100644 --- a/src/platform/mix.storage.lib/Services/MixStorageService.cs +++ b/src/platform/mix.storage.lib/Services/MixStorageService.cs @@ -1,7 +1,5 @@ -using Amazon.S3; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; -using Mix.Heart.Models; using Mix.Mq.Lib.Models; using Mix.Storage.Lib.Engines.Aws; using Mix.Storage.Lib.Engines.AzureStorage; @@ -10,8 +8,6 @@ using Mix.Storage.Lib.Engines.Mix; using Mix.Storage.Lib.Helpers; using Mix.Storage.Lib.Models; -using MySqlX.XDevAPI.Common; -using System.IO; namespace Mix.Storage.Lib.Services { @@ -23,9 +19,9 @@ public class MixStorageService private readonly HttpService _httpService; public StorageSettingsModel Settings { get; set; } = new(); public MixStorageService( - IHttpContextAccessor httpContext, - UnitOfWorkInfo cmsUow, - IConfiguration configuration, + IHttpContextAccessor httpContext, + UnitOfWorkInfo cmsUow, + IConfiguration configuration, HttpService httpService, IMemoryQueueService queueService) { _configuration = configuration; diff --git a/src/platform/mix.storage.lib/Subscribers/StorageBackgroundTaskSubscriber.cs b/src/platform/mix.storage.lib/Subscribers/StorageBackgroundTaskSubscriber.cs index 6c106c858..1261a2cb1 100644 --- a/src/platform/mix.storage.lib/Subscribers/StorageBackgroundTaskSubscriber.cs +++ b/src/platform/mix.storage.lib/Subscribers/StorageBackgroundTaskSubscriber.cs @@ -2,16 +2,9 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; -using Mix.Communicator.Models; -using Mix.Communicator.Services; -using Mix.Lib.Subscribers; using Mix.Log.Lib.Interfaces; -using Mix.Mixdb.Event.Services; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; -using Mix.Queue.Engines.MixQueue; -using Mix.Service.Commands; -using Mix.Service.Interfaces; using Mix.Service.Services; using Mix.SignalR.Enums; using Mix.SignalR.Interfaces; diff --git a/src/platform/mix.storage.lib/mix.storage.lib.csproj b/src/platform/mix.storage.lib/mix.storage.lib.csproj index 94e1dfeb4..99800e682 100644 --- a/src/platform/mix.storage.lib/mix.storage.lib.csproj +++ b/src/platform/mix.storage.lib/mix.storage.lib.csproj @@ -9,8 +9,8 @@ - - + + diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Dtos/UpdateWarehouseDto.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Dtos/UpdateWarehouseDto.cs index b8beeb146..dd0d10968 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Dtos/UpdateWarehouseDto.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Dtos/UpdateWarehouseDto.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Services.Ecommerce.Lib.Dtos +namespace Mix.Services.Ecommerce.Lib.Dtos { public sealed class UpdateWarehouseDto { diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Mix/EntityConfigurations/OrderConfiguration.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Mix/EntityConfigurations/OrderConfiguration.cs index 69a33f48c..7b907ed36 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Mix/EntityConfigurations/OrderConfiguration.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Mix/EntityConfigurations/OrderConfiguration.cs @@ -6,7 +6,6 @@ using Mix.Services.Ecommerce.Lib.Enums; using Mix.Services.Payments.Lib.Constants; using Newtonsoft.Json.Linq; -using Quartz; namespace Mix.Services.Ecommerce.Lib.Entities.Mix.EntityConfigurations { diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Mix/EntityConfigurations/OrderItemConfiguration.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Mix/EntityConfigurations/OrderItemConfiguration.cs index d0c670cac..950862ca1 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Mix/EntityConfigurations/OrderItemConfiguration.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Mix/EntityConfigurations/OrderItemConfiguration.cs @@ -21,7 +21,7 @@ public override void Configure(EntityTypeBuilder builder) .IsRequired(false) .HasConversion(new EnumToStringConverter()) .HasColumnType($"{Config.String}{Config.SmallLength}") - .HasCharSet(Config.CharSet); + .HasCharSet(Config.CharSet); builder.Property(e => e.Currency).IsRequired(false); builder.Property(e => e.Title).IsRequired(false); builder.Property(e => e.Description).IsRequired(false); diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Paypal/PaypalTransactionResponse.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Paypal/PaypalTransactionResponse.cs index 6601082b2..193c69786 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Paypal/PaypalTransactionResponse.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Entities/Paypal/PaypalTransactionResponse.cs @@ -1,5 +1,4 @@ -using CommandLine; -using Mix.Heart.Entities; +using Mix.Heart.Entities; using Mix.Services.Ecommerce.Lib.Enums; using Mix.Services.Ecommerce.Lib.Models.Paypal; using Newtonsoft.Json.Linq; @@ -18,7 +17,7 @@ public class PaypalTransactionResponse : EntityBase public int MixTentantId { get; set; } public PaypalTransactionResponse() { - + } public PaypalTransactionResponse(PaypalOrderCapturedResponse response) { diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Enums/PaymentGateway.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Enums/PaymentGateway.cs index afebc6f07..ed02a3ac8 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Enums/PaymentGateway.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Enums/PaymentGateway.cs @@ -2,6 +2,7 @@ { public enum PaymentGateway { + Payoo, Onepay, Paypal, Momo diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Enums/PaymentStatus.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Enums/PaymentStatus.cs index 72e89450c..e7f64f69d 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Enums/PaymentStatus.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Enums/PaymentStatus.cs @@ -2,10 +2,10 @@ { public enum PaymentStatus { - SENT, - PENDING, - SUCCESS, - FAILED, - INVALIDRESPONSE + Sent, + Pending, + Success, + Failed, + InvalidResponse } } diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Extensions/EcommerceServiceProviderExtensions.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Extensions/EcommerceServiceProviderExtensions.cs index 116ce5983..ebd9c2bcd 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Extensions/EcommerceServiceProviderExtensions.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Extensions/EcommerceServiceProviderExtensions.cs @@ -80,7 +80,7 @@ public static void AddMixPaypal(this IServiceCollection services) { context.Database.Migrate(); } - context.Dispose(); + context.Dispose(); } } services.TryAddScoped(); diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Interfaces/IPaymentService.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Interfaces/IPaymentService.cs index 37ab4bf4b..100296b75 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Interfaces/IPaymentService.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Interfaces/IPaymentService.cs @@ -1,5 +1,4 @@ using Mix.Services.Ecommerce.Lib.Enums; -using Mix.Services.Ecommerce.Lib.Models.Onepay; using Mix.Services.Ecommerce.Lib.ViewModels; using Newtonsoft.Json.Linq; diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/EcommerceDb/20230528150942_InitEcommerce.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/EcommerceDb/20230528150942_InitEcommerce.cs index b9f7f0a65..b49ee33c7 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/EcommerceDb/20230528150942_InitEcommerce.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/EcommerceDb/20230528150942_InitEcommerce.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/EcommerceDb/20230607113542_AddOrderTempId.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/EcommerceDb/20230607113542_AddOrderTempId.cs index a4e635f8c..d806a3100 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/EcommerceDb/20230607113542_AddOrderTempId.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/EcommerceDb/20230607113542_AddOrderTempId.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/OnepayDb/20230527064302_InitOnepay.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/OnepayDb/20230527064302_InitOnepay.cs index 017015b0e..fb47971ff 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/OnepayDb/20230527064302_InitOnepay.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/OnepayDb/20230527064302_InitOnepay.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/PaypalDb/20230527135819_InitPaypal.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/PaypalDb/20230527135819_InitPaypal.cs index e0600aeac..e81e6dc28 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/PaypalDb/20230527135819_InitPaypal.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Migrations/PaypalDb/20230527135819_InitPaypal.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PayPalAccessToken.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PayPalAccessToken.cs index 193357791..c47b3f4b9 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PayPalAccessToken.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PayPalAccessToken.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Services.Ecommerce.Lib.Models.Paypal +namespace Mix.Services.Ecommerce.Lib.Models.Paypal { public sealed class PayPalAccessToken { diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalConfigurations.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalConfigurations.cs index 8a1243f67..81f0aad6f 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalConfigurations.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalConfigurations.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Services.Ecommerce.Lib.Models.Paypal +namespace Mix.Services.Ecommerce.Lib.Models.Paypal { public sealed class PaypalConfigurations { diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalOrderCapturedResponse.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalOrderCapturedResponse.cs index 50933175d..859dc91df 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalOrderCapturedResponse.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalOrderCapturedResponse.cs @@ -1,12 +1,4 @@ -using DocumentFormat.OpenXml.Wordprocessing; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using static Google.Rpc.Help.Types; - -namespace Mix.Services.Ecommerce.Lib.Models.Paypal +namespace Mix.Services.Ecommerce.Lib.Models.Paypal { public sealed class PaypalOrderCapturedResponse { diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalOrderCreatedResponse.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalOrderCreatedResponse.cs index d5b52cc62..8ce331fbc 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalOrderCreatedResponse.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalOrderCreatedResponse.cs @@ -1,11 +1,4 @@ -using Mix.Services.Ecommerce.Lib.ViewModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Mix.Services.Ecommerce.Lib.Models.Paypal +namespace Mix.Services.Ecommerce.Lib.Models.Paypal { public class PaypalOrderCreatedResponse { diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalRequest.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalRequest.cs index de29732ac..e630106d4 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalRequest.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalRequest.cs @@ -1,5 +1,4 @@ -using Mix.Services.Ecommerce.Lib.Interfaces; -using Mix.Services.Ecommerce.Lib.ViewModels; +using Mix.Services.Ecommerce.Lib.ViewModels; using Newtonsoft.Json.Linq; namespace Mix.Services.Ecommerce.Lib.Models.Paypal @@ -26,7 +25,7 @@ public class PaypalRequestPurchaseUnit { public PaypalRequestPurchaseUnit() { - + } public PaypalRequestPurchaseUnit(OrderViewModel order) { @@ -62,7 +61,7 @@ public class ResponsePurchaseUnit { public ResponsePurchaseUnit() { - + } public string reference_id { get; set; } public PaypalShipping shipping { get; set; } @@ -79,7 +78,7 @@ public class SellerReceivableBreakdown { public SellerReceivableBreakdown() { - + } public PaypalAmount gross_amount { get; set; } public PaypalAmount paypal_fee { get; set; } @@ -101,7 +100,7 @@ public class PaypalLink { public PaypalLink() { - + } public string rel { get; set; } public string method { get; set; } @@ -112,7 +111,7 @@ public class PurchaseItem { public PurchaseItem() { - + } public PurchaseItem(OrderItemViewModel item) { @@ -132,7 +131,7 @@ public class PaypalAmount { public PaypalAmount() { - + } public PaypalAmount(OrderViewModel order) { @@ -149,7 +148,7 @@ public class Payee { public Payee() { - + } public string merchant_id { get; set; } public string email_address { get; set; } @@ -159,7 +158,7 @@ public class Breakdown { public Breakdown() { - + } public Breakdown(OrderViewModel order) { @@ -184,7 +183,7 @@ public UnitAmount(OrderItemViewModel item) } public UnitAmount() { - + } public UnitAmount(string currency, double? total) { @@ -200,7 +199,7 @@ public class RedirecUrls { public RedirecUrls() { - + } public RedirecUrls(string returnUrl, string cancelUrl) { diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/EcommerceService.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/EcommerceService.cs index 2e2fcfbec..03ca9a4bb 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/EcommerceService.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/EcommerceService.cs @@ -1,23 +1,23 @@ using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Mix.Constant.Constants; using Mix.Heart.Enums; using Mix.Heart.Exceptions; using Mix.Heart.Helpers; +using Mix.Heart.Services; using Mix.Heart.UnitOfWork; +using Mix.Lib.Interfaces; using Mix.Lib.Services; +using Mix.Service.Services; using Mix.Services.Ecommerce.Lib.Dtos; +using Mix.Services.Ecommerce.Lib.Entities.Mix; using Mix.Services.Ecommerce.Lib.Enums; +using Mix.Services.Ecommerce.Lib.Interfaces; +using Mix.Services.Ecommerce.Lib.Models; using Mix.Services.Ecommerce.Lib.Providers; using Mix.Services.Ecommerce.Lib.ViewModels; -using Mix.Services.Ecommerce.Lib.Entities.Mix; using Newtonsoft.Json.Linq; using System.Security.Claims; -using Mix.Services.Ecommerce.Lib.Models; -using Mix.Constant.Constants; -using Microsoft.Extensions.Configuration; -using Mix.Service.Services; -using Mix.Services.Ecommerce.Lib.Interfaces; -using Mix.Lib.Interfaces; -using Mix.Heart.Services; namespace Mix.Services.Ecommerce.Lib.Services { @@ -117,7 +117,7 @@ public virtual async Task UpdateOrderStatus(int orderId, OrderStatus orderStatus await LogAction(orderId, OrderTrackingAction.PAID); break; case OrderStatus.SHIPPING: - if (order.PaymentStatus != PaymentStatus.SUCCESS) + if (order.PaymentStatus != PaymentStatus.Success) { throw new MixException(MixErrorStatus.Badrequest, "Cannot ship unpaid order"); } @@ -336,7 +336,7 @@ public virtual async Task ProcessPaymentResponse( throw new MixException(MixErrorStatus.ServerError, $"Not Implement {order.PaymentGateway} payment"); } - if (order.PaymentStatus != PaymentStatus.SUCCESS && order.PaymentStatus != PaymentStatus.FAILED) + if (order.PaymentStatus != PaymentStatus.Success && order.PaymentStatus != PaymentStatus.Failed) { order.PaymentResponse = paymentResponse; order.PaymentStatus = await paymentService.ProcessPaymentResponse(order, paymentResponse, cancellationToken); @@ -344,7 +344,7 @@ public virtual async Task ProcessPaymentResponse( } - if (order.PaymentStatus == PaymentStatus.SUCCESS) + if (order.PaymentStatus == PaymentStatus.Success) { order.OrderStatus = OrderStatus.PAID; if (!string.IsNullOrEmpty(order.Email)) diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/OnepayService.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/OnepayService.cs index 65f889cb7..8a02d51a7 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/OnepayService.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/OnepayService.cs @@ -155,22 +155,22 @@ public async Task ProcessPaymentResponse(OrderViewModel orderDeta var response = responseObj.ToObject() ?? throw new MixException(MixErrorStatus.Badrequest, "Cannot convert response."); - var paymentStatus = PaymentStatus.SUCCESS; + var paymentStatus = PaymentStatus.Success; if (!response.vpc_TxnResponseCode.Equals("0") && !string.IsNullOrEmpty(response.vpc_Message)) { if (!string.IsNullOrEmpty(response.vpc_SecureHash)) { if (!Settings.SecureHashKey.Equals(response.vpc_SecureHash)) { - paymentStatus = PaymentStatus.INVALIDRESPONSE; + paymentStatus = PaymentStatus.InvalidResponse; } } - paymentStatus = PaymentStatus.PENDING; + paymentStatus = PaymentStatus.Pending; } if (string.IsNullOrEmpty(response.vpc_SecureHash)) { - paymentStatus = PaymentStatus.INVALIDRESPONSE; + paymentStatus = PaymentStatus.InvalidResponse; } Dictionary parameters = ReflectionHelper.ConverObjectToDictinary(response); var secureHashKey = CreateSHA256Signature(parameters); diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/OrderService.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/OrderService.cs index bbbf63404..48f02f7d7 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/OrderService.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/OrderService.cs @@ -1,20 +1,20 @@ using Microsoft.AspNetCore.Http; using Mix.Heart.Enums; using Mix.Heart.Exceptions; +using Mix.Heart.Extensions; +using Mix.Heart.Models; +using Mix.Heart.Services; using Mix.Heart.UnitOfWork; +using Mix.Lib.Interfaces; +using Mix.Lib.Models.Common; using Mix.Lib.Services; +using Mix.Service.Services; using Mix.Services.Ecommerce.Lib.Dtos; +using Mix.Services.Ecommerce.Lib.Entities.Mix; using Mix.Services.Ecommerce.Lib.Enums; +using Mix.Services.Ecommerce.Lib.Interfaces; using Mix.Services.Ecommerce.Lib.ViewModels; -using Mix.Services.Ecommerce.Lib.Entities.Mix; using System.Security.Claims; -using Mix.Lib.Models.Common; -using Mix.Heart.Models; -using Mix.Heart.Extensions; -using Mix.Service.Services; -using Mix.Services.Ecommerce.Lib.Interfaces; -using Mix.Heart.Services; -using Mix.Lib.Interfaces; namespace Mix.Services.Ecommerce.Lib.Services { @@ -80,7 +80,7 @@ public async Task CancelOrder( var user = await _userManager.GetUserAsync(principal) ?? throw new MixException(MixErrorStatus.Badrequest, "User not found"); var order = await OrderViewModel.GetRepository(_uow, CacheService).GetSingleAsync(m => m.Id == id && m.UserId == user!.Id, cancellationToken) ?? throw new MixException(MixErrorStatus.Badrequest, "Invalid Order"); - if (order.PaymentStatus == PaymentStatus.SUCCESS) + if (order.PaymentStatus == PaymentStatus.Success) { throw new MixException(MixErrorStatus.Badrequest, "Cannot cancel paid order"); } diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs index c8c4f0c94..7a61fa589 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs @@ -5,6 +5,7 @@ using Mix.Heart.Exceptions; using Mix.Heart.Services; using Mix.Heart.UnitOfWork; +using Mix.Lib.Interfaces; using Mix.Service.Services; using Mix.Services.Ecommerce.Lib.Entities.Paypal; using Mix.Services.Ecommerce.Lib.Enums; @@ -12,17 +13,11 @@ using Mix.Services.Ecommerce.Lib.Models.Paypal; using Mix.Services.Ecommerce.Lib.ViewModels; using Mix.Services.Ecommerce.Lib.ViewModels.Paypal; -using Mix.Shared.Services; -using Newtonsoft.Json.Linq; -using System.Text; +using Mix.Services.Payments.Lib.Constants; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using System.Net.Http.Headers; -using System.Net.Http; -using Mix.Services.Payments.Lib.Constants; -using DocumentFormat.OpenXml.Office2010.Excel; -using System.Text.RegularExpressions; -using Quartz.Util; -using Mix.Lib.Interfaces; +using System.Text; namespace Mix.Services.Ecommerce.Lib.Services { @@ -76,7 +71,7 @@ public async Task ProcessPaymentResponse(OrderViewModel orderDeta { try { - if (orderDetail.PaymentStatus == PaymentStatus.SUCCESS || orderDetail.PaymentStatus == PaymentStatus.FAILED) + if (orderDetail.PaymentStatus == PaymentStatus.Success || orderDetail.PaymentStatus == PaymentStatus.Failed) { return orderDetail.PaymentStatus; } @@ -84,7 +79,7 @@ public async Task ProcessPaymentResponse(OrderViewModel orderDeta string? token = response.Value("token"); string? payerId = response.Value("PayerID"); var result = await CaptureOrderResult(token); - if (string.IsNullOrEmpty(result?.id) && orderDetail.PaymentStatus == PaymentStatus.SENT) + if (string.IsNullOrEmpty(result?.id) && orderDetail.PaymentStatus == PaymentStatus.Sent) { result = await GetOrderResult(token); } @@ -95,7 +90,7 @@ public async Task ProcessPaymentResponse(OrderViewModel orderDeta } var reference = result.purchase_units[0].reference_id; - var status = !string.IsNullOrEmpty(reference) ? PaymentStatus.SUCCESS : PaymentStatus.FAILED; + var status = !string.IsNullOrEmpty(reference) ? PaymentStatus.Success : PaymentStatus.Failed; await SaveResponse(result, status, cancellationToken); return status; diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/OrderItemViewModel.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/OrderItemViewModel.cs index 8dc3fbba0..fd6344a15 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/OrderItemViewModel.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/OrderItemViewModel.cs @@ -1,7 +1,5 @@ -using DocumentFormat.OpenXml.Office.CustomUI; -using Mix.Heart.UnitOfWork; +using Mix.Heart.UnitOfWork; using Mix.Heart.ViewModel; -using Mix.Lib.Attributes; using Mix.Services.Ecommerce.Lib.Entities.Mix; using Mix.Services.Ecommerce.Lib.Enums; using Mix.Services.Payments.Lib.Constants; @@ -79,7 +77,7 @@ protected override async Task SaveEntityRelationshipAsync(OrderItem parentEntity ParentId = parentEntity.OrderDetailId, ChildId = parentEntity.Id, ChildDatabaseName = EcommerceConstants.DataTableNameOrderItem, - CreatedDateTime = DateTime.Now, + CreatedDateTime = DateTime.UtcNow, CreatedBy = CreatedBy, MixTenantId = MixTenantId }; diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/Paypal/PaypalTransactionRequestViewModel.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/Paypal/PaypalTransactionRequestViewModel.cs index b69326317..b6bfb58fc 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/Paypal/PaypalTransactionRequestViewModel.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/Paypal/PaypalTransactionRequestViewModel.cs @@ -2,7 +2,6 @@ using Mix.Heart.ViewModel; using Mix.Services.Ecommerce.Lib.Entities.Paypal; using Mix.Services.Ecommerce.Lib.Enums; -using Mix.Services.Ecommerce.Lib.Models.Paypal; using Newtonsoft.Json.Linq; namespace Mix.Services.Ecommerce.Lib.ViewModels.Paypal diff --git a/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/WarehouseViewModel.cs b/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/WarehouseViewModel.cs index a3f5cb77c..0a60ecb8f 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/WarehouseViewModel.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce.lib/ViewModels/WarehouseViewModel.cs @@ -1,5 +1,4 @@ -using Mix.Constant.Enums; -using Mix.Heart.UnitOfWork; +using Mix.Heart.UnitOfWork; using Mix.Heart.ViewModel; using Mix.Services.Ecommerce.Lib.Entities; using Mix.Services.Ecommerce.Lib.Entities.Mix; diff --git a/src/services/core/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs b/src/services/core/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs index 5c33ce475..3cea9582a 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs @@ -9,15 +9,11 @@ using Mix.Lib.Services; using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; -using Mix.Service.Services; using Mix.Services.Ecommerce.Lib.Dtos; using Mix.Services.Ecommerce.Lib.Enums; using Mix.Services.Ecommerce.Lib.Interfaces; using Mix.Services.Ecommerce.Lib.Models; using Mix.Services.Ecommerce.Lib.ViewModels; -using Mix.SignalR.Interfaces; -using Mix.SignalR.Models; -using MySqlX.XDevAPI.Common; using Newtonsoft.Json.Linq; using System.Web; diff --git a/src/services/core/ecommerces/mix.services.ecommerce/Controllers/ApiOrderDetailController.cs b/src/services/core/ecommerces/mix.services.ecommerce/Controllers/ApiOrderDetailController.cs index 6ce47d0b3..3d34c9fbe 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce/Controllers/ApiOrderDetailController.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce/Controllers/ApiOrderDetailController.cs @@ -33,7 +33,7 @@ public OrderDetailController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { Repository.IsCache = false; diff --git a/src/services/core/ecommerces/mix.services.ecommerce/StartupService.cs b/src/services/core/ecommerces/mix.services.ecommerce/StartupService.cs index 25e0cd0c0..a24abd380 100644 --- a/src/services/core/ecommerces/mix.services.ecommerce/StartupService.cs +++ b/src/services/core/ecommerces/mix.services.ecommerce/StartupService.cs @@ -17,7 +17,7 @@ public void AddServices(IServiceCollection services, IConfiguration configuratio { services.AddMixEcommerce(configuration); services.TryAddScoped(); - + } } diff --git a/src/services/core/graphql/mix.services.graphql.lib/Models/ColumnMetadata.cs b/src/services/core/graphql/mix.services.graphql.lib/Models/ColumnMetadata.cs index 84280ff71..888b70f51 100644 --- a/src/services/core/graphql/mix.services.graphql.lib/Models/ColumnMetadata.cs +++ b/src/services/core/graphql/mix.services.graphql.lib/Models/ColumnMetadata.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Mix.Services.Graphql.Lib.Models +namespace Mix.Services.Graphql.Lib.Models { public class ColumnMetadata { diff --git a/src/services/core/graphql/mix.services.graphql.lib/Models/DatabaseMetadata.cs b/src/services/core/graphql/mix.services.graphql.lib/Models/DatabaseMetadata.cs index 6baa9e26e..6c9a510fa 100644 --- a/src/services/core/graphql/mix.services.graphql.lib/Models/DatabaseMetadata.cs +++ b/src/services/core/graphql/mix.services.graphql.lib/Models/DatabaseMetadata.cs @@ -1,7 +1,5 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; - -using Mix.Services.Graphql.Lib.Entities; using Mix.Services.Graphql.Lib.Interfaces; namespace Mix.Services.Graphql.Lib.Models diff --git a/src/services/core/graphql/mix.services.graphql.lib/Models/TableMetadata.cs b/src/services/core/graphql/mix.services.graphql.lib/Models/TableMetadata.cs index 3d88f9437..7678b9e8c 100644 --- a/src/services/core/graphql/mix.services.graphql.lib/Models/TableMetadata.cs +++ b/src/services/core/graphql/mix.services.graphql.lib/Models/TableMetadata.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Mix.Services.Graphql.Lib.Models +namespace Mix.Services.Graphql.Lib.Models { public class TableMetadata { diff --git a/src/services/core/graphql/mix.services.graphql.lib/Providers/DynamicLinqProvider.cs b/src/services/core/graphql/mix.services.graphql.lib/Providers/DynamicLinqProvider.cs index 2cb46dc2e..27b9401e1 100644 --- a/src/services/core/graphql/mix.services.graphql.lib/Providers/DynamicLinqProvider.cs +++ b/src/services/core/graphql/mix.services.graphql.lib/Providers/DynamicLinqProvider.cs @@ -1,10 +1,6 @@ using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; using System.Linq.Dynamic.Core.CustomTypeProviders; using System.Reflection; -using System.Threading.Tasks; namespace Mix.Services.Graphql.Lib.Providers { diff --git a/src/services/core/graphql/mix.services.graphql.lib/Resolvers/MyFieldResolver.cs b/src/services/core/graphql/mix.services.graphql.lib/Resolvers/MyFieldResolver.cs index f25916f1e..a8f2d73f3 100644 --- a/src/services/core/graphql/mix.services.graphql.lib/Resolvers/MyFieldResolver.cs +++ b/src/services/core/graphql/mix.services.graphql.lib/Resolvers/MyFieldResolver.cs @@ -1,9 +1,7 @@ using GraphQL; using GraphQL.Resolvers; using Microsoft.EntityFrameworkCore; -using Mix.Database.Base; using Mix.Heart.Extensions; -using Mix.Services.Graphql.Lib; using Mix.Services.Graphql.Lib.Models; using System.Linq.Dynamic.Core; diff --git a/src/services/core/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs b/src/services/core/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs index 9c8474ffc..10918d22e 100644 --- a/src/services/core/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs +++ b/src/services/core/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs @@ -1,10 +1,5 @@ using GraphQL; using GraphQL.Resolvers; -using GraphQL.Types; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Mix.Heart.Extensions; namespace Mix.Services.Graphql.Lib.Resolvers diff --git a/src/services/core/graphql/mix.services.graphql.lib/ServiceCollectionExtensions.cs b/src/services/core/graphql/mix.services.graphql.lib/ServiceCollectionExtensions.cs index 9d7d05497..4e3d9a9ec 100644 --- a/src/services/core/graphql/mix.services.graphql.lib/ServiceCollectionExtensions.cs +++ b/src/services/core/graphql/mix.services.graphql.lib/ServiceCollectionExtensions.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Mix.Constant.Constants; using Mix.Database.Services; using Mix.Mixdb.Services; using Mix.Services.Graphql.Lib.Entities; @@ -28,8 +29,10 @@ public static IServiceCollection AddMixGraphQL(this IServiceCollection services) services.TryAddSingleton(); services.TryAddSingleton((resolver) => { + string mixdbCnn = dbService.GetConnectionString(MixConstants.CONST_MIXDB_CONNECTION); var runtimeDbContextService = resolver.GetRequiredService(); - var dbContext = runtimeDbContextService.GetMixDatabaseDbContext()!; + runtimeDbContextService.LoadDbContextAssembly(mixdbCnn); + var dbContext = runtimeDbContextService.GetMixDatabaseDbContext(mixdbCnn)!; var tableNameLookup = resolver.GetRequiredService(); DatabaseMetadata metaDatabase = new(dbContext, tableNameLookup); var schema = new Schema { Query = new GraphQLQuery(dbContext, metaDatabase, tableNameLookup) }; diff --git a/src/services/core/graphql/mix.services.graphql.lib/mix.services.graphql.lib.csproj b/src/services/core/graphql/mix.services.graphql.lib/mix.services.graphql.lib.csproj index 47dc8043b..a778d93b5 100644 --- a/src/services/core/graphql/mix.services.graphql.lib/mix.services.graphql.lib.csproj +++ b/src/services/core/graphql/mix.services.graphql.lib/mix.services.graphql.lib.csproj @@ -18,8 +18,8 @@ - - + + diff --git a/src/services/core/graphql/mix.services.graphql/Controllers/GraphqlController.cs b/src/services/core/graphql/mix.services.graphql/Controllers/GraphqlController.cs index 094a55ac6..4777d5c84 100644 --- a/src/services/core/graphql/mix.services.graphql/Controllers/GraphqlController.cs +++ b/src/services/core/graphql/mix.services.graphql/Controllers/GraphqlController.cs @@ -4,10 +4,6 @@ using GraphQL.Types; using GraphQL.Validation; using Microsoft.AspNetCore.Mvc; -using Mix.Database.Entities.Cms; - -using Mix.Services.Graphql.Lib; -using Mix.Services.Graphql.Lib.Models; namespace Mix.Services.Graphql.Controllers { diff --git a/src/services/core/graphql/mix.services.graphql/mix.services.graphql.csproj b/src/services/core/graphql/mix.services.graphql/mix.services.graphql.csproj index e9f152b03..77beeba3b 100644 --- a/src/services/core/graphql/mix.services.graphql/mix.services.graphql.csproj +++ b/src/services/core/graphql/mix.services.graphql/mix.services.graphql.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/services/mix-auth-service/mix.auth.api/Controllers/MixAccountController.cs b/src/services/core/mix-auth-service/mix.auth.api/Controllers/MixAccountController.cs similarity index 100% rename from src/services/mix-auth-service/mix.auth.api/Controllers/MixAccountController.cs rename to src/services/core/mix-auth-service/mix.auth.api/Controllers/MixAccountController.cs index 50374694c..94b30f8cb 100644 --- a/src/services/mix-auth-service/mix.auth.api/Controllers/MixAccountController.cs +++ b/src/services/core/mix-auth-service/mix.auth.api/Controllers/MixAccountController.cs @@ -3,27 +3,27 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.EntityFrameworkCore; +using Mix.Auth.Dtos; +using Mix.Auth.Models.OAuthRequests; using Mix.Database.Entities.Account; using Mix.Database.Services; using Mix.Heart.Models; using Mix.Identity.Domain.Models; +using Mix.Identity.Interfaces; using Mix.Identity.Models; +using Mix.Identity.Models.ManageViewModels; +using Mix.Lib.Interfaces; using Mix.Lib.Services; +using Mix.Mq.Lib.Models; +using Mix.Queue.Interfaces; +using Mix.RepoDb.Interfaces; using Mix.RepoDb.Repositories; using Mix.Shared.Services; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using RepoDb; using System.Linq.Expressions; -using Mix.Queue.Interfaces; -using Newtonsoft.Json.Linq; using System.Web; -using Mix.Identity.Models.ManageViewModels; -using Mix.Lib.Interfaces; -using Mix.Auth.Dtos; -using Mix.Auth.Models.OAuthRequests; -using Mix.Identity.Interfaces; -using Mix.Mq.Lib.Models; -using Mix.RepoDb.Interfaces; namespace mix.auth.service.Controllers { diff --git a/src/services/mix-auth-service/mix.auth.api/Controllers/MixRoleController.cs b/src/services/core/mix-auth-service/mix.auth.api/Controllers/MixRoleController.cs similarity index 55% rename from src/services/mix-auth-service/mix.auth.api/Controllers/MixRoleController.cs rename to src/services/core/mix-auth-service/mix.auth.api/Controllers/MixRoleController.cs index 1b9daf2e2..b5cc808c3 100644 --- a/src/services/mix-auth-service/mix.auth.api/Controllers/MixRoleController.cs +++ b/src/services/core/mix-auth-service/mix.auth.api/Controllers/MixRoleController.cs @@ -1,21 +1,23 @@ -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Mix.Database.Entities.Account; using Mix.Heart.Entities.Cache; +using Mix.Heart.Models; +using Mix.Identity.Models; using Mix.Lib.Interfaces; using Mix.Lib.Services; using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; +using Mix.Services.Databases.Lib.Interfaces; namespace mix.auth.service.Controllers { - [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "SuperAdmin, Owner")] + [MixAuthorize(roles: MixRoles.Owner)] [Route("api/v2/rest/auth/role")] [ApiController] public class MixRoleController : MixRestEntityApiControllerBase { private readonly TenantRoleManager _roleManager; + private readonly IMixPermissionService _permissionService; public MixRoleController( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, @@ -26,11 +28,35 @@ public MixRoleController( MixCmsAccountContext context, IMemoryQueueService queueService, IMixTenantService mixTenantService, - TenantRoleManager roleManager) + TenantRoleManager roleManager, + IMixPermissionService permissionService) : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, cacheDbContext, context, queueService, mixTenantService) { _roleManager = roleManager; + _permissionService = permissionService; + } + public override async Task>> Get([FromQuery] SearchRequestDto req) + { + var roles = await base.GetHandler(req); + var result = new PagingResponseModel() + { + PagingData = roles.PagingData + }; + var models = new List(); + foreach (var item in roles.Items) + { + models.Add(new RoleBOModel() + { + ConcurrencyStamp = item.ConcurrencyStamp, + Id = item.Id, + Name = item.Name, + NormalizedName = item.NormalizedName, + Permissions = await _permissionService.GetPermissionByRoleId(item.Id) + }); + } + result.Items = models; + return Ok(result); } protected override async Task CreateHandlerAsync(MixRole data) @@ -43,13 +69,12 @@ protected override async Task CreateHandlerAsync(MixRole data) } else { - throw new MixException(MixErrorStatus.Badrequest, "Invalid Role", result.Errors.Select(m=>m.Description).ToArray()); + throw new MixException(MixErrorStatus.Badrequest, "Invalid Role", result.Errors.Select(m => m.Description).ToArray()); } } protected override async Task DeleteHandler(MixRole data) { await _roleManager.DeleteAsync(data); - await base.DeleteHandler(data); } } } diff --git a/src/services/mix-auth-service/mix.auth.api/Controllers/OAuthClientController.cs b/src/services/core/mix-auth-service/mix.auth.api/Controllers/OAuthClientController.cs similarity index 89% rename from src/services/mix-auth-service/mix.auth.api/Controllers/OAuthClientController.cs rename to src/services/core/mix-auth-service/mix.auth.api/Controllers/OAuthClientController.cs index 2d4a56efe..0361f18b0 100644 --- a/src/services/mix-auth-service/mix.auth.api/Controllers/OAuthClientController.cs +++ b/src/services/core/mix-auth-service/mix.auth.api/Controllers/OAuthClientController.cs @@ -1,5 +1,4 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Mix.Database.Entities.Account; using Mix.Identity.Interfaces; using Mix.Identity.ViewModels; @@ -25,18 +24,18 @@ public OAuthClientController(IHttpContextAccessor httpContextAccessor, IConfigur protected override async Task CreateHandlerAsync(OAuthClientViewModel data, CancellationToken cancellationToken = default) { var result = await base.CreateHandlerAsync(data, cancellationToken); - _oauthClientService.LoadClients(true); + _oauthClientService.LoadClients(Uow.DbContext, true); return result; } protected override async Task UpdateHandler(Guid id, OAuthClientViewModel data, CancellationToken cancellationToken = default) { await base.UpdateHandler(id, data, cancellationToken); - _oauthClientService.LoadClients(true); + _oauthClientService.LoadClients(Uow.DbContext, true); } protected override async Task DeleteHandler(OAuthClientViewModel data, CancellationToken cancellationToken = default) { await base.DeleteHandler(data, cancellationToken); - _oauthClientService.LoadClients(true); + _oauthClientService.LoadClients(Uow.DbContext, true); } } } diff --git a/src/services/mix-auth-service/mix.auth.api/Dockerfile b/src/services/core/mix-auth-service/mix.auth.api/Dockerfile similarity index 76% rename from src/services/mix-auth-service/mix.auth.api/Dockerfile rename to src/services/core/mix-auth-service/mix.auth.api/Dockerfile index 94a1286c9..7b1af72b8 100644 --- a/src/services/mix-auth-service/mix.auth.api/Dockerfile +++ b/src/services/core/mix-auth-service/mix.auth.api/Dockerfile @@ -10,8 +10,8 @@ FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build ARG BUILD_CONFIGURATION=Release WORKDIR /src COPY ["platform/core/mix-heart/nuget.config", "platform/core/mix-heart/"] -COPY ["services/mix-auth-service/mix.auth.service/mix.auth.api.csproj", "services/mix-auth-service/mix.auth.service/"] -COPY ["applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/"] +COPY ["services/core/mix-auth-service/mix.auth.api/mix.auth.api.csproj", "services/core/mix-auth-service/mix.auth.api/"] +COPY ["applications/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "applications/mixcore.host.aspire.ServiceDefaults/"] COPY ["modules/mix.grpc/mix.grpc.csproj", "modules/mix.grpc/"] COPY ["platform/mix.library/mix.library.csproj", "platform/mix.library/"] COPY ["platform/core/mix.mixdb.event/mix.mixdb.event.csproj", "platform/core/mix.mixdb.event/"] @@ -25,16 +25,16 @@ COPY ["platform/mix.identity/mix.identity.csproj", "platform/mix.identity/"] COPY ["platform/mix.auth/mix.auth.csproj", "platform/mix.auth/"] COPY ["platform/mix.quartz/mix.quartz.csproj", "platform/mix.quartz/"] COPY ["platform/mix.queue/mix.queue.csproj", "platform/mix.queue/"] -COPY ["services/mix-message-queue/mix.mq.server/mix.mq.server.csproj", "services/mix-message-queue/mix.mq/"] -COPY ["services/mix-message-queue/mix.mq.lib/mix.mq.lib.csproj", "services/mix-message-queue/mix.mq.lib/"] +COPY ["services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj", "services/core/mix-message-queue/mix.mq/"] +COPY ["services/core/mix-message-queue/mix.mq.lib/mix.mq.lib.csproj", "services/core/mix-message-queue/mix.mq.lib/"] COPY ["platform/mix.signalr/mix.signalr.csproj", "platform/mix.signalr/"] COPY ["platform/mix.repodb/mix.repodb.csproj", "platform/mix.repodb/"] COPY ["platform/mix.communicator/mix.communicator.csproj", "platform/mix.communicator/"] COPY ["platform/mix.signalr.hub/mix.signalr.hub.csproj", "platform/mix.signalr.hub/"] COPY ["platform/mix.log/mix.log.lib.csproj", "platform/mix.log/"] -RUN dotnet restore "./services/mix-auth-service/mix.auth.service/mix.auth.api.csproj" +RUN dotnet restore "./services/core/mix-auth-service/mix.auth.api/mix.auth.api.csproj" COPY . . -WORKDIR "/src/services/mix-auth-service/mix.auth.service" +WORKDIR "/src/services/core/mix-auth-service/mix.auth.api" RUN dotnet build "./mix.auth.api.csproj" -c $BUILD_CONFIGURATION -o /app/build FROM build AS publish diff --git a/src/services/mix-auth-service/mix.auth.api/Dockerfile_linux b/src/services/core/mix-auth-service/mix.auth.api/Dockerfile_linux similarity index 69% rename from src/services/mix-auth-service/mix.auth.api/Dockerfile_linux rename to src/services/core/mix-auth-service/mix.auth.api/Dockerfile_linux index f36bf250b..0d04f355b 100644 --- a/src/services/mix-auth-service/mix.auth.api/Dockerfile_linux +++ b/src/services/core/mix-auth-service/mix.auth.api/Dockerfile_linux @@ -8,8 +8,8 @@ EXPOSE 8081 FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build ARG BUILD_CONFIGURATION=Release COPY ["src/platform/core/mix-heart/nuget.config", "src/platform/core/mix-heart/"] -COPY ["src/services/mix-auth-service/mix.auth.service/mix.auth.api.csproj", "src/services/mix-auth-service/mix.auth.service/"] -COPY ["src/applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "src/applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/"] +COPY ["src/services/core/mix-auth-service/mix.auth.api/mix.auth.api.csproj", "src/services/core/mix-auth-service/mix.auth.api/"] +COPY ["src/applications/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "applications/mixcore.host.aspire.ServiceDefaults/"] COPY ["src/modules/mix.grpc/mix.grpc.csproj", "src/modules/mix.grpc/"] COPY ["src/platform/mix.library/mix.library.csproj", "src/platform/mix.library/"] COPY ["src/platform/core/mix.mixdb.event/mix.mixdb.event.csproj", "src/platform/core/mix.mixdb.event/"] @@ -23,20 +23,20 @@ COPY ["src/platform/mix.identity/mix.identity.csproj", "src/platform/mix.identit COPY ["src/platform/mix.auth/mix.auth.csproj", "src/platform/mix.auth/"] COPY ["src/platform/mix.quartz/mix.quartz.csproj", "src/platform/mix.quartz/"] COPY ["src/platform/mix.queue/mix.queue.csproj", "src/platform/mix.queue/"] -COPY ["src/services/mix-message-queue/mix.mq.server/mix.mq.server.csproj", "src/services/mix-message-queue/mix.mq/"] -COPY ["src/services/mix-message-queue/mix.mq.lib/mix.mq.lib.csproj", "src/services/mix-message-queue/mix.mq.lib/"] +COPY ["src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj", "src/services/core/mix-message-queue/mix.mq/"] +COPY ["src/services/core/mix-message-queue/mix.mq.lib/mix.mq.lib.csproj", "src/services/core/mix-message-queue/mix.mq.lib/"] COPY ["src/platform/mix.signalr/mix.signalr.csproj", "src/platform/mix.signalr/"] COPY ["src/platform/mix.repodb/mix.repodb.csproj", "src/platform/mix.repodb/"] COPY ["src/platform/mix.communicator/mix.communicator.csproj", "src/platform/mix.communicator/"] COPY ["src/platform/mix.signalr.hub/mix.signalr.hub.csproj", "src/platform/mix.signalr.hub/"] COPY ["src/platform/mix.log/mix.log.lib.csproj", "src/platform/mix.log/"] -RUN dotnet restore "src/services/mix-auth-service/mix.auth.service/mix.auth.api.csproj" +RUN dotnet restore "src/services/core/mix-auth-service/mix.auth.api/mix.auth.api.csproj" COPY . . -RUN dotnet build "src/services/mix-auth-service/mix.auth.service/mix.auth.api.csproj" -c $BUILD_CONFIGURATION -o /app/build +RUN dotnet build "src/services/core/mix-auth-service/mix.auth.api/mix.auth.api.csproj" -c $BUILD_CONFIGURATION -o /app/build FROM build AS publish ARG BUILD_CONFIGURATION=Release -RUN dotnet publish "src/services/mix-auth-service/mix.auth.service/mix.auth.api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false +RUN dotnet publish "src/services/core/mix-auth-service/mix.auth.api/mix.auth.api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false FROM base AS final COPY --from=publish /app/publish . diff --git a/src/services/mix-auth-service/mix.auth.api/Domain/Protos/mixmq.proto b/src/services/core/mix-auth-service/mix.auth.api/Domain/Protos/mixmq.proto similarity index 100% rename from src/services/mix-auth-service/mix.auth.api/Domain/Protos/mixmq.proto rename to src/services/core/mix-auth-service/mix.auth.api/Domain/Protos/mixmq.proto diff --git a/src/services/mix-auth-service/mix.auth.api/Domain/StartupService.cs b/src/services/core/mix-auth-service/mix.auth.api/Domain/StartupService.cs similarity index 100% rename from src/services/mix-auth-service/mix.auth.api/Domain/StartupService.cs rename to src/services/core/mix-auth-service/mix.auth.api/Domain/StartupService.cs diff --git a/src/services/mix-auth-service/mix.auth.api/Domain/Subscribers/MixAuthBackgroundTaskSubscriber.cs b/src/services/core/mix-auth-service/mix.auth.api/Domain/Subscribers/MixAuthBackgroundTaskSubscriber.cs similarity index 91% rename from src/services/mix-auth-service/mix.auth.api/Domain/Subscribers/MixAuthBackgroundTaskSubscriber.cs rename to src/services/core/mix-auth-service/mix.auth.api/Domain/Subscribers/MixAuthBackgroundTaskSubscriber.cs index a7b9d4af5..2ebfc41e9 100644 --- a/src/services/mix-auth-service/mix.auth.api/Domain/Subscribers/MixAuthBackgroundTaskSubscriber.cs +++ b/src/services/core/mix-auth-service/mix.auth.api/Domain/Subscribers/MixAuthBackgroundTaskSubscriber.cs @@ -1,12 +1,7 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.ObjectPool; -using Mix.Constant.Constants; +using Microsoft.Extensions.ObjectPool; using Mix.Mq.Lib.Models; using Mix.Queue.Engines; using Mix.Queue.Interfaces; -using Mix.Service.Services; using Mix.SignalR.Enums; using Mix.SignalR.Interfaces; using Mix.SignalR.Models; @@ -45,7 +40,7 @@ public override Task StartAsync(CancellationToken cancellationToken = default) } catch (Exception ex) { - _logger.LogError(GetType().Name, ex); + Logger.LogError(GetType().Name, ex); } } }); diff --git a/src/services/mix-auth-service/mix.auth.api/Domain/ViewModels/MixRoleViewModel.cs b/src/services/core/mix-auth-service/mix.auth.api/Domain/ViewModels/MixRoleViewModel.cs similarity index 100% rename from src/services/mix-auth-service/mix.auth.api/Domain/ViewModels/MixRoleViewModel.cs rename to src/services/core/mix-auth-service/mix.auth.api/Domain/ViewModels/MixRoleViewModel.cs diff --git a/src/services/mix-auth-service/mix.auth.api/Program.cs b/src/services/core/mix-auth-service/mix.auth.api/Program.cs similarity index 91% rename from src/services/mix-auth-service/mix.auth.api/Program.cs rename to src/services/core/mix-auth-service/mix.auth.api/Program.cs index d674c9de9..b22f881fe 100644 --- a/src/services/mix-auth-service/mix.auth.api/Program.cs +++ b/src/services/core/mix-auth-service/mix.auth.api/Program.cs @@ -1,12 +1,8 @@ -using Mix.Constant.Constants; using Mix.Database.Entities.Account; -using Mix.Heart.Services; -using System.Configuration; -using System.Reflection; -using Mix.Log.Lib; -using Microsoft.Azure.Amqp.Framing; using Mix.Lib.Middlewares; - +using Mix.Lib.Services; +using Mix.Log.Lib; +using System.Reflection; if (Directory.Exists($"../{MixFolders.MixCoreConfigurationFolder}")) { MixFileHelper.CopyFolder($"../{MixFolders.MixCoreConfigurationFolder}", MixFolders.MixContentSharedFolder); @@ -30,7 +26,7 @@ builder.Services.AddMixLog(builder.Configuration); // Must app Auth config after Add mixservice to init App config builder.Services.AddMixAuthorize(builder.Configuration); - +builder.Services.AddScoped(); var app = builder.Build(); diff --git a/src/services/mix-auth-service/mix.auth.api/Properties/launchSettings.json b/src/services/core/mix-auth-service/mix.auth.api/Properties/launchSettings.json similarity index 100% rename from src/services/mix-auth-service/mix.auth.api/Properties/launchSettings.json rename to src/services/core/mix-auth-service/mix.auth.api/Properties/launchSettings.json diff --git a/src/services/mix-auth-service/mix.auth.api/appsettings.Development.json b/src/services/core/mix-auth-service/mix.auth.api/appsettings.Development.json similarity index 100% rename from src/services/mix-auth-service/mix.auth.api/appsettings.Development.json rename to src/services/core/mix-auth-service/mix.auth.api/appsettings.Development.json diff --git a/src/services/mix-auth-service/mix.auth.api/mix.auth.api.csproj b/src/services/core/mix-auth-service/mix.auth.api/mix.auth.api.csproj similarity index 68% rename from src/services/mix-auth-service/mix.auth.api/mix.auth.api.csproj rename to src/services/core/mix-auth-service/mix.auth.api/mix.auth.api.csproj index 84d076925..8e0efb604 100644 --- a/src/services/mix-auth-service/mix.auth.api/mix.auth.api.csproj +++ b/src/services/core/mix-auth-service/mix.auth.api/mix.auth.api.csproj @@ -1,4 +1,4 @@ - + net8.0 @@ -14,20 +14,15 @@ Mix.Auth.Api - - - - - - - + - - - - + + + + + @@ -52,7 +47,7 @@ - + diff --git a/src/services/mix-auth-service/mix.auth.api/mix.auth.service.http b/src/services/core/mix-auth-service/mix.auth.api/mix.auth.service.http similarity index 100% rename from src/services/mix-auth-service/mix.auth.api/mix.auth.service.http rename to src/services/core/mix-auth-service/mix.auth.api/mix.auth.service.http diff --git a/src/services/mix-auth-service/mix.auth.api/runtimeconfig.template.json b/src/services/core/mix-auth-service/mix.auth.api/runtimeconfig.template.json similarity index 100% rename from src/services/mix-auth-service/mix.auth.api/runtimeconfig.template.json rename to src/services/core/mix-auth-service/mix.auth.api/runtimeconfig.template.json diff --git a/src/services/core/mix-databases/mix.services.databases.lib/Abstracts/MixPostService.cs b/src/services/core/mix-databases/mix.services.databases.lib/Abstracts/MixPostService.cs index 47c688d04..d467d2b0b 100644 --- a/src/services/core/mix-databases/mix.services.databases.lib/Abstracts/MixPostService.cs +++ b/src/services/core/mix-databases/mix.services.databases.lib/Abstracts/MixPostService.cs @@ -3,7 +3,6 @@ using Mix.Database.Entities.Cms; using Mix.Heart.Enums; using Mix.Heart.Exceptions; -using Mix.Heart.Extensions; using Mix.Heart.Models; using Mix.Heart.Repository; using Mix.Heart.Services; @@ -14,8 +13,6 @@ using Mix.Service.Services; using Mix.Services.Databases.Lib.Interfaces; using Mix.Shared.Dtos; -using RepoDb; -using System.Linq.Expressions; namespace Mix.Services.Databases.Lib.Abstracts { diff --git a/src/services/core/mix-databases/mix.services.databases.lib/Interfaces/IMixPermissionService.cs b/src/services/core/mix-databases/mix.services.databases.lib/Interfaces/IMixPermissionService.cs index 2c14bf6b6..67cf27421 100644 --- a/src/services/core/mix-databases/mix.services.databases.lib/Interfaces/IMixPermissionService.cs +++ b/src/services/core/mix-databases/mix.services.databases.lib/Interfaces/IMixPermissionService.cs @@ -1,4 +1,6 @@ -using Mix.Mixdb.ViewModels; +using Mix.Database.Entities.Account; +using Mix.Identity.Dtos; +using Mix.Mixdb.ViewModels; using Mix.Services.Databases.Lib.Dtos; namespace Mix.Services.Databases.Lib.Interfaces @@ -8,5 +10,7 @@ public interface IMixPermissionService public Task> GetPermissionAsync(Guid userId); public Task AddUserPermission(CreateUserPermissionDto dto); + Task> GetPermissionByRoleId(Guid roleId); + Task GrantPermissions(GrantPermissionsDto dto); } } diff --git a/src/services/core/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs b/src/services/core/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs index 60141376a..07387c977 100644 --- a/src/services/core/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs +++ b/src/services/core/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs @@ -1,23 +1,22 @@ using Microsoft.AspNetCore.Http; -using Mix.Database.Entities.Cms; +using Mix.Auth.Constants; +using Mix.Constant.Enums; +using Mix.Heart.Extensions; using Mix.Heart.Helpers; +using Mix.Heart.Models; +using Mix.Heart.Services; using Mix.Heart.UnitOfWork; +using Mix.Lib.Helpers; +using Mix.Lib.Interfaces; using Mix.Lib.Services; -using Mix.Services.Databases.Lib.Dtos; -using System.Linq.Expressions; -using Mix.Heart.Models; -using Mix.Shared.Models; -using Mix.Services.Databases.Lib.Models; -using Mix.Heart.Extensions; using Mix.Mixdb.ViewModels; -using Mix.Constant.Enums; using Mix.Service.Services; +using Mix.Services.Databases.Lib.Dtos; using Mix.Services.Databases.Lib.Interfaces; -using Mix.Heart.Services; +using Mix.Services.Databases.Lib.Models; using Mix.Shared.Dtos; -using Mix.Lib.Helpers; -using Mix.Lib.Interfaces; -using Mix.Auth.Constants; +using Mix.Shared.Models; +using System.Linq.Expressions; namespace Mix.Services.Databases.Lib.Services { diff --git a/src/services/core/mix-databases/mix.services.databases.lib/Services/MixUserDataService.cs b/src/services/core/mix-databases/mix.services.databases.lib/Services/MixUserDataService.cs index f8321388c..e3f567b89 100644 --- a/src/services/core/mix-databases/mix.services.databases.lib/Services/MixUserDataService.cs +++ b/src/services/core/mix-databases/mix.services.databases.lib/Services/MixUserDataService.cs @@ -1,17 +1,17 @@ using Microsoft.AspNetCore.Http; -using Mix.Mixdb.ViewModels; using Mix.Constant.Enums; using Mix.Database.Entities.Account; using Mix.Heart.Enums; using Mix.Heart.Exceptions; using Mix.Heart.Helpers; +using Mix.Heart.Services; using Mix.Heart.UnitOfWork; +using Mix.Lib.Interfaces; using Mix.Lib.Services; +using Mix.Mixdb.ViewModels; using Mix.Service.Services; using Mix.Services.Databases.Lib.Dtos; using Mix.Services.Databases.Lib.Interfaces; -using Mix.Heart.Services; -using Mix.Lib.Interfaces; namespace Mix.Services.Databases.Lib.Services { diff --git a/src/services/core/mix-databases/mix.services.databases.lib/Services/MixUserPermissionService.cs b/src/services/core/mix-databases/mix.services.databases.lib/Services/MixUserPermissionService.cs index 62f3d5c09..3fb0d103b 100644 --- a/src/services/core/mix-databases/mix.services.databases.lib/Services/MixUserPermissionService.cs +++ b/src/services/core/mix-databases/mix.services.databases.lib/Services/MixUserPermissionService.cs @@ -1,16 +1,21 @@ using Microsoft.AspNetCore.Http; -using Mix.Mixdb.ViewModels; +using Microsoft.EntityFrameworkCore; +using Mix.Auth.Constants; +using Mix.Constant.Constants; +using Mix.Database.Entities.Account; +using Mix.Heart.Enums; using Mix.Heart.Exceptions; using Mix.Heart.Helpers; +using Mix.Heart.Services; using Mix.Heart.UnitOfWork; +using Mix.Identity.Dtos; +using Mix.Lib.Interfaces; using Mix.Lib.Services; -using Mix.Services.Databases.Lib.Dtos; -using System.Linq.Expressions; +using Mix.Mixdb.ViewModels; using Mix.Service.Services; +using Mix.Services.Databases.Lib.Dtos; using Mix.Services.Databases.Lib.Interfaces; -using Mix.Heart.Services; -using Mix.Lib.Interfaces; -using Mix.Auth.Constants; +using System.Linq.Expressions; namespace Mix.Services.Databases.Lib.Services { @@ -18,26 +23,78 @@ public sealed class MixUserPermissionService : TenantServiceBase, IMixPermission { private readonly MixIdentityService _identityService; private readonly MixDbDbContext _permissionDbContext; - private readonly UnitOfWorkInfo _uow; - + private readonly UnitOfWorkInfo _accUow; + private readonly UnitOfWorkInfo _mixUow; + private readonly IQueryable _permissionQuery; public MixUserPermissionService( IHttpContextAccessor httpContextAccessor, - UnitOfWorkInfo uow, + UnitOfWorkInfo accUow, MixIdentityService identityService, MixCacheService cacheService, - IMixTenantService mixTenantService) + IMixTenantService mixTenantService, + UnitOfWorkInfo mixUow) : base(httpContextAccessor, cacheService, mixTenantService) { - _uow = uow; - _permissionDbContext = _uow.DbContext; + _accUow = accUow; + _mixUow = mixUow; + _permissionDbContext = mixUow.DbContext; _identityService = identityService; + _permissionQuery = _accUow.DbContext.SysMixDatabaseAssociation + .Where(m => m.ParentDatabaseName == MixDatabaseNames.ROLE + && m.ChildDatabaseName == MixDatabaseNames.SYSTEM_PERMISSION); + } + + public async Task> GetPermissionByRoleId(Guid roleId) + { + var permissionIds = _permissionQuery.Where(m => m.GuidParentId == roleId).Select(m => m.ChildId); + return await _accUow.DbContext.Permission.Where(m => permissionIds.Contains(m.Id)) + .ToListAsync(); } + public async Task GrantPermissions(GrantPermissionsDto dto) + { + foreach (var item in dto.Permissions) + { + if (dto.IsActive && _permissionQuery.Any(m => m.GuidParentId == item.RoleId && m.ChildId == item.PermissionId)) + { + continue; + } + + try + { + if (dto.IsActive) + { + _accUow.DbContext.SysMixDatabaseAssociation.Add(new SysMixDatabaseAssociation() + { + ParentDatabaseName = MixDatabaseNames.ROLE, + ChildDatabaseName = MixDatabaseNames.SYSTEM_PERMISSION, + GuidParentId = item.RoleId, + ChildId = item.PermissionId, + CreatedBy = dto.RequestedBy, + CreatedDateTime = DateTime.UtcNow + }); + } + else + { + var rel = _permissionQuery.FirstOrDefault(m => m.GuidParentId == item.RoleId && m.ChildId == item.PermissionId); + if (rel != null) + { + _accUow.DbContext.SysMixDatabaseAssociation.Remove(rel); + } + } + await _accUow.DbContext.SaveChangesAsync(); + } + catch (Exception ex) + { + throw new MixException(MixErrorStatus.ServerError, ex); + } + } + } public async Task> GetPermissionAsync(Guid userId) { var permissions = _permissionDbContext.UserPermission.Where(m => m.MixTenantId == CurrentTenant.Id && m.UserId == userId); Expression> predicate = m => m.MixTenantId == CurrentTenant.Id && permissions.Any(p => p.PermissionId == m.Id); - var result = await MixPermissionViewModel.GetRepository(_uow, CacheService).GetAllAsync(predicate); + var result = await MixPermissionViewModel.GetRepository(_accUow, CacheService).GetAllAsync(predicate); return result; } @@ -48,7 +105,7 @@ public async Task AddUserPermission(CreateUserPermissionDto dto) throw new MixException(Heart.Enums.MixErrorStatus.Badrequest, "User not exist"); } - MixUserPermissionViewModel userPermission = new(_uow) + MixUserPermissionViewModel userPermission = new(_accUow) { MixTenantId = CurrentTenant.Id, CreatedBy = _identityService.GetClaim(HttpContextAccessor.HttpContext!.User, MixClaims.Username) diff --git a/src/services/core/mix-databases/mix.servives.databases/Controllers/MixMetadataController.cs b/src/services/core/mix-databases/mix.servives.databases/Controllers/MixMetadataController.cs index cb0880a43..be894e08f 100644 --- a/src/services/core/mix-databases/mix.servives.databases/Controllers/MixMetadataController.cs +++ b/src/services/core/mix-databases/mix.servives.databases/Controllers/MixMetadataController.cs @@ -1,21 +1,18 @@ using Microsoft.AspNetCore.Mvc; +using Mix.Heart.Extensions; +using Mix.Heart.Services; using Mix.Heart.UnitOfWork; using Mix.Lib.Base; +using Mix.Lib.Interfaces; using Mix.Lib.Models.Common; using Mix.Lib.Services; +using Mix.Mixdb.ViewModels; +using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; -using Mix.Service.Services; using Mix.Services.Databases.Lib.Dtos; -using Mix.Shared.Dtos; -using Mix.Heart.Extensions; -using Mix.Mixdb.ViewModels; using Mix.Services.Databases.Lib.Interfaces; -using Mix.Heart.Services; -using Mix.Database.Entities.Cms; -using Mix.Database.Entities.MixDb; +using Mix.Shared.Dtos; using Mix.SignalR.Interfaces; -using Mix.Lib.Interfaces; -using Mix.Mq.Lib.Models; namespace Mix.Services.Databases.Controllers { @@ -35,7 +32,7 @@ public MixMetadataController( IMemoryQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { _metadataService = metadataService; diff --git a/src/services/core/mix-databases/mix.servives.databases/Controllers/MixPermissionController.cs b/src/services/core/mix-databases/mix.servives.databases/Controllers/MixPermissionController.cs index cba8a9421..842d88c45 100644 --- a/src/services/core/mix-databases/mix.servives.databases/Controllers/MixPermissionController.cs +++ b/src/services/core/mix-databases/mix.servives.databases/Controllers/MixPermissionController.cs @@ -1,20 +1,18 @@ using Microsoft.AspNetCore.Mvc; +using Mix.Auth.Constants; +using Mix.Heart.Services; using Mix.Heart.UnitOfWork; +using Mix.Identity.Dtos; using Mix.Lib.Attributes; using Mix.Lib.Base; +using Mix.Lib.Interfaces; using Mix.Lib.Services; +using Mix.Mixdb.ViewModels; +using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; -using Mix.Service.Services; using Mix.Services.Databases.Lib.Dtos; -using Mix.Mixdb.ViewModels; using Mix.Services.Databases.Lib.Interfaces; -using Mix.Heart.Services; -using Mix.Database.Entities.Cms; -using Mix.Database.Entities.MixDb; using Mix.SignalR.Interfaces; -using Mix.Lib.Interfaces; -using Mix.Auth.Constants; -using Mix.Mq.Lib.Models; namespace Mix.Services.Databases.Controllers { @@ -59,6 +57,7 @@ public async Task AddUserPermission(CreateUserPermissionDto dto) return Ok(); } + [MixAuthorize] [HttpGet("get-my-permissions")] public async Task>> GetMyPermissions() { @@ -71,7 +70,15 @@ public async Task>> GetMyPermissions() return BadRequest(); } - + [MixAuthorize(roles: $"{MixRoles.Owner},{MixRoles.Administrators}")] + [Route("grant-permission")] + [HttpPost] + public async Task GrantPermission([FromBody] GrantPermissionsDto dto) + { + dto.RequestedBy = MixIdentityService.GetClaim(User, MixClaims.Username); + await _permissionService.GrantPermissions(dto); + return Ok(); + } #endregion #region Overrides diff --git a/src/services/core/mix-databases/mix.servives.databases/Controllers/MixUserDataController.cs b/src/services/core/mix-databases/mix.servives.databases/Controllers/MixUserDataController.cs index d03c42afe..0f3aeea9c 100644 --- a/src/services/core/mix-databases/mix.servives.databases/Controllers/MixUserDataController.cs +++ b/src/services/core/mix-databases/mix.servives.databases/Controllers/MixUserDataController.cs @@ -1,20 +1,16 @@ using Microsoft.AspNetCore.Mvc; -using Mix.Mixdb.ViewModels; +using Mix.Heart.Services; using Mix.Heart.UnitOfWork; using Mix.Lib.Attributes; using Mix.Lib.Base; +using Mix.Lib.Interfaces; using Mix.Lib.Services; +using Mix.Mixdb.ViewModels; +using Mix.Mq.Lib.Models; using Mix.Queue.Interfaces; -using Mix.Service.Services; using Mix.Services.Databases.Lib.Dtos; using Mix.Services.Databases.Lib.Interfaces; -using Mix.Heart.Services; -using Mix.Database.Entities.Cms; -using Mix.Database.Entities.MixDb; using Mix.SignalR.Interfaces; -using Mix.Lib.Interfaces; -using static System.Runtime.InteropServices.JavaScript.JSType; -using Mix.Mq.Lib.Models; namespace Mix.Services.Databases.Controllers { diff --git a/src/services/mix-message-queue/mix.mq.lib/mix.mq.lib.csproj b/src/services/core/mix-message-queue/mix.mq.lib/mix.mq.lib.csproj similarity index 100% rename from src/services/mix-message-queue/mix.mq.lib/mix.mq.lib.csproj rename to src/services/core/mix-message-queue/mix.mq.lib/mix.mq.lib.csproj diff --git a/src/services/mix-message-queue/mix.mq.server/Controllers/MqController.cs b/src/services/core/mix-message-queue/mix.mq.server/Controllers/MqController.cs similarity index 93% rename from src/services/mix-message-queue/mix.mq.server/Controllers/MqController.cs rename to src/services/core/mix-message-queue/mix.mq.server/Controllers/MqController.cs index 6dccb563a..540a1a2a2 100644 --- a/src/services/mix-message-queue/mix.mq.server/Controllers/MqController.cs +++ b/src/services/core/mix-message-queue/mix.mq.server/Controllers/MqController.cs @@ -1,9 +1,6 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Mix.Mq.Lib.Models; using Mix.Mq.Server.Domain.Services; -using Newtonsoft.Json.Linq; -using System.Text.Json; namespace Mix.Mq.Server.Controllers { diff --git a/src/services/mix-message-queue/mix.mq.server/Dockerfile b/src/services/core/mix-message-queue/mix.mq.server/Dockerfile similarity index 82% rename from src/services/mix-message-queue/mix.mq.server/Dockerfile rename to src/services/core/mix-message-queue/mix.mq.server/Dockerfile index ed931e7e6..a41acfa3a 100644 --- a/src/services/mix-message-queue/mix.mq.server/Dockerfile +++ b/src/services/core/mix-message-queue/mix.mq.server/Dockerfile @@ -10,8 +10,8 @@ FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build ARG BUILD_CONFIGURATION=Release WORKDIR /src COPY ["platform/core/mix-heart/nuget.config", "platform/core/mix-heart/"] -COPY ["services/mix-message-queue/mix.mq.server/mix.mq.server.csproj", "services/mix-message-queue/mix.mq.server/"] -COPY ["applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/"] +COPY ["services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj", "services/core/mix-message-queue/mix.mq.server/"] +COPY ["applications/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "applications/mixcore.host.aspire.ServiceDefaults/"] COPY ["modules/mix.messenger/mix.messenger.csproj", "modules/mix.messenger/"] COPY ["platform/mix.signalr.hub/mix.signalr.hub.csproj", "platform/mix.signalr.hub/"] COPY ["platform/core/mix-heart/src/mix.heart/mix.heart.csproj", "platform/core/mix-heart/src/mix.heart/"] @@ -30,9 +30,9 @@ COPY ["platform/mix.library/mix.library.csproj", "platform/mix.library/"] COPY ["platform/core/mix.mixdb.event/mix.mixdb.event.csproj", "platform/core/mix.mixdb.event/"] COPY ["platform/mix.mixdb/mix.mixdb.csproj", "platform/mix.mixdb/"] COPY ["platform/mix.repodb/mix.repodb.csproj", "platform/mix.repodb/"] -RUN dotnet restore "./services/mix-message-queue/mix.mq.server/mix.mq.server.csproj" +RUN dotnet restore "./services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj" COPY . . -WORKDIR "/src/services/mix-message-queue/mix.mq.server" +WORKDIR "/src/services/core/mix-message-queue/mix.mq.server" RUN dotnet build "./mix.mq.server.csproj" -c $BUILD_CONFIGURATION -o /app/build FROM build AS publish diff --git a/src/services/mix-message-queue/mix.mq.server/Dockerfile_linux b/src/services/core/mix-message-queue/mix.mq.server/Dockerfile_linux similarity index 75% rename from src/services/mix-message-queue/mix.mq.server/Dockerfile_linux rename to src/services/core/mix-message-queue/mix.mq.server/Dockerfile_linux index 73c82910b..fc451bb5d 100644 --- a/src/services/mix-message-queue/mix.mq.server/Dockerfile_linux +++ b/src/services/core/mix-message-queue/mix.mq.server/Dockerfile_linux @@ -8,8 +8,8 @@ EXPOSE 8081 FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build ARG BUILD_CONFIGURATION=Release COPY ["src/platform/core/mix-heart/nuget.config", "src/platform/core/mix-heart/"] -COPY ["src/services/mix-message-queue/mix.mq.server/mix.mq.server.csproj", "src/services/mix-message-queue/mix.mq.server/"] -COPY ["src/applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "src/applications/mixcore.host.aspire/mixcore.host.aspire.ServiceDefaults/"] +COPY ["src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj", "src/services/core/mix-message-queue/mix.mq.server/"] +COPY ["src/applications/mixcore.host.aspire.ServiceDefaults/mixcore.host.aspire.ServiceDefaults.csproj", "applications/mixcore.host.aspire.ServiceDefaults/"] COPY ["src/modules/mix.messenger/mix.messenger.csproj", "src/modules/mix.messenger/"] COPY ["src/platform/mix.signalr.hub/mix.signalr.hub.csproj", "src/platform/mix.signalr.hub/"] COPY ["src/platform/core/mix-heart/src/mix.heart/mix.heart.csproj", "src/platform/core/mix-heart/src/mix.heart/"] @@ -28,13 +28,13 @@ COPY ["src/platform/mix.library/mix.library.csproj", "src/platform/mix.library/" COPY ["src/platform/core/mix.mixdb.event/mix.mixdb.event.csproj", "src/platform/core/mix.mixdb.event/"] COPY ["src/platform/mix.mixdb/mix.mixdb.csproj", "src/platform/mix.mixdb/"] COPY ["src/platform/mix.repodb/mix.repodb.csproj", "src/platform/mix.repodb/"] -RUN dotnet restore "src/services/mix-message-queue/mix.mq.server/mix.mq.server.csproj" +RUN dotnet restore "src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj" COPY . . -RUN dotnet build "/src/services/mix-message-queue/mix.mq.server/mix.mq.server.csproj" -c $BUILD_CONFIGURATION -o /app/build +RUN dotnet build "/src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj" -c $BUILD_CONFIGURATION -o /app/build FROM build AS publish ARG BUILD_CONFIGURATION=Release -RUN dotnet publish "/src/services/mix-message-queue/mix.mq.server/mix.mq.server.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false +RUN dotnet publish "/src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false FROM base AS final COPY --from=publish /app/publish . diff --git a/src/services/mix-message-queue/mix.mq.server/Domain/Protos/mixmq.proto b/src/services/core/mix-message-queue/mix.mq.server/Domain/Protos/mixmq.proto similarity index 100% rename from src/services/mix-message-queue/mix.mq.server/Domain/Protos/mixmq.proto rename to src/services/core/mix-message-queue/mix.mq.server/Domain/Protos/mixmq.proto diff --git a/src/services/mix-message-queue/mix.mq.server/Domain/Services/GrpcStreamingService.cs b/src/services/core/mix-message-queue/mix.mq.server/Domain/Services/GrpcStreamingService.cs similarity index 95% rename from src/services/mix-message-queue/mix.mq.server/Domain/Services/GrpcStreamingService.cs rename to src/services/core/mix-message-queue/mix.mq.server/Domain/Services/GrpcStreamingService.cs index a8c25245f..e45cd7e97 100644 --- a/src/services/mix-message-queue/mix.mq.server/Domain/Services/GrpcStreamingService.cs +++ b/src/services/core/mix-message-queue/mix.mq.server/Domain/Services/GrpcStreamingService.cs @@ -2,8 +2,6 @@ using Mix.Mq.Lib.Models; using Newtonsoft.Json.Linq; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; namespace Mix.Mq.Server.Domain.Services { @@ -54,7 +52,7 @@ private async Task CreateSubscription(SubscribeRequest request, IServerStreamWri var _topic = _queue.GetTopic(request.TopicId); Initialize(_topic, request.SubsctiptionId); - while (!_cancellationToken.IsCancellationRequested) + while (true) { var inQueueItems = _topic.ConsumeQueue(request.SubsctiptionId, 10); try @@ -79,19 +77,20 @@ private async Task CreateSubscription(SubscribeRequest request, IServerStreamWri { _logger.LogError($"RpcException at{DateTime.UtcNow.AddHours(7)} - {GetType().Name} Cannot write stream message to {request.SubsctiptionId}: {ex.Message}", ex); AddToPendingMessages(request.SubsctiptionId, inQueueItems.ToList()); - await RemoveSubscription(request); + //await RemoveSubscription(request); break; } catch (Exception ex) { _logger.LogError($"Exception at{DateTime.UtcNow.AddHours(7)} - {GetType().Name} Cannot write stream message to {request.SubsctiptionId}: {ex.Message}", ex); AddToPendingMessages(request.SubsctiptionId, inQueueItems.ToList()); - await RemoveSubscription(request); + //await RemoveSubscription(request); break; } - await Task.Delay(1000, _cancellationToken); + await Task.Delay(1000); } + _logger.LogInformation($"{request.SubsctiptionId} stopped at {DateTime.UtcNow.AddHours(7)}"); } private async Task SendPendingMessages(SubscribeRequest request, IServerStreamWriter responseStream) diff --git a/src/services/mix-message-queue/mix.mq.server/Domain/Services/MixMqService.cs b/src/services/core/mix-message-queue/mix.mq.server/Domain/Services/MixMqService.cs similarity index 79% rename from src/services/mix-message-queue/mix.mq.server/Domain/Services/MixMqService.cs rename to src/services/core/mix-message-queue/mix.mq.server/Domain/Services/MixMqService.cs index ce9075e6d..18485b924 100644 --- a/src/services/mix-message-queue/mix.mq.server/Domain/Services/MixMqService.cs +++ b/src/services/core/mix-message-queue/mix.mq.server/Domain/Services/MixMqService.cs @@ -1,14 +1,8 @@ -using Azure.Core; -using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using Mix.Heart.Extensions; using Mix.Mq.Lib.Models; -using Mix.Signalr.Hub.Models; using Newtonsoft.Json.Linq; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; namespace Mix.Mq.Server.Domain.Services; @@ -24,18 +18,17 @@ public MixMqService(ILogger logger, MixQueueMessages responseStream, ServerCallContext context) + public override Task Subscribe(SubscribeRequest request, IServerStreamWriter responseStream, ServerCallContext context) { try { _logger.LogInformation($"{request.SubsctiptionId} started at {DateTime.UtcNow.AddHours(7)}"); - await _subscriptionService.AddSubscription(request, responseStream); - await Task.Delay(100, context.CancellationToken); + return _subscriptionService.AddSubscription(request, responseStream); } catch (Exception e) { _logger.LogError($"{request.SubsctiptionId} broken at {DateTime.UtcNow.AddHours(7)}: {e.Message}", e); - await _subscriptionService.RemoveSubscription(request); + return _subscriptionService.RemoveSubscription(request); } } diff --git a/src/services/mix-message-queue/mix.mq.server/Domain/Services/MixMqSubscriptionService.cs b/src/services/core/mix-message-queue/mix.mq.server/Domain/Services/MixMqSubscriptionService.cs similarity index 78% rename from src/services/mix-message-queue/mix.mq.server/Domain/Services/MixMqSubscriptionService.cs rename to src/services/core/mix-message-queue/mix.mq.server/Domain/Services/MixMqSubscriptionService.cs index 0385c67a9..3c229f91c 100644 --- a/src/services/mix-message-queue/mix.mq.server/Domain/Services/MixMqSubscriptionService.cs +++ b/src/services/core/mix-message-queue/mix.mq.server/Domain/Services/MixMqSubscriptionService.cs @@ -1,11 +1,4 @@ -using Azure.Messaging.ServiceBus.Administration; -using Grpc.Core; -using Mix.Mq.Lib.Models; -using Newtonsoft.Json.Linq; -using System.Collections.Concurrent; -using System.Threading; - -namespace Mix.Mq.Server.Domain.Services +namespace Mix.Mq.Server.Domain.Services { public sealed class MixMqSubscriptionService : IHostedService { @@ -28,6 +21,6 @@ public Task StopAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - + } } diff --git a/src/services/mix-message-queue/mix.mq.server/Domain/StartupService.cs b/src/services/core/mix-message-queue/mix.mq.server/Domain/StartupService.cs similarity index 79% rename from src/services/mix-message-queue/mix.mq.server/Domain/StartupService.cs rename to src/services/core/mix-message-queue/mix.mq.server/Domain/StartupService.cs index 45c8862c5..dda72c0e9 100644 --- a/src/services/mix-message-queue/mix.mq.server/Domain/StartupService.cs +++ b/src/services/core/mix-message-queue/mix.mq.server/Domain/StartupService.cs @@ -1,8 +1,4 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.DependencyInjection.Extensions; using Mix.Mq.Lib.Models; using Mix.Mq.Server.Domain.Services; using Mix.Shared.Interfaces; @@ -13,7 +9,6 @@ public class StartupService : IStartupService { public void AddServices(IServiceCollection services, IConfiguration configuration) { - services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton>(); services.AddGrpc(); diff --git a/src/services/mix-message-queue/mix.mq.server/Program.cs b/src/services/core/mix-message-queue/mix.mq.server/Program.cs similarity index 77% rename from src/services/mix-message-queue/mix.mq.server/Program.cs rename to src/services/core/mix-message-queue/mix.mq.server/Program.cs index 55e605e13..be255d56f 100644 --- a/src/services/mix-message-queue/mix.mq.server/Program.cs +++ b/src/services/core/mix-message-queue/mix.mq.server/Program.cs @@ -1,18 +1,20 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Mix.Constant.Constants; +using Mix.Database.Entities.Account; +using Mix.Database.Entities.Cms; using Mix.Heart.Services; using Mix.Lib.Helpers; using Mix.Log.Lib; using Mix.Mq.Lib.Models; using Mix.Mq.Server.Domain.Services; -using OpenTelemetry; -using System.Configuration; -using System.Reflection; using Mix.Queue.Extensions; +using Mix.Service.Interfaces; +using Mix.Service.Services; +using System.Reflection; -if (Directory.Exists($"../{MixFolders.MixCoreConfigurationFolder}")) +if (Directory.Exists($"../../{MixFolders.MixCoreConfigurationFolder}")) { - MixFileHelper.CopyFolder($"../{MixFolders.MixCoreConfigurationFolder}", MixFolders.MixContentSharedFolder); + MixFileHelper.CopyFolder($"../../{MixFolders.MixCoreConfigurationFolder}", MixFolders.MixContentSharedFolder); } @@ -52,7 +54,10 @@ builder.Services.AddMixSignalR(builder.Configuration); builder.Services.AddMixCommunicators(); builder.Services.AddSwaggerGen(); - +builder.Services.TryAddSingleton(); +builder.Services.AddDbContext(); +builder.Services.AddDbContext(); +builder.Services.AddMixIdentityConfigurations(builder.Configuration); var app = builder.Build(); if (app.Environment.IsDevelopment()) @@ -65,6 +70,7 @@ app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true }); app.UseRouting(); app.UseMixCors(); +app.UseMixAuth(); app.UseEndpoints(endpoints => { endpoints.MapGrpcService().EnableGrpcWeb() diff --git a/src/services/mix-message-queue/mix.mq.server/Properties/launchSettings.json b/src/services/core/mix-message-queue/mix.mq.server/Properties/launchSettings.json similarity index 100% rename from src/services/mix-message-queue/mix.mq.server/Properties/launchSettings.json rename to src/services/core/mix-message-queue/mix.mq.server/Properties/launchSettings.json diff --git a/src/services/mix-message-queue/mix.mq.server/Readme.md b/src/services/core/mix-message-queue/mix.mq.server/Readme.md similarity index 100% rename from src/services/mix-message-queue/mix.mq.server/Readme.md rename to src/services/core/mix-message-queue/mix.mq.server/Readme.md diff --git a/src/services/mix-message-queue/mix.mq.server/appsettings.Development.json b/src/services/core/mix-message-queue/mix.mq.server/appsettings.Development.json similarity index 100% rename from src/services/mix-message-queue/mix.mq.server/appsettings.Development.json rename to src/services/core/mix-message-queue/mix.mq.server/appsettings.Development.json diff --git a/src/services/mix-message-queue/mix.mq.server/mix.mq.server.csproj b/src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj similarity index 64% rename from src/services/mix-message-queue/mix.mq.server/mix.mq.server.csproj rename to src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj index c1b21c814..de4969ab8 100644 --- a/src/services/mix-message-queue/mix.mq.server/mix.mq.server.csproj +++ b/src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.csproj @@ -18,15 +18,15 @@ - - - - - + + + + + - - + + diff --git a/src/services/mix-message-queue/mix.mq.server/mix.mq.server.http b/src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.http similarity index 100% rename from src/services/mix-message-queue/mix.mq.server/mix.mq.server.http rename to src/services/core/mix-message-queue/mix.mq.server/mix.mq.server.http diff --git a/src/services/core/mix-message-queue/mix.mq.server/runtimeconfig.template.json b/src/services/core/mix-message-queue/mix.mq.server/runtimeconfig.template.json new file mode 100644 index 000000000..cbbea1422 --- /dev/null +++ b/src/services/core/mix-message-queue/mix.mq.server/runtimeconfig.template.json @@ -0,0 +1,12 @@ +{ + "configProperties": { + "System.GC.RetainVM": false, + "System.GC.NoAffinitize": false, + "System.GC.ConserveMemory": 5, + "System.GC.Server": false, + "System.GC.Concurrent": true, + "System.GC.HeapCount": 12, + "System.Threading.Thread.EnableAutoreleasePool": true + } + } + \ No newline at end of file diff --git a/src/services/mix-auth-service/mix.auth.api/mix.auth.api.http b/src/services/mix-auth-service/mix.auth.api/mix.auth.api.http deleted file mode 100644 index b9409b140..000000000 --- a/src/services/mix-auth-service/mix.auth.api/mix.auth.api.http +++ /dev/null @@ -1,6 +0,0 @@ -@mix.auth.service_HostAddress = http://localhost:5238 - -GET {{mix.auth.service_HostAddress}}/weatherforecast/ -Accept: application/json - -###