Browse Source

Updated to file scoped namespaces

pull/89/head
Galip Tolga Erdem 5 years ago
parent
commit
52f8b9a137
  1. 3
      services/administration/src/EShopOnAbp.AdministrationService.HttpApi.Host/AdministrationServiceHttpApiHostModule.cs
  2. 13
      services/administration/src/EShopOnAbp.AdministrationService.HttpApi.Host/Controllers/HomeController.cs
  3. 33
      services/administration/src/EShopOnAbp.AdministrationService.HttpApi.Host/DbMigrations/AdministrationServiceDatabaseMigrationChecker.cs
  4. 121
      services/administration/src/EShopOnAbp.AdministrationService.HttpApi.Host/DbMigrations/AdministrationServiceDatabaseMigrationEventHandler.cs
  5. 273
      services/basket/src/EShopOnAbp.BasketService/BasketServiceModule.cs
  6. 13
      services/catalog/src/EShopOnAbp.CatalogService.HttpApi.Host/Controllers/HomeController.cs
  7. 49
      services/catalog/src/EShopOnAbp.CatalogService.HttpApi.Host/DbMigrations/CatalogServiceDatabaseMigrationChecker.cs
  8. 83
      services/catalog/src/EShopOnAbp.CatalogService.HttpApi.Host/DbMigrations/CatalogServiceDatabaseMigrationEventHandler.cs
  9. 172
      services/catalog/src/EShopOnAbp.CatalogService.HttpApi.Host/DbMigrations/ProductServiceDataSeeder.cs
  10. 13
      services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/Controllers/HomeController.cs
  11. 11
      services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/DbMigrations/ApplyDatabaseSeedsEto.cs
  12. 28
      services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/DbMigrations/DataSeederEventHandler.cs
  13. 625
      services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/DbMigrations/IdentityServerDataSeeder.cs
  14. 53
      services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/DbMigrations/IdentityServiceDatabaseMigrationChecker.cs
  15. 122
      services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/DbMigrations/IdentityServiceDatabaseMigrationEventHandler.cs
  16. 13
      services/ordering/src/EShopOnAbp.OrderingService.HttpApi.Host/Controllers/HomeController.cs
  17. 33
      services/ordering/src/EShopOnAbp.OrderingService.HttpApi.Host/DbMigrations/OrderingServiceDatabaseMigrationChecker.cs
  18. 89
      services/ordering/src/EShopOnAbp.OrderingService.HttpApi.Host/DbMigrations/OrderingServiceDatabaseMigrationEventHandler.cs
  19. 1
      services/ordering/src/EShopOnAbp.OrderingService.HttpApi.Host/OrderingServiceHttpApiHostModule.cs
  20. 13
      services/payment/src/EShopOnAbp.PaymentService.HttpApi.Host/Controllers/HomeController.cs
  21. 33
      services/payment/src/EShopOnAbp.PaymentService.HttpApi.Host/DbMigrations/PaymentServiceDatabaseMigrationChecker.cs
  22. 79
      services/payment/src/EShopOnAbp.PaymentService.HttpApi.Host/DbMigrations/PaymentServiceDatabaseMigrationEventHandler.cs
  23. 19
      shared/EShopOnAbp.Shared.Hosting.AspNetCore/EShopOnAbpSharedHostingAspNetCoreModule.cs
  24. 55
      shared/EShopOnAbp.Shared.Hosting.AspNetCore/SerilogConfigurationHelper.cs
  25. 55
      shared/EShopOnAbp.Shared.Hosting.AspNetCore/SwaggerConfigurationHelper.cs
  26. 7
      shared/EShopOnAbp.Shared.Hosting.Microservices/DbMigrations/EfCore/DatabaseEfCoreMigrationEventHandler.cs
  27. 7
      shared/EShopOnAbp.Shared.Hosting.Microservices/DbMigrations/PendingMigrationsCheckerBase.cs
  28. 61
      shared/EShopOnAbp.Shared.Hosting.Microservices/EShopOnAbpSharedHostingMicroservicesModule.cs
  29. 29
      shared/EShopOnAbp.Shared.Hosting.Microservices/JwtBearerConfigurationHelper.cs
  30. 39
      shared/EShopOnAbp.Shared.Localization/EShopOnAbpSharedLocalizationModule.cs

3
services/administration/src/EShopOnAbp.AdministrationService.HttpApi.Host/AdministrationServiceHttpApiHostModule.cs

@ -2,14 +2,11 @@ using EShopOnAbp.AdministrationService.DbMigrations;
using EShopOnAbp.AdministrationService.EntityFrameworkCore;
using EShopOnAbp.Shared.Hosting.AspNetCore;
using EShopOnAbp.Shared.Hosting.Microservices;
using Medallion.Threading;
using Medallion.Threading.Redis;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;

13
services/administration/src/EShopOnAbp.AdministrationService.HttpApi.Host/Controllers/HomeController.cs

@ -1,13 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
namespace EShopOnAbp.AdministrationService.Controllers
namespace EShopOnAbp.AdministrationService.Controllers;
public class HomeController : AbpController
{
public class HomeController : AbpController
public ActionResult Index()
{
public ActionResult Index()
{
return Redirect("~/swagger");
}
return Redirect("~/swagger");
}
}
}

33
services/administration/src/EShopOnAbp.AdministrationService.HttpApi.Host/DbMigrations/AdministrationServiceDatabaseMigrationChecker.cs

@ -5,23 +5,22 @@ using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
namespace EShopOnAbp.AdministrationService.DbMigrations
namespace EShopOnAbp.AdministrationService.DbMigrations;
public class AdministrationServiceDatabaseMigrationChecker
: PendingEfCoreMigrationsChecker<AdministrationServiceDbContext>
{
public class AdministrationServiceDatabaseMigrationChecker : PendingEfCoreMigrationsChecker<AdministrationServiceDbContext>
public AdministrationServiceDatabaseMigrationChecker(
IUnitOfWorkManager unitOfWorkManager,
IServiceProvider serviceProvider,
ICurrentTenant currentTenant,
IDistributedEventBus distributedEventBus)
: base(
unitOfWorkManager,
serviceProvider,
currentTenant,
distributedEventBus,
AdministrationServiceDbProperties.ConnectionStringName)
{
public AdministrationServiceDatabaseMigrationChecker(
IUnitOfWorkManager unitOfWorkManager,
IServiceProvider serviceProvider,
ICurrentTenant currentTenant,
IDistributedEventBus distributedEventBus)
: base(
unitOfWorkManager,
serviceProvider,
currentTenant,
distributedEventBus,
AdministrationServiceDbProperties.ConnectionStringName)
{
}
}
}
}

121
services/administration/src/EShopOnAbp.AdministrationService.HttpApi.Host/DbMigrations/AdministrationServiceDatabaseMigrationEventHandler.cs

@ -12,86 +12,83 @@ using Volo.Abp.MultiTenancy;
using Volo.Abp.PermissionManagement;
using Volo.Abp.Uow;
namespace EShopOnAbp.AdministrationService.DbMigrations
namespace EShopOnAbp.AdministrationService.DbMigrations;
public class AdministrationServiceDatabaseMigrationEventHandler
: DatabaseEfCoreMigrationEventHandler<AdministrationServiceDbContext>,
IDistributedEventHandler<ApplyDatabaseMigrationsEto>
{
public class AdministrationServiceDatabaseMigrationEventHandler
: DatabaseEfCoreMigrationEventHandler<AdministrationServiceDbContext>,
IDistributedEventHandler<ApplyDatabaseMigrationsEto>
private readonly IPermissionDefinitionManager _permissionDefinitionManager;
private readonly IPermissionDataSeeder _permissionDataSeeder;
public AdministrationServiceDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IPermissionDefinitionManager permissionDefinitionManager,
IPermissionDataSeeder permissionDataSeeder,
IDistributedEventBus distributedEventBus,
IAbpDistributedLock distributedLockProvider
) : base(
currentTenant,
unitOfWorkManager,
tenantStore,
distributedEventBus,
AdministrationServiceDbProperties.ConnectionStringName,
distributedLockProvider
)
{
private readonly IPermissionDefinitionManager _permissionDefinitionManager;
private readonly IPermissionDataSeeder _permissionDataSeeder;
_permissionDefinitionManager = permissionDefinitionManager;
_permissionDataSeeder = permissionDataSeeder;
}
public AdministrationServiceDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IPermissionDefinitionManager permissionDefinitionManager,
IPermissionDataSeeder permissionDataSeeder,
IDistributedEventBus distributedEventBus,
IAbpDistributedLock distributedLockProvider
) : base(
currentTenant,
unitOfWorkManager,
tenantStore,
distributedEventBus,
AdministrationServiceDbProperties.ConnectionStringName,
distributedLockProvider
)
public async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData)
{
if (eventData.DatabaseName != DatabaseName)
{
_permissionDefinitionManager = permissionDefinitionManager;
_permissionDataSeeder = permissionDataSeeder;
return;
}
public async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData)
try
{
if (eventData.DatabaseName != DatabaseName)
await using (var handle = await DistributedLockProvider.TryAcquireAsync(DatabaseName))
{
return;
}
Log.Information("AdministrationService acquired lock for db migration and seeding...");
try
{
await using (var handle = await DistributedLockProvider.TryAcquireAsync(DatabaseName))
if (handle != null)
{
Log.Information("AdministrationService acquired lock for db migration and seeding...");
if (handle != null)
{
await MigrateDatabaseSchemaAsync();
await SeedDataAsync();
}
await MigrateDatabaseSchemaAsync();
await SeedDataAsync();
}
}
catch (Exception ex)
{
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex);
}
}
private async Task SeedDataAsync()
catch (Exception ex)
{
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex);
}
}
using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: true))
{
var multiTenancySide = MultiTenancySides.Host;
var permissionNames = _permissionDefinitionManager
.GetPermissions()
.Where(p => p.MultiTenancySide.HasFlag(multiTenancySide))
.Where(p => !p.Providers.Any() ||
p.Providers.Contains(RolePermissionValueProvider.ProviderName))
.Select(p => p.Name)
.ToArray();
private async Task SeedDataAsync()
{
using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: true))
{
var multiTenancySide = MultiTenancySides.Host;
await _permissionDataSeeder.SeedAsync(
RolePermissionValueProvider.ProviderName,
"admin",
permissionNames
);
var permissionNames = _permissionDefinitionManager
.GetPermissions()
.Where(p => p.MultiTenancySide.HasFlag(multiTenancySide))
.Where(p => !p.Providers.Any() ||
p.Providers.Contains(RolePermissionValueProvider.ProviderName))
.Select(p => p.Name)
.ToArray();
await uow.CompleteAsync();
}
await _permissionDataSeeder.SeedAsync(
RolePermissionValueProvider.ProviderName,
"admin",
permissionNames
);
await uow.CompleteAsync();
}
}
}

273
services/basket/src/EShopOnAbp.BasketService/BasketServiceModule.cs

@ -16,175 +16,174 @@ using Volo.Abp.Http.Client;
using Volo.Abp.Modularity;
using Volo.Abp.VirtualFileSystem;
namespace EShopOnAbp.BasketService
namespace EShopOnAbp.BasketService;
[DependsOn(
typeof(AbpAspNetCoreMvcModule),
typeof(AbpHttpClientModule),
typeof(AbpAutoMapperModule),
typeof(AbpCachingModule),
typeof(AbpDddApplicationModule),
typeof(AbpDddDomainModule),
typeof(BasketServiceContractsModule),
typeof(EShopOnAbpSharedHostingMicroservicesModule)
)]
public class BasketServiceModule : AbpModule
{
[DependsOn(
typeof(AbpAspNetCoreMvcModule),
typeof(AbpHttpClientModule),
typeof(AbpAutoMapperModule),
typeof(AbpCachingModule),
typeof(AbpDddApplicationModule),
typeof(AbpDddDomainModule),
typeof(BasketServiceContractsModule),
typeof(EShopOnAbpSharedHostingMicroservicesModule)
)]
public class BasketServiceModule : AbpModule
public override void ConfigureServices(ServiceConfigurationContext context)
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
var hostingEnvironment = context.Services.GetHostingEnvironment();
var hostingEnvironment = context.Services.GetHostingEnvironment();
Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = hostingEnvironment.IsDevelopment();
Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = hostingEnvironment.IsDevelopment();
var configuration = context.Services.GetConfiguration();
var configuration = context.Services.GetConfiguration();
ConfigureAutoMapper();
ConfigureAspNetCoreRouting(context);
ConfigureGrpc(context);
ConfigureDistributedCache();
ConfigureVirtualFileSystem();
ConfigureAuthentication(context, configuration);
ConfigureSwagger(context, configuration);
ConfigureAutoApiControllers();
}
ConfigureAutoMapper();
ConfigureAspNetCoreRouting(context);
ConfigureGrpc(context);
ConfigureDistributedCache();
ConfigureVirtualFileSystem();
ConfigureAuthentication(context, configuration);
ConfigureSwagger(context, configuration);
ConfigureAutoApiControllers();
}
private void ConfigureAspNetCoreRouting(ServiceConfigurationContext context)
private void ConfigureAspNetCoreRouting(ServiceConfigurationContext context)
{
Configure<AbpAspNetCoreMvcOptions>(options =>
{
Configure<AbpAspNetCoreMvcOptions>(options =>
options.ConventionalControllers.Create(typeof(BasketServiceModule).Assembly, opts =>
{
options.ConventionalControllers.Create(typeof(BasketServiceModule).Assembly, opts =>
{
opts.RootPath = "basket";
opts.RemoteServiceName = BasketServiceConstants.RemoteServiceName;
});
opts.RootPath = "basket";
opts.RemoteServiceName = BasketServiceConstants.RemoteServiceName;
});
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var app = context.GetApplicationBuilder();
var env = context.GetEnvironment();
});
}
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var app = context.GetApplicationBuilder();
var env = context.GetEnvironment();
app.UseCorrelationId();
app.UseCors();
app.UseAbpRequestLocalization();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAbpClaimsMap();
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
var configuration = context.ServiceProvider.GetRequiredService<IConfiguration>();
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Basket Service API");
options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
options.OAuthClientSecret(configuration["AuthServer:SwaggerClientSecret"]);
});
app.UseAbpSerilogEnrichers();
app.UseAuditing();
app.UseUnitOfWork();
app.UseConfiguredEndpoints();
}
private void ConfigureSwagger(ServiceConfigurationContext context, IConfiguration configuration)
if (env.IsDevelopment())
{
SwaggerConfigurationHelper.ConfigureWithAuth(
context: context,
authority: configuration["AuthServer:Authority"],
scopes: new
Dictionary<string, string> /* Requested scopes for authorization code request and descriptions for swagger UI only */
{
{"BasketService", "Basket Service API"}
},
apiTitle: "Basket Service API"
);
app.UseDeveloperExceptionPage();
}
private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
app.UseCorrelationId();
app.UseCors();
app.UseAbpRequestLocalization();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAbpClaimsMap();
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
JwtBearerConfigurationHelper.Configure(context, "BasketService");
var configuration = context.ServiceProvider.GetRequiredService<IConfiguration>();
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Basket Service API");
options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
options.OAuthClientSecret(configuration["AuthServer:SwaggerClientSecret"]);
});
app.UseAbpSerilogEnrichers();
app.UseAuditing();
app.UseUnitOfWork();
app.UseConfiguredEndpoints();
}
private void ConfigureSwagger(ServiceConfigurationContext context, IConfiguration configuration)
{
SwaggerConfigurationHelper.ConfigureWithAuth(
context: context,
authority: configuration["AuthServer:Authority"],
scopes: new
Dictionary<string, string> /* Requested scopes for authorization code request and descriptions for swagger UI only */
{
{"BasketService", "Basket Service API"}
},
apiTitle: "Basket Service API"
);
}
private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
{
JwtBearerConfigurationHelper.Configure(context, "BasketService");
context.Services.AddCors(options =>
context.Services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
options.AddDefaultPolicy(builder =>
{
builder
.WithOrigins(
configuration["App:CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.Trim().RemovePostFix("/"))
.ToArray()
)
.WithAbpExposedHeaders()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
builder
.WithOrigins(
configuration["App:CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.Trim().RemovePostFix("/"))
.ToArray()
)
.WithAbpExposedHeaders()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
Configure<AbpAntiForgeryOptions>(options => { options.AutoValidate = false; });
}
Configure<AbpAntiForgeryOptions>(options => { options.AutoValidate = false; });
}
private void ConfigureAutoApiControllers()
private void ConfigureAutoApiControllers()
{
Configure<AbpAspNetCoreMvcOptions>(options =>
{
Configure<AbpAspNetCoreMvcOptions>(options =>
{
options.ConventionalControllers.Create(typeof(BasketServiceModule).Assembly);
});
}
options.ConventionalControllers.Create(typeof(BasketServiceModule).Assembly);
});
}
private void ConfigureGrpc(ServiceConfigurationContext context)
private void ConfigureGrpc(ServiceConfigurationContext context)
{
context.Services.AddGrpcClient<ProductPublic.ProductPublicClient>((services, options) =>
{
context.Services.AddGrpcClient<ProductPublic.ProductPublicClient>((services, options) =>
{
var remoteServiceOptions = services.GetRequiredService<IOptionsMonitor<AbpRemoteServiceOptions>>().CurrentValue;
var catalogServiceConfiguration = remoteServiceOptions.RemoteServices.GetConfigurationOrDefault("Catalog");
var catalogGrpcUrl = catalogServiceConfiguration.GetOrDefault("GrpcUrl");
var remoteServiceOptions = services.GetRequiredService<IOptionsMonitor<AbpRemoteServiceOptions>>().CurrentValue;
var catalogServiceConfiguration = remoteServiceOptions.RemoteServices.GetConfigurationOrDefault("Catalog");
var catalogGrpcUrl = catalogServiceConfiguration.GetOrDefault("GrpcUrl");
options.Address = new Uri(catalogGrpcUrl);
});
}
options.Address = new Uri(catalogGrpcUrl);
});
}
private void ConfigureAutoMapper()
private void ConfigureAutoMapper()
{
Configure<AbpAutoMapperOptions>(options =>
{
Configure<AbpAutoMapperOptions>(options =>
{
options.AddMaps<BasketServiceModule>();
});
}
options.AddMaps<BasketServiceModule>();
});
}
private void ConfigureDistributedCache()
private void ConfigureDistributedCache()
{
Configure<AbpDistributedCacheOptions>(options =>
{
Configure<AbpDistributedCacheOptions>(options =>
options.CacheConfigurators.Add(cacheName =>
{
options.CacheConfigurators.Add(cacheName =>
if (cacheName == CacheNameAttribute.GetCacheName(typeof(Basket)))
{
if (cacheName == CacheNameAttribute.GetCacheName(typeof(Basket)))
return new DistributedCacheEntryOptions
{
return new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromDays(7)
};
}
SlidingExpiration = TimeSpan.FromDays(7)
};
}
return null;
});
return null;
});
}
});
}
private void ConfigureVirtualFileSystem()
private void ConfigureVirtualFileSystem()
{
Configure<AbpVirtualFileSystemOptions>(options =>
{
Configure<AbpVirtualFileSystemOptions>(options =>
{
options.FileSets.AddEmbedded<BasketServiceModule>();
});
}
options.FileSets.AddEmbedded<BasketServiceModule>();
});
}
}
}

13
services/catalog/src/EShopOnAbp.CatalogService.HttpApi.Host/Controllers/HomeController.cs

@ -1,13 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
namespace EShopOnAbp.CatalogService.Controllers
namespace EShopOnAbp.CatalogService.Controllers;
public class HomeController : AbpController
{
public class HomeController : AbpController
public ActionResult Index()
{
public ActionResult Index()
{
return Redirect("~/swagger");
}
return Redirect("~/swagger");
}
}
}

49
services/catalog/src/EShopOnAbp.CatalogService.HttpApi.Host/DbMigrations/CatalogServiceDatabaseMigrationChecker.cs

@ -6,32 +6,31 @@ using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
namespace EShopOnAbp.CatalogService.DbMigrations
namespace EShopOnAbp.CatalogService.DbMigrations;
public class CatalogServiceDatabaseMigrationChecker : PendingMongoDbMigrationsChecker<CatalogServiceMongoDbContext>
{
public class CatalogServiceDatabaseMigrationChecker : PendingMongoDbMigrationsChecker<CatalogServiceMongoDbContext>
{
private readonly ProductServiceDataSeeder _productServiceDataSeeder;
private readonly ProductServiceDataSeeder _productServiceDataSeeder;
public CatalogServiceDatabaseMigrationChecker(
IUnitOfWorkManager unitOfWorkManager,
IServiceProvider serviceProvider,
ICurrentTenant currentTenant,
IDistributedEventBus distributedEventBus,
ProductServiceDataSeeder productServiceDataSeeder)
: base(
unitOfWorkManager,
serviceProvider,
currentTenant,
distributedEventBus,
CatalogServiceDbProperties.ConnectionStringName)
{
_productServiceDataSeeder = productServiceDataSeeder;
}
public CatalogServiceDatabaseMigrationChecker(
IUnitOfWorkManager unitOfWorkManager,
IServiceProvider serviceProvider,
ICurrentTenant currentTenant,
IDistributedEventBus distributedEventBus,
ProductServiceDataSeeder productServiceDataSeeder)
: base(
unitOfWorkManager,
serviceProvider,
currentTenant,
distributedEventBus,
CatalogServiceDbProperties.ConnectionStringName)
{
_productServiceDataSeeder = productServiceDataSeeder;
}
public override async Task CheckAsync()
{
await base.CheckAsync();
await _productServiceDataSeeder.SeedAsync();
}
public override async Task CheckAsync()
{
await base.CheckAsync();
await _productServiceDataSeeder.SeedAsync();
}
}
}

83
services/catalog/src/EShopOnAbp.CatalogService.HttpApi.Host/DbMigrations/CatalogServiceDatabaseMigrationEventHandler.cs

@ -9,59 +9,58 @@ using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
namespace EShopOnAbp.CatalogService.DbMigrations
{
public class CatalogServiceDatabaseMigrationEventHandler
: DatabaseMongoDbMigrationEventHandler<CatalogServiceMongoDbContext>,
namespace EShopOnAbp.CatalogService.DbMigrations;
public class CatalogServiceDatabaseMigrationEventHandler
: DatabaseMongoDbMigrationEventHandler<CatalogServiceMongoDbContext>,
IDistributedEventHandler<ApplyDatabaseMigrationsEto>
{
public CatalogServiceDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IDistributedEventBus distributedEventBus,
IServiceProvider serviceProvider,
IAbpDistributedLock distributedLockProvider
) : base(
currentTenant,
unitOfWorkManager,
tenantStore,
distributedEventBus,
CatalogServiceDbProperties.ConnectionStringName,
serviceProvider,
distributedLockProvider)
{
public CatalogServiceDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IDistributedEventBus distributedEventBus,
IServiceProvider serviceProvider,
IAbpDistributedLock distributedLockProvider
) : base(
currentTenant,
unitOfWorkManager,
tenantStore,
distributedEventBus,
CatalogServiceDbProperties.ConnectionStringName,
serviceProvider,
distributedLockProvider)
}
public async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData)
{
if (eventData.DatabaseName != DatabaseName)
{
return;
}
public async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData)
if (eventData.TenantId != null)
{
if (eventData.DatabaseName != DatabaseName)
{
return;
}
return;
}
if (eventData.TenantId != null)
{
return;
}
try
{
Log.Information("CatalogService has acquired lock for db migration...");
try
await using (var handle = await DistributedLockProvider.TryAcquireAsync(DatabaseName))
{
Log.Information("CatalogService has acquired lock for db migration...");
await using (var handle = await DistributedLockProvider.TryAcquireAsync(DatabaseName))
if (handle != null)
{
if (handle != null)
{
Log.Information("CatalogService is migrating database...");
await MigrateDatabaseSchemaAsync();
}
Log.Information("CatalogService is migrating database...");
await MigrateDatabaseSchemaAsync();
}
}
catch (Exception ex)
{
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex);
}
}
catch (Exception ex)
{
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex);
}
}
}
}

172
services/catalog/src/EShopOnAbp.CatalogService.HttpApi.Host/DbMigrations/ProductServiceDataSeeder.cs

@ -1,110 +1,108 @@
using System;
using System.Threading.Tasks;
using EShopOnAbp.CatalogService.Products;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;
namespace EShopOnAbp.CatalogService.DbMigrations
namespace EShopOnAbp.CatalogService.DbMigrations;
public class ProductServiceDataSeeder : ITransientDependency
{
public class ProductServiceDataSeeder : ITransientDependency
private readonly ProductManager _productManager;
private readonly IRepository<Product, Guid> _productRepository;
public ProductServiceDataSeeder(
IRepository<Product, Guid> productRepository,
ProductManager productManager)
{
private readonly ProductManager _productManager;
private readonly IRepository<Product, Guid> _productRepository;
_productRepository = productRepository;
_productManager = productManager;
}
public ProductServiceDataSeeder(
IRepository<Product, Guid> productRepository,
ProductManager productManager)
{
_productRepository = productRepository;
_productManager = productManager;
}
[UnitOfWork]
public virtual async Task SeedAsync()
{
await AddProductsAsync();
}
[UnitOfWork]
public virtual async Task SeedAsync()
private async Task AddProductsAsync()
{
if (await _productRepository.GetCountAsync() > 0)
{
await AddProductsAsync();
return;
}
private async Task AddProductsAsync()
{
if (await _productRepository.GetCountAsync() > 0)
{
return;
}
await _productManager.CreateAsync(
"ABP04918",
"Lego Star Wars - 75059 Sandcrawler UCS",
999,
42,
"lego.jpg"
);
await _productManager.CreateAsync(
"ABP04918",
"Lego Star Wars - 75059 Sandcrawler UCS",
999,
42,
"lego.jpg"
);
await _productManager.CreateAsync(
"ABP23849",
"Nikon AF-S 50mm f/1.8 G Lens",
1499,
56,
"nikon.jpg"
);
await _productManager.CreateAsync(
"ABP23849",
"Nikon AF-S 50mm f/1.8 G Lens",
1499,
56,
"nikon.jpg"
);
await _productManager.CreateAsync(
"ABP82731",
"Beats Solo3 Wireless On-Ear Headphone",
97,
20,
"beats.jpg"
);
await _productManager.CreateAsync(
"ABP82731",
"Beats Solo3 Wireless On-Ear Headphone",
97,
20,
"beats.jpg"
);
await _productManager.CreateAsync(
"ABP12322",
"Rampage Sn-Rw2 Gamer Headphone",
654,
42,
"rampage.jpg"
);
await _productManager.CreateAsync(
"ABP12322",
"Rampage Sn-Rw2 Gamer Headphone",
654,
42,
"rampage.jpg"
);
await _productManager.CreateAsync(
"ABP00291",
"Asus Transformer Book T300CHI-FH011H",
1249,
3,
"asus.jpg"
);
await _productManager.CreateAsync(
"ABP00291",
"Asus Transformer Book T300CHI-FH011H",
1249,
3,
"asus.jpg"
);
await _productManager.CreateAsync(
"ABP02918",
"OKI C332DN Dublex + Network A4 Laser Printer",
215,
6,
"oki.jpg"
);
await _productManager.CreateAsync(
"ABP02918",
"OKI C332DN Dublex + Network A4 Laser Printer",
215,
6,
"oki.jpg"
);
await _productManager.CreateAsync(
"ABP11121",
"Bluecat Rd810 Mini Led",
449,
13,
"bluecat.jpg"
);
await _productManager.CreateAsync(
"ABP11121",
"Bluecat Rd810 Mini Led",
449,
13,
"bluecat.jpg"
);
await _productManager.CreateAsync(
"ABP44432",
"Sunny 55\" TV 4K Ultra HD Curved Smart Led TV",
2249,
1,
"sunny.jpg"
);
await _productManager.CreateAsync(
"ABP44432",
"Sunny 55\" TV 4K Ultra HD Curved Smart Led TV",
2249,
1,
"sunny.jpg"
);
await _productManager.CreateAsync(
"ABP37182",
"Sony Playstation 4 Slim 500 GB (PAL)",
699,
120,
"playstation.jpg"
);
}
await _productManager.CreateAsync(
"ABP37182",
"Sony Playstation 4 Slim 500 GB (PAL)",
699,
120,
"playstation.jpg"
);
}
}
}

13
services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/Controllers/HomeController.cs

@ -1,13 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
namespace EShopOnAbp.IdentityService.Controllers
namespace EShopOnAbp.IdentityService.Controllers;
public class HomeController : AbpController
{
public class HomeController : AbpController
public ActionResult Index()
{
public ActionResult Index()
{
return Redirect("~/swagger");
}
return Redirect("~/swagger");
}
}
}

11
services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/DbMigrations/ApplyDatabaseSeedsEto.cs

@ -1,10 +1,9 @@
using Volo.Abp.Domain.Entities.Events.Distributed;
using Volo.Abp.EventBus;
namespace EShopOnAbp.IdentityService.DbMigrations
namespace EShopOnAbp.IdentityService.DbMigrations;
[EventName("abp.identity.apply_database_seeds")]
public class ApplyDatabaseSeedsEto : EtoBase
{
[EventName("abp.identity.apply_database_seeds")]
public class ApplyDatabaseSeedsEto : EtoBase
{
}
}
}

28
services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/DbMigrations/DataSeederEventHandler.cs

@ -1,23 +1,21 @@
using System;
using System.Threading.Tasks;
using System.Threading.Tasks;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus;
namespace EShopOnAbp.IdentityService.DbMigrations
namespace EShopOnAbp.IdentityService.DbMigrations;
public class DataSeederEventHandler : ILocalEventHandler<ApplyDatabaseSeedsEto>, ITransientDependency
{
public class DataSeederEventHandler : ILocalEventHandler<ApplyDatabaseSeedsEto>, ITransientDependency
{
protected IDataSeeder DataSeeder { get; }
protected IDataSeeder DataSeeder { get; }
public DataSeederEventHandler(IDataSeeder dataSeeder)
{
DataSeeder = dataSeeder;
}
public DataSeederEventHandler(IDataSeeder dataSeeder)
{
DataSeeder = dataSeeder;
}
public async Task HandleEventAsync(ApplyDatabaseSeedsEto eventData)
{
await DataSeeder.SeedAsync();
}
public async Task HandleEventAsync(ApplyDatabaseSeedsEto eventData)
{
await DataSeeder.SeedAsync();
}
}
}

625
services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/DbMigrations/IdentityServerDataSeeder.cs

@ -20,381 +20,380 @@ using ApiResource = Volo.Abp.IdentityServer.ApiResources.ApiResource;
using ApiScope = Volo.Abp.IdentityServer.ApiScopes.ApiScope;
using Client = Volo.Abp.IdentityServer.Clients.Client;
namespace EShopOnAbp.IdentityService.DbMigrations
namespace EShopOnAbp.IdentityService.DbMigrations;
public class IdentityServerDataSeeder : IDataSeedContributor, ITransientDependency
{
public class IdentityServerDataSeeder : IDataSeedContributor, ITransientDependency
private readonly IApiResourceRepository _apiResourceRepository;
private readonly IApiScopeRepository _apiScopeRepository;
private readonly IClientRepository _clientRepository;
private readonly IIdentityResourceDataSeeder _identityResourceDataSeeder;
private readonly IGuidGenerator _guidGenerator;
private readonly IPermissionDataSeeder _permissionDataSeeder;
private readonly IConfiguration _configuration;
private readonly ICurrentTenant _currentTenant;
public IdentityServerDataSeeder(
IClientRepository clientRepository,
IApiResourceRepository apiResourceRepository,
IApiScopeRepository apiScopeRepository,
IIdentityResourceDataSeeder identityResourceDataSeeder,
IGuidGenerator guidGenerator,
IPermissionDataSeeder permissionDataSeeder,
IConfiguration configuration,
ICurrentTenant currentTenant)
{
private readonly IApiResourceRepository _apiResourceRepository;
private readonly IApiScopeRepository _apiScopeRepository;
private readonly IClientRepository _clientRepository;
private readonly IIdentityResourceDataSeeder _identityResourceDataSeeder;
private readonly IGuidGenerator _guidGenerator;
private readonly IPermissionDataSeeder _permissionDataSeeder;
private readonly IConfiguration _configuration;
private readonly ICurrentTenant _currentTenant;
_clientRepository = clientRepository;
_apiResourceRepository = apiResourceRepository;
_apiScopeRepository = apiScopeRepository;
_identityResourceDataSeeder = identityResourceDataSeeder;
_guidGenerator = guidGenerator;
_permissionDataSeeder = permissionDataSeeder;
_configuration = configuration;
_currentTenant = currentTenant;
}
public IdentityServerDataSeeder(
IClientRepository clientRepository,
IApiResourceRepository apiResourceRepository,
IApiScopeRepository apiScopeRepository,
IIdentityResourceDataSeeder identityResourceDataSeeder,
IGuidGenerator guidGenerator,
IPermissionDataSeeder permissionDataSeeder,
IConfiguration configuration,
ICurrentTenant currentTenant)
{
_clientRepository = clientRepository;
_apiResourceRepository = apiResourceRepository;
_apiScopeRepository = apiScopeRepository;
_identityResourceDataSeeder = identityResourceDataSeeder;
_guidGenerator = guidGenerator;
_permissionDataSeeder = permissionDataSeeder;
_configuration = configuration;
_currentTenant = currentTenant;
}
public virtual Task SeedAsync(DataSeedContext context)
{
return SeedAsync();
}
public virtual Task SeedAsync(DataSeedContext context)
[UnitOfWork]
public virtual async Task SeedAsync()
{
using (_currentTenant.Change(null))
{
return SeedAsync();
await _identityResourceDataSeeder.CreateStandardResourcesAsync();
await CreateApiResourcesAsync();
await CreateApiScopesAsync();
await CreateSwaggerClientsAsync();
await CreateClientsAsync();
}
}
[UnitOfWork]
public virtual async Task SeedAsync()
private async Task CreateApiResourcesAsync()
{
var commonApiUserClaims = new[]
{
using (_currentTenant.Change(null))
{
await _identityResourceDataSeeder.CreateStandardResourcesAsync();
await CreateApiResourcesAsync();
await CreateApiScopesAsync();
await CreateSwaggerClientsAsync();
await CreateClientsAsync();
}
}
"email",
"email_verified",
"name",
"phone_number",
"phone_number_verified",
"role"
};
private async Task CreateApiResourcesAsync()
{
var commonApiUserClaims = new[]
{
"email",
"email_verified",
"name",
"phone_number",
"phone_number_verified",
"role"
};
await CreateApiResourceAsync("AccountService", commonApiUserClaims);
await CreateApiResourceAsync("IdentityService", commonApiUserClaims);
await CreateApiResourceAsync("AdministrationService", commonApiUserClaims);
await CreateApiResourceAsync("CatalogService", commonApiUserClaims);
await CreateApiResourceAsync("BasketService", commonApiUserClaims);
await CreateApiResourceAsync("OrderingService", commonApiUserClaims);
await CreateApiResourceAsync("PaymentService", commonApiUserClaims);
}
await CreateApiResourceAsync("AccountService", commonApiUserClaims);
await CreateApiResourceAsync("IdentityService", commonApiUserClaims);
await CreateApiResourceAsync("AdministrationService", commonApiUserClaims);
await CreateApiResourceAsync("CatalogService", commonApiUserClaims);
await CreateApiResourceAsync("BasketService", commonApiUserClaims);
await CreateApiResourceAsync("OrderingService", commonApiUserClaims);
await CreateApiResourceAsync("PaymentService", commonApiUserClaims);
}
private async Task CreateApiScopesAsync()
{
await CreateApiScopeAsync("AccountService");
await CreateApiScopeAsync("IdentityService");
await CreateApiScopeAsync("AdministrationService");
await CreateApiScopeAsync("CatalogService");
await CreateApiScopeAsync("BasketService");
await CreateApiScopeAsync("OrderingService");
await CreateApiScopeAsync("PaymentService");
}
private async Task CreateSwaggerClientsAsync()
{
await CreateWebGatewaySwaggerClientAsync("WebGateway",
new[]
{
"AccountService", "IdentityService", "AdministrationService",
"CatalogService", "BasketService",
"PaymentService", "OrderingService"
});
}
private async Task CreateApiScopesAsync()
private async Task CreateWebGatewaySwaggerClientAsync(string name, string[] scopes = null)
{
var commonScopes = new[]
{
await CreateApiScopeAsync("AccountService");
await CreateApiScopeAsync("IdentityService");
await CreateApiScopeAsync("AdministrationService");
await CreateApiScopeAsync("CatalogService");
await CreateApiScopeAsync("BasketService");
await CreateApiScopeAsync("OrderingService");
await CreateApiScopeAsync("PaymentService");
}
"email",
"openid",
"profile",
"role",
"phone",
"address"
};
scopes ??= new[] {name};
private async Task CreateSwaggerClientsAsync()
// Swagger Client
var swaggerClientId = $"{name}_Swagger";
if (!swaggerClientId.IsNullOrWhiteSpace())
{
await CreateWebGatewaySwaggerClientAsync("WebGateway",
new[]
var webGatewaySwaggerRootUrl = _configuration[$"IdentityServerClients:{name}:RootUrl"].TrimEnd('/');
var publicWebGatewayRootUrl = _configuration[$"IdentityServerClients:PublicWebGateway:RootUrl"].TrimEnd('/');
var accountServiceRootUrl = _configuration[$"IdentityServerClients:AccountService:RootUrl"].TrimEnd('/');
var identityServiceRootUrl = _configuration[$"IdentityServerClients:IdentityService:RootUrl"].TrimEnd('/');
var administrationServiceRootUrl = _configuration[$"IdentityServerClients:AdministrationService:RootUrl"].TrimEnd('/');
var catalogServiceRootUrl = _configuration[$"IdentityServerClients:CatalogService:RootUrl"].TrimEnd('/');
var basketServiceRootUrl = _configuration[$"IdentityServerClients:BasketService:RootUrl"].TrimEnd('/');
var orderingServiceRootUrl = _configuration[$"IdentityServerClients:OrderingService:RootUrl"].TrimEnd('/');
var paymentServiceRootUrl = _configuration[$"IdentityServerClients:PaymentService:RootUrl"].TrimEnd('/');
await CreateClientAsync(
name: swaggerClientId,
scopes: commonScopes.Union(scopes),
grantTypes: new[] {"authorization_code"},
secret: "1q2w3e*".Sha256(),
requireClientSecret: false,
redirectUris: new List<string>
{
$"{webGatewaySwaggerRootUrl}/swagger/oauth2-redirect.html", // WebGateway redirect uri
$"{publicWebGatewayRootUrl}/swagger/oauth2-redirect.html", // PublicWebGateway redirect uri
$"{accountServiceRootUrl}/swagger/oauth2-redirect.html", // AccountService redirect uri
$"{identityServiceRootUrl}/swagger/oauth2-redirect.html", // IdentityService redirect uri
$"{administrationServiceRootUrl}/swagger/oauth2-redirect.html", // AdministrationService redirect uri
$"{catalogServiceRootUrl}/swagger/oauth2-redirect.html", // CatalogService redirect uri
$"{basketServiceRootUrl}/swagger/oauth2-redirect.html", // BasketService redirect uri
$"{orderingServiceRootUrl}/swagger/oauth2-redirect.html", // OrderingService redirect uri
$"{paymentServiceRootUrl}/swagger/oauth2-redirect.html" // PaymentService redirect uri
},
corsOrigins: new[]
{
"AccountService", "IdentityService", "AdministrationService",
"CatalogService", "BasketService",
"PaymentService", "OrderingService"
});
webGatewaySwaggerRootUrl.RemovePostFix("/"),
publicWebGatewayRootUrl.RemovePostFix("/"),
accountServiceRootUrl.RemovePostFix("/"),
identityServiceRootUrl.RemovePostFix("/"),
administrationServiceRootUrl.RemovePostFix("/"),
catalogServiceRootUrl.RemovePostFix("/"),
basketServiceRootUrl.RemovePostFix("/"),
orderingServiceRootUrl.RemovePostFix("/"),
paymentServiceRootUrl.RemovePostFix("/")
}
);
}
}
private async Task CreateWebGatewaySwaggerClientAsync(string name, string[] scopes = null)
private async Task<ApiResource> CreateApiResourceAsync(string name, IEnumerable<string> claims)
{
var apiResource = await _apiResourceRepository.FindByNameAsync(name);
if (apiResource == null)
{
var commonScopes = new[]
{
"email",
"openid",
"profile",
"role",
"phone",
"address"
};
scopes ??= new[] {name};
// Swagger Client
var swaggerClientId = $"{name}_Swagger";
if (!swaggerClientId.IsNullOrWhiteSpace())
{
var webGatewaySwaggerRootUrl = _configuration[$"IdentityServerClients:{name}:RootUrl"].TrimEnd('/');
var publicWebGatewayRootUrl = _configuration[$"IdentityServerClients:PublicWebGateway:RootUrl"].TrimEnd('/');
var accountServiceRootUrl = _configuration[$"IdentityServerClients:AccountService:RootUrl"].TrimEnd('/');
var identityServiceRootUrl = _configuration[$"IdentityServerClients:IdentityService:RootUrl"].TrimEnd('/');
var administrationServiceRootUrl = _configuration[$"IdentityServerClients:AdministrationService:RootUrl"].TrimEnd('/');
var catalogServiceRootUrl = _configuration[$"IdentityServerClients:CatalogService:RootUrl"].TrimEnd('/');
var basketServiceRootUrl = _configuration[$"IdentityServerClients:BasketService:RootUrl"].TrimEnd('/');
var orderingServiceRootUrl = _configuration[$"IdentityServerClients:OrderingService:RootUrl"].TrimEnd('/');
var paymentServiceRootUrl = _configuration[$"IdentityServerClients:PaymentService:RootUrl"].TrimEnd('/');
await CreateClientAsync(
name: swaggerClientId,
scopes: commonScopes.Union(scopes),
grantTypes: new[] {"authorization_code"},
secret: "1q2w3e*".Sha256(),
requireClientSecret: false,
redirectUris: new List<string>
{
$"{webGatewaySwaggerRootUrl}/swagger/oauth2-redirect.html", // WebGateway redirect uri
$"{publicWebGatewayRootUrl}/swagger/oauth2-redirect.html", // PublicWebGateway redirect uri
$"{accountServiceRootUrl}/swagger/oauth2-redirect.html", // AccountService redirect uri
$"{identityServiceRootUrl}/swagger/oauth2-redirect.html", // IdentityService redirect uri
$"{administrationServiceRootUrl}/swagger/oauth2-redirect.html", // AdministrationService redirect uri
$"{catalogServiceRootUrl}/swagger/oauth2-redirect.html", // CatalogService redirect uri
$"{basketServiceRootUrl}/swagger/oauth2-redirect.html", // BasketService redirect uri
$"{orderingServiceRootUrl}/swagger/oauth2-redirect.html", // OrderingService redirect uri
$"{paymentServiceRootUrl}/swagger/oauth2-redirect.html" // PaymentService redirect uri
},
corsOrigins: new[]
{
webGatewaySwaggerRootUrl.RemovePostFix("/"),
publicWebGatewayRootUrl.RemovePostFix("/"),
accountServiceRootUrl.RemovePostFix("/"),
identityServiceRootUrl.RemovePostFix("/"),
administrationServiceRootUrl.RemovePostFix("/"),
catalogServiceRootUrl.RemovePostFix("/"),
basketServiceRootUrl.RemovePostFix("/"),
orderingServiceRootUrl.RemovePostFix("/"),
paymentServiceRootUrl.RemovePostFix("/")
}
);
}
apiResource = await _apiResourceRepository.InsertAsync(
new ApiResource(
_guidGenerator.Create(),
name,
name + " API"
),
autoSave: true
);
}
private async Task<ApiResource> CreateApiResourceAsync(string name, IEnumerable<string> claims)
foreach (var claim in claims)
{
var apiResource = await _apiResourceRepository.FindByNameAsync(name);
if (apiResource == null)
if (apiResource.FindClaim(claim) == null)
{
apiResource = await _apiResourceRepository.InsertAsync(
new ApiResource(
_guidGenerator.Create(),
name,
name + " API"
),
autoSave: true
);
}
foreach (var claim in claims)
{
if (apiResource.FindClaim(claim) == null)
{
apiResource.AddUserClaim(claim);
}
apiResource.AddUserClaim(claim);
}
return await _apiResourceRepository.UpdateAsync(apiResource);
}
private async Task<ApiScope> CreateApiScopeAsync(string name)
{
var apiScope = await _apiScopeRepository.FindByNameAsync(name);
if (apiScope == null)
{
apiScope = await _apiScopeRepository.InsertAsync(
new ApiScope(
_guidGenerator.Create(),
name,
name + " API"
),
autoSave: true
);
}
return await _apiResourceRepository.UpdateAsync(apiResource);
}
return apiScope;
private async Task<ApiScope> CreateApiScopeAsync(string name)
{
var apiScope = await _apiScopeRepository.FindByNameAsync(name);
if (apiScope == null)
{
apiScope = await _apiScopeRepository.InsertAsync(
new ApiScope(
_guidGenerator.Create(),
name,
name + " API"
),
autoSave: true
);
}
private async Task CreateClientsAsync()
return apiScope;
}
private async Task CreateClientsAsync()
{
var commonScopes = new[]
{
var commonScopes = new[]
"email",
"openid",
"profile",
"role",
"phone",
"address"
};
//Public Web Client
var publicWebClientRootUrl = _configuration["IdentityServerClients:PublicWeb:RootUrl"]
.EnsureEndsWith('/');
await CreateClientAsync(
name: "PublicWeb",
scopes: commonScopes.Union(new[]
{
"email",
"openid",
"profile",
"role",
"phone",
"address"
};
"AccountService",
"AdministrationService",
"CatalogService",
"BasketService",
"PaymentService",
"OrderingService"
}),
grantTypes: new[] {"hybrid"},
secret: "1q2w3e*".Sha256(),
redirectUris: new List<string>{ $"{publicWebClientRootUrl}signin-oidc" },
postLogoutRedirectUri: $"{publicWebClientRootUrl}signout-callback-oidc",
frontChannelLogoutUri: $"{publicWebClientRootUrl}Account/FrontChannelLogout",
corsOrigins: new[] {publicWebClientRootUrl.RemovePostFix("/")}
);
//Public Web Client
var publicWebClientRootUrl = _configuration["IdentityServerClients:PublicWeb:RootUrl"]
.EnsureEndsWith('/');
await CreateClientAsync(
name: "PublicWeb",
scopes: commonScopes.Union(new[]
{
"AccountService",
"AdministrationService",
"CatalogService",
"BasketService",
"PaymentService",
"OrderingService"
}),
grantTypes: new[] {"hybrid"},
secret: "1q2w3e*".Sha256(),
redirectUris: new List<string>{ $"{publicWebClientRootUrl}signin-oidc" },
postLogoutRedirectUri: $"{publicWebClientRootUrl}signout-callback-oidc",
frontChannelLogoutUri: $"{publicWebClientRootUrl}Account/FrontChannelLogout",
corsOrigins: new[] {publicWebClientRootUrl.RemovePostFix("/")}
);
//Angular Client
var angularClientRootUrl =
_configuration["IdentityServerClients:Web:RootUrl"].TrimEnd('/');
await CreateClientAsync(
name: "Web",
scopes: commonScopes.Union(new[]
{
"AccountService",
"IdentityService",
"AdministrationService",
"CatalogService"
}),
grantTypes: new[] {"authorization_code", "LinkLogin", "password"},
secret: "1q2w3e*".Sha256(),
requirePkce: true,
requireClientSecret: false,
redirectUris: new List<string>{ $"{angularClientRootUrl}" },
postLogoutRedirectUri: $"{angularClientRootUrl}",
corsOrigins: new[] {angularClientRootUrl}
);
//Angular Client
var angularClientRootUrl =
_configuration["IdentityServerClients:Web:RootUrl"].TrimEnd('/');
await CreateClientAsync(
name: "Web",
scopes: commonScopes.Union(new[]
{
"AccountService",
"IdentityService",
"AdministrationService",
"CatalogService"
}),
grantTypes: new[] {"authorization_code", "LinkLogin", "password"},
secret: "1q2w3e*".Sha256(),
requirePkce: true,
requireClientSecret: false,
redirectUris: new List<string>{ $"{angularClientRootUrl}" },
postLogoutRedirectUri: $"{angularClientRootUrl}",
corsOrigins: new[] {angularClientRootUrl}
);
//Administration Service Client
await CreateClientAsync(
name: "EShopOnAbp_AdministrationService",
scopes: commonScopes.Union(new[]
{
"IdentityService"
}),
grantTypes: new[] {"client_credentials"},
secret: "1q2w3e*".Sha256(),
permissions: new[] {IdentityPermissions.Users.Default}
);
}
//Administration Service Client
await CreateClientAsync(
name: "EShopOnAbp_AdministrationService",
scopes: commonScopes.Union(new[]
private async Task<Client> CreateClientAsync(
string name,
IEnumerable<string> scopes,
IEnumerable<string> grantTypes,
string secret = null,
List<string> redirectUris = null,
string postLogoutRedirectUri = null,
string frontChannelLogoutUri = null,
bool requireClientSecret = true,
bool requirePkce = false,
IEnumerable<string> permissions = null,
IEnumerable<string> corsOrigins = null)
{
var client = await _clientRepository.FindByClientIdAsync(name);
if (client == null)
{
client = await _clientRepository.InsertAsync(
new Client(
_guidGenerator.Create(),
name
)
{
"IdentityService"
}),
grantTypes: new[] {"client_credentials"},
secret: "1q2w3e*".Sha256(),
permissions: new[] {IdentityPermissions.Users.Default}
ClientName = name,
ProtocolType = "oidc",
Description = name,
AlwaysIncludeUserClaimsInIdToken = true,
AllowOfflineAccess = true,
AbsoluteRefreshTokenLifetime = 31536000, //365 days
AccessTokenLifetime = 31536000, //365 days
AuthorizationCodeLifetime = 300,
IdentityTokenLifetime = 300,
RequireConsent = false,
FrontChannelLogoutUri = frontChannelLogoutUri,
RequireClientSecret = requireClientSecret,
RequirePkce = requirePkce
},
autoSave: true
);
}
private async Task<Client> CreateClientAsync(
string name,
IEnumerable<string> scopes,
IEnumerable<string> grantTypes,
string secret = null,
List<string> redirectUris = null,
string postLogoutRedirectUri = null,
string frontChannelLogoutUri = null,
bool requireClientSecret = true,
bool requirePkce = false,
IEnumerable<string> permissions = null,
IEnumerable<string> corsOrigins = null)
foreach (var scope in scopes)
{
var client = await _clientRepository.FindByClientIdAsync(name);
if (client == null)
if (client.FindScope(scope) == null)
{
client = await _clientRepository.InsertAsync(
new Client(
_guidGenerator.Create(),
name
)
{
ClientName = name,
ProtocolType = "oidc",
Description = name,
AlwaysIncludeUserClaimsInIdToken = true,
AllowOfflineAccess = true,
AbsoluteRefreshTokenLifetime = 31536000, //365 days
AccessTokenLifetime = 31536000, //365 days
AuthorizationCodeLifetime = 300,
IdentityTokenLifetime = 300,
RequireConsent = false,
FrontChannelLogoutUri = frontChannelLogoutUri,
RequireClientSecret = requireClientSecret,
RequirePkce = requirePkce
},
autoSave: true
);
}
foreach (var scope in scopes)
{
if (client.FindScope(scope) == null)
{
client.AddScope(scope);
}
client.AddScope(scope);
}
}
foreach (var grantType in grantTypes)
foreach (var grantType in grantTypes)
{
if (client.FindGrantType(grantType) == null)
{
if (client.FindGrantType(grantType) == null)
{
client.AddGrantType(grantType);
}
client.AddGrantType(grantType);
}
}
if (!secret.IsNullOrEmpty())
if (!secret.IsNullOrEmpty())
{
if (client.FindSecret(secret) == null)
{
if (client.FindSecret(secret) == null)
{
client.AddSecret(secret);
}
client.AddSecret(secret);
}
}
if (redirectUris != null)
if (redirectUris != null)
{
foreach (var redirectUri in redirectUris)
{
foreach (var redirectUri in redirectUris)
if (redirectUri != null)
{
if (redirectUri != null)
if (client.FindRedirectUri(redirectUri) == null)
{
if (client.FindRedirectUri(redirectUri) == null)
{
client.AddRedirectUri(redirectUri);
}
client.AddRedirectUri(redirectUri);
}
}
}
}
if (postLogoutRedirectUri != null)
if (postLogoutRedirectUri != null)
{
if (client.FindPostLogoutRedirectUri(postLogoutRedirectUri) == null)
{
if (client.FindPostLogoutRedirectUri(postLogoutRedirectUri) == null)
{
client.AddPostLogoutRedirectUri(postLogoutRedirectUri);
}
client.AddPostLogoutRedirectUri(postLogoutRedirectUri);
}
}
if (permissions != null)
{
await _permissionDataSeeder.SeedAsync(
ClientPermissionValueProvider.ProviderName,
name,
permissions,
null
);
}
if (permissions != null)
{
await _permissionDataSeeder.SeedAsync(
ClientPermissionValueProvider.ProviderName,
name,
permissions,
null
);
}
if (corsOrigins != null)
if (corsOrigins != null)
{
foreach (var origin in corsOrigins)
{
foreach (var origin in corsOrigins)
if (!origin.IsNullOrWhiteSpace() && client.FindCorsOrigin(origin) == null)
{
if (!origin.IsNullOrWhiteSpace() && client.FindCorsOrigin(origin) == null)
{
client.AddCorsOrigin(origin);
}
client.AddCorsOrigin(origin);
}
}
return await _clientRepository.UpdateAsync(client);
}
return await _clientRepository.UpdateAsync(client);
}
}

53
services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/DbMigrations/IdentityServiceDatabaseMigrationChecker.cs

@ -7,38 +7,37 @@ using Volo.Abp.EventBus.Local;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
namespace EShopOnAbp.IdentityService.DbMigrations
namespace EShopOnAbp.IdentityService.DbMigrations;
public class IdentityServiceDatabaseMigrationChecker : PendingEfCoreMigrationsChecker<IdentityServiceDbContext>
{
public class IdentityServiceDatabaseMigrationChecker : PendingEfCoreMigrationsChecker<IdentityServiceDbContext>
protected ILocalEventBus LocalEventBus { get; }
public IdentityServiceDatabaseMigrationChecker(
IUnitOfWorkManager unitOfWorkManager,
IServiceProvider serviceProvider,
ICurrentTenant currentTenant,
IDistributedEventBus distributedEventBus,
ILocalEventBus localEventBus)
: base(
unitOfWorkManager,
serviceProvider,
currentTenant,
distributedEventBus,
IdentityServiceDbProperties.ConnectionStringName)
{
protected ILocalEventBus LocalEventBus { get; }
LocalEventBus = localEventBus;
}
public IdentityServiceDatabaseMigrationChecker(
IUnitOfWorkManager unitOfWorkManager,
IServiceProvider serviceProvider,
ICurrentTenant currentTenant,
IDistributedEventBus distributedEventBus,
ILocalEventBus localEventBus)
: base(
unitOfWorkManager,
serviceProvider,
currentTenant,
distributedEventBus,
IdentityServiceDbProperties.ConnectionStringName)
{
LocalEventBus = localEventBus;
}
public override async Task<bool> CheckAsync()
{
var isMigrationRequired = await base.CheckAsync();
public override async Task<bool> CheckAsync()
if (!isMigrationRequired)
{
var isMigrationRequired = await base.CheckAsync();
if (!isMigrationRequired)
{
await LocalEventBus.PublishAsync(new ApplyDatabaseSeedsEto());
}
return isMigrationRequired;
await LocalEventBus.PublishAsync(new ApplyDatabaseSeedsEto());
}
return isMigrationRequired;
}
}

122
services/identity/src/EShopOnAbp.IdentityService.HttpApi.Host/DbMigrations/IdentityServiceDatabaseMigrationEventHandler.cs

@ -11,82 +11,80 @@ using Volo.Abp.Identity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
namespace EShopOnAbp.IdentityService.DbMigrations
namespace EShopOnAbp.IdentityService.DbMigrations;
public class IdentityServiceDatabaseMigrationEventHandler
: DatabaseEfCoreMigrationEventHandler<IdentityServiceDbContext>,
IDistributedEventHandler<ApplyDatabaseMigrationsEto>
{
public class IdentityServiceDatabaseMigrationEventHandler
: DatabaseEfCoreMigrationEventHandler<IdentityServiceDbContext>,
IDistributedEventHandler<ApplyDatabaseMigrationsEto>
private readonly IIdentityDataSeeder _identityDataSeeder;
private readonly IdentityServerDataSeeder _identityServerDataSeeder;
private readonly ILocalEventBus _localEventBus;
public IdentityServiceDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IIdentityDataSeeder identityDataSeeder,
IdentityServerDataSeeder identityServerDataSeeder,
IDistributedEventBus distributedEventBus,
ILocalEventBus localEventBus,
IAbpDistributedLock distributedLockProvider
) : base(
currentTenant,
unitOfWorkManager,
tenantStore,
distributedEventBus,
IdentityServiceDbProperties.ConnectionStringName,
distributedLockProvider)
{
private readonly IIdentityDataSeeder _identityDataSeeder;
private readonly IdentityServerDataSeeder _identityServerDataSeeder;
private readonly ILocalEventBus _localEventBus;
_identityDataSeeder = identityDataSeeder;
_identityServerDataSeeder = identityServerDataSeeder;
_localEventBus = localEventBus;
}
public IdentityServiceDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IIdentityDataSeeder identityDataSeeder,
IdentityServerDataSeeder identityServerDataSeeder,
IDistributedEventBus distributedEventBus,
ILocalEventBus localEventBus,
IAbpDistributedLock distributedLockProvider
) : base(
currentTenant,
unitOfWorkManager,
tenantStore,
distributedEventBus,
IdentityServiceDbProperties.ConnectionStringName,
distributedLockProvider)
public async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData)
{
if (eventData.DatabaseName != DatabaseName)
{
_identityDataSeeder = identityDataSeeder;
_identityServerDataSeeder = identityServerDataSeeder;
_localEventBus = localEventBus;
return;
}
public async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData)
try
{
if (eventData.DatabaseName != DatabaseName)
await using (var handle = await DistributedLockProvider.TryAcquireAsync(DatabaseName))
{
return;
}
Log.Information("IdentityService has acquired lock for db migration...");
try
{
await using (var handle = await DistributedLockProvider.TryAcquireAsync(DatabaseName))
if (handle != null)
{
Log.Information("IdentityService has acquired lock for db migration...");
if (handle != null)
{
Log.Information("IdentityService is migrating database...");
await MigrateDatabaseSchemaAsync();
Log.Information("IdentityService is seeding data...");
await SeedDataAsync(
adminEmail: IdentityServiceDbProperties.DefaultAdminEmailAddress,
adminPassword: IdentityServiceDbProperties.DefaultAdminPassword
);
}
Log.Information("IdentityService is migrating database...");
await MigrateDatabaseSchemaAsync();
Log.Information("IdentityService is seeding data...");
await SeedDataAsync(
adminEmail: IdentityServiceDbProperties.DefaultAdminEmailAddress,
adminPassword: IdentityServiceDbProperties.DefaultAdminPassword
);
}
await _localEventBus.PublishAsync(new ApplyDatabaseSeedsEto());
}
catch (Exception ex)
{
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex);
}
}
private async Task SeedDataAsync(string adminEmail, string adminPassword)
await _localEventBus.PublishAsync(new ApplyDatabaseSeedsEto());
}
catch (Exception ex)
{
Log.Information($"Seeding IdentityServer data...");
await _identityServerDataSeeder.SeedAsync();
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex);
}
}
Log.Information($"Seeding user data...");
await _identityDataSeeder.SeedAsync(
adminEmail,
adminPassword
);
private async Task SeedDataAsync(string adminEmail, string adminPassword)
{
Log.Information($"Seeding IdentityServer data...");
await _identityServerDataSeeder.SeedAsync();
}
Log.Information($"Seeding user data...");
await _identityDataSeeder.SeedAsync(
adminEmail,
adminPassword
);
}
}
}

13
services/ordering/src/EShopOnAbp.OrderingService.HttpApi.Host/Controllers/HomeController.cs

@ -1,13 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
namespace EShopOnAbp.OrderingService.Controllers
namespace EShopOnAbp.OrderingService.Controllers;
public class HomeController : AbpController
{
public class HomeController : AbpController
public ActionResult Index()
{
public ActionResult Index()
{
return Redirect("~/swagger");
}
return Redirect("~/swagger");
}
}
}

33
services/ordering/src/EShopOnAbp.OrderingService.HttpApi.Host/DbMigrations/OrderingServiceDatabaseMigrationChecker.cs

@ -5,23 +5,22 @@ using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
namespace EShopOnAbp.OrderingService.DbMigrations
namespace EShopOnAbp.OrderingService.DbMigrations;
public class OrderingServiceDatabaseMigrationChecker
: PendingEfCoreMigrationsChecker<OrderingServiceDbContext>
{
public class OrderingServiceDatabaseMigrationChecker : PendingEfCoreMigrationsChecker<OrderingServiceDbContext>
public OrderingServiceDatabaseMigrationChecker(
IUnitOfWorkManager unitOfWorkManager,
IServiceProvider serviceProvider,
ICurrentTenant currentTenant,
IDistributedEventBus distributedEventBus)
: base(
unitOfWorkManager,
serviceProvider,
currentTenant,
distributedEventBus,
OrderingServiceDbProperties.ConnectionStringName)
{
public OrderingServiceDatabaseMigrationChecker(
IUnitOfWorkManager unitOfWorkManager,
IServiceProvider serviceProvider,
ICurrentTenant currentTenant,
IDistributedEventBus distributedEventBus)
: base(
unitOfWorkManager,
serviceProvider,
currentTenant,
distributedEventBus,
OrderingServiceDbProperties.ConnectionStringName)
{
}
}
}
}

89
services/ordering/src/EShopOnAbp.OrderingService.HttpApi.Host/DbMigrations/OrderingServiceDatabaseMigrationEventHandler.cs

@ -9,63 +9,62 @@ using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
namespace EShopOnAbp.OrderingService.DbMigrations
{
public class OrderingServiceDatabaseMigrationEventHandler
: DatabaseEfCoreMigrationEventHandler<OrderingServiceDbContext>,
namespace EShopOnAbp.OrderingService.DbMigrations;
public class OrderingServiceDatabaseMigrationEventHandler
: DatabaseEfCoreMigrationEventHandler<OrderingServiceDbContext>,
IDistributedEventHandler<ApplyDatabaseMigrationsEto>
{
private readonly IDataSeeder _dataSeeder;
public OrderingServiceDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IDistributedEventBus distributedEventBus,
IDataSeeder dataSeeder,
IAbpDistributedLock distributedLockProvider)
: base(
currentTenant,
unitOfWorkManager,
tenantStore,
distributedEventBus,
OrderingServiceDbProperties.ConnectionStringName,
distributedLockProvider)
{
private readonly IDataSeeder _dataSeeder;
_dataSeeder = dataSeeder;
}
public OrderingServiceDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IDistributedEventBus distributedEventBus,
IDataSeeder dataSeeder,
IAbpDistributedLock distributedLockProvider)
: base(
currentTenant,
unitOfWorkManager,
tenantStore,
distributedEventBus,
OrderingServiceDbProperties.ConnectionStringName,
distributedLockProvider)
public async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData)
{
if (eventData.DatabaseName != DatabaseName)
{
_dataSeeder = dataSeeder;
return;
}
public async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData)
if (eventData.TenantId != null)
{
if (eventData.DatabaseName != DatabaseName)
{
return;
}
return;
}
if (eventData.TenantId != null)
try
{
await using (var handle = await DistributedLockProvider.TryAcquireAsync(DatabaseName))
{
return;
}
Log.Information("OrderingService has acquired lock for db migration...");
try
{
await using (var handle = await DistributedLockProvider.TryAcquireAsync(DatabaseName))
if (handle != null)
{
Log.Information("OrderingService has acquired lock for db migration...");
if (handle != null)
{
Log.Information("OrderingService is migrating database...");
await MigrateDatabaseSchemaAsync();
Log.Information("OrderingService is seeding data...");
await _dataSeeder.SeedAsync();
}
Log.Information("OrderingService is migrating database...");
await MigrateDatabaseSchemaAsync();
Log.Information("OrderingService is seeding data...");
await _dataSeeder.SeedAsync();
}
}
catch (Exception ex)
{
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex);
}
}
catch (Exception ex)
{
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex);
}
}
}
}

1
services/ordering/src/EShopOnAbp.OrderingService.HttpApi.Host/OrderingServiceHttpApiHostModule.cs

@ -21,7 +21,6 @@ namespace EShopOnAbp.OrderingService;
typeof(OrderingServiceHttpApiModule),
typeof(OrderingServiceApplicationModule),
typeof(OrderingServiceEntityFrameworkCoreModule),
//typeof(MedallionAbpDistributedLock),
typeof(EShopOnAbpSharedHostingMicroservicesModule)
)]
public class OrderingServiceHttpApiHostModule : AbpModule

13
services/payment/src/EShopOnAbp.PaymentService.HttpApi.Host/Controllers/HomeController.cs

@ -1,13 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
namespace EShopOnAbp.PaymentService.Controllers
namespace EShopOnAbp.PaymentService.Controllers;
public class HomeController : AbpController
{
public class HomeController : AbpController
public ActionResult Index()
{
public ActionResult Index()
{
return Redirect("~/swagger");
}
return Redirect("~/swagger");
}
}
}

33
services/payment/src/EShopOnAbp.PaymentService.HttpApi.Host/DbMigrations/PaymentServiceDatabaseMigrationChecker.cs

@ -5,23 +5,22 @@ using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
namespace EShopOnAbp.PaymentService.DbMigrations
namespace EShopOnAbp.PaymentService.DbMigrations;
public class PaymentServiceDatabaseMigrationChecker
: PendingEfCoreMigrationsChecker<PaymentServiceDbContext>
{
public class PaymentServiceDatabaseMigrationChecker : PendingEfCoreMigrationsChecker<PaymentServiceDbContext>
public PaymentServiceDatabaseMigrationChecker(
IUnitOfWorkManager unitOfWorkManager,
IServiceProvider serviceProvider,
ICurrentTenant currentTenant,
IDistributedEventBus distributedEventBus)
: base(
unitOfWorkManager,
serviceProvider,
currentTenant,
distributedEventBus,
PaymentServiceDbProperties.ConnectionStringName)
{
public PaymentServiceDatabaseMigrationChecker(
IUnitOfWorkManager unitOfWorkManager,
IServiceProvider serviceProvider,
ICurrentTenant currentTenant,
IDistributedEventBus distributedEventBus)
: base(
unitOfWorkManager,
serviceProvider,
currentTenant,
distributedEventBus,
PaymentServiceDbProperties.ConnectionStringName)
{
}
}
}
}

79
services/payment/src/EShopOnAbp.PaymentService.HttpApi.Host/DbMigrations/PaymentServiceDatabaseMigrationEventHandler.cs

@ -9,57 +9,56 @@ using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
namespace EShopOnAbp.PaymentService.DbMigrations
{
public class PaymentServiceDatabaseMigrationEventHandler
: DatabaseEfCoreMigrationEventHandler<PaymentServiceDbContext>,
namespace EShopOnAbp.PaymentService.DbMigrations;
public class PaymentServiceDatabaseMigrationEventHandler
: DatabaseEfCoreMigrationEventHandler<PaymentServiceDbContext>,
IDistributedEventHandler<ApplyDatabaseMigrationsEto>
{
public PaymentServiceDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IDistributedEventBus distributedEventBus,
IAbpDistributedLock distributedLockProvider)
: base(
currentTenant,
unitOfWorkManager,
tenantStore,
distributedEventBus,
PaymentServiceDbProperties.ConnectionStringName,
distributedLockProvider)
{
public PaymentServiceDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IDistributedEventBus distributedEventBus,
IAbpDistributedLock distributedLockProvider)
: base(
currentTenant,
unitOfWorkManager,
tenantStore,
distributedEventBus,
PaymentServiceDbProperties.ConnectionStringName,
distributedLockProvider)
}
public async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData)
{
if (eventData.DatabaseName != DatabaseName)
{
return;
}
public async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData)
if (eventData.TenantId != null)
{
if (eventData.DatabaseName != DatabaseName)
{
return;
}
return;
}
if (eventData.TenantId != null)
{
return;
}
try
{
Log.Information("PaymentService has acquired lock for db migration...");
try
await using (var handle = await DistributedLockProvider.TryAcquireAsync(DatabaseName))
{
Log.Information("PaymentService has acquired lock for db migration...");
await using (var handle = await DistributedLockProvider.TryAcquireAsync(DatabaseName))
if (handle != null)
{
if (handle != null)
{
Log.Information("PaymentService is migrating database...");
await MigrateDatabaseSchemaAsync();
}
Log.Information("PaymentService is migrating database...");
await MigrateDatabaseSchemaAsync();
}
}
catch (Exception ex)
{
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex);
}
}
catch (Exception ex)
{
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex);
}
}
}
}

19
shared/EShopOnAbp.Shared.Hosting.AspNetCore/EShopOnAbpSharedHostingAspNetCoreModule.cs

@ -2,17 +2,16 @@
using Volo.Abp.Modularity;
using Volo.Abp.Swashbuckle;
namespace EShopOnAbp.Shared.Hosting.AspNetCore
namespace EShopOnAbp.Shared.Hosting.AspNetCore;
[DependsOn(
typeof(EShopOnAbpSharedHostingModule),
typeof(AbpSwashbuckleModule),
typeof(AbpAspNetCoreSerilogModule)
)]
public class EShopOnAbpSharedHostingAspNetCoreModule : AbpModule
{
[DependsOn(
typeof(EShopOnAbpSharedHostingModule),
typeof(AbpSwashbuckleModule),
typeof(AbpAspNetCoreSerilogModule)
)]
public class EShopOnAbpSharedHostingAspNetCoreModule : AbpModule
public override void ConfigureServices(ServiceConfigurationContext context)
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
}
}
}

55
shared/EShopOnAbp.Shared.Hosting.AspNetCore/SerilogConfigurationHelper.cs

@ -1,40 +1,39 @@
using Serilog;
using Serilog.Events;
namespace EShopOnAbp.Shared.Hosting.AspNetCore
namespace EShopOnAbp.Shared.Hosting.AspNetCore;
public static class SerilogConfigurationHelper
{
public static class SerilogConfigurationHelper
public static void Configure(string applicationName)
{
public static void Configure(string applicationName)
{
// TODO: Uncomment following lines for ElasticSearch configuration
// var configuration = new ConfigurationBuilder()
// .SetBasePath(Directory.GetCurrentDirectory())
// .AddJsonFile("appsettings.json")
// .AddEnvironmentVariables()
// .Build();
// TODO: Uncomment following lines for ElasticSearch configuration
// var configuration = new ConfigurationBuilder()
// .SetBasePath(Directory.GetCurrentDirectory())
// .AddJsonFile("appsettings.json")
// .AddEnvironmentVariables()
// .Build();
Log.Logger = new LoggerConfiguration()
Log.Logger = new LoggerConfiguration()
#if DEBUG
.MinimumLevel.Debug()
.MinimumLevel.Debug()
#else
.MinimumLevel.Information()
#endif
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", $"{applicationName}")
.WriteTo.Async(c => c.File("Logs/logs.txt"))
// TODO: Uncomment following lines for ElasticSearch configuration
// .WriteTo.Elasticsearch(
// new ElasticsearchSinkOptions(new Uri(configuration["ElasticSearch:Url"]))
// {
// AutoRegisterTemplate = true,
// AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
// IndexFormat = "MyProjectName-log-{0:yyyy.MM}"
// })
.WriteTo.Async(c => c.Console())
.CreateLogger();
}
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", $"{applicationName}")
.WriteTo.Async(c => c.File("Logs/logs.txt"))
// TODO: Uncomment following lines for ElasticSearch configuration
// .WriteTo.Elasticsearch(
// new ElasticsearchSinkOptions(new Uri(configuration["ElasticSearch:Url"]))
// {
// AutoRegisterTemplate = true,
// AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
// IndexFormat = "MyProjectName-log-{0:yyyy.MM}"
// })
.WriteTo.Async(c => c.Console())
.CreateLogger();
}
}

55
shared/EShopOnAbp.Shared.Hosting.AspNetCore/SwaggerConfigurationHelper.cs

@ -3,40 +3,39 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Volo.Abp.Modularity;
namespace EShopOnAbp.Shared.Hosting.AspNetCore
namespace EShopOnAbp.Shared.Hosting.AspNetCore;
public static class SwaggerConfigurationHelper
{
public static class SwaggerConfigurationHelper
public static void Configure(
ServiceConfigurationContext context,
string apiTitle
)
{
public static void Configure(
ServiceConfigurationContext context,
string apiTitle
)
context.Services.AddSwaggerGen(options =>
{
context.Services.AddSwaggerGen(options =>
options.SwaggerDoc("v1", new OpenApiInfo {Title = apiTitle, Version = "v1"});
options.DocInclusionPredicate((docName, description) => true);
options.CustomSchemaIds(type => type.FullName);
});
}
public static void ConfigureWithAuth(
ServiceConfigurationContext context,
string authority,
Dictionary<string, string> scopes,
string apiTitle,
string apiVersion = "v1",
string apiName = "v1"
)
{
context.Services.AddAbpSwaggerGenWithOAuth(
authority: authority,
scopes: scopes,
options =>
{
options.SwaggerDoc("v1", new OpenApiInfo {Title = apiTitle, Version = "v1"});
options.SwaggerDoc(apiName, new OpenApiInfo { Title = apiTitle, Version = apiVersion });
options.DocInclusionPredicate((docName, description) => true);
options.CustomSchemaIds(type => type.FullName);
});
}
public static void ConfigureWithAuth(
ServiceConfigurationContext context,
string authority,
Dictionary<string, string> scopes,
string apiTitle,
string apiVersion = "v1",
string apiName = "v1"
)
{
context.Services.AddAbpSwaggerGenWithOAuth(
authority: authority,
scopes: scopes,
options =>
{
options.SwaggerDoc(apiName, new OpenApiInfo { Title = apiTitle, Version = apiVersion });
options.DocInclusionPredicate((docName, description) => true);
options.CustomSchemaIds(type => type.FullName);
});
}
}
}

7
shared/EShopOnAbp.Shared.Hosting.Microservices/DbMigrations/EfCore/DatabaseEfCoreMigrationEventHandler.cs

@ -23,7 +23,6 @@ public abstract class DatabaseEfCoreMigrationEventHandler<TDbContext> : Database
{
protected const string TryCountPropertyName = "TryCount";
protected const int MaxEventTryCount = 3;
protected ICurrentTenant CurrentTenant { get; }
protected IUnitOfWorkManager UnitOfWorkManager { get; }
protected ITenantStore TenantStore { get; }
@ -39,7 +38,7 @@ public abstract class DatabaseEfCoreMigrationEventHandler<TDbContext> : Database
IDistributedEventBus distributedEventBus,
string databaseName,
IAbpDistributedLock distributedLockProvider
)
)
{
CurrentTenant = currentTenant;
UnitOfWorkManager = unitOfWorkManager;
@ -59,7 +58,6 @@ public abstract class DatabaseEfCoreMigrationEventHandler<TDbContext> : Database
{
var result = false;
using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: false))
{
async Task<bool> MigrateDatabaseSchemaWithDbContextAsync()
@ -84,7 +82,6 @@ public abstract class DatabaseEfCoreMigrationEventHandler<TDbContext> : Database
await uow.CompleteAsync();
}
return result;
}
@ -105,7 +102,7 @@ public abstract class DatabaseEfCoreMigrationEventHandler<TDbContext> : Database
}
else
{
Log.Error(
Log.Warning(
$"Could not apply database migrations. Canceling the operation. TenantId = {eventData.TenantId}, DatabaseName = {eventData.DatabaseName}.");
Log.Error(exception.ToString());
}

7
shared/EShopOnAbp.Shared.Hosting.Microservices/DbMigrations/PendingMigrationsCheckerBase.cs

@ -1,8 +1,7 @@
using Volo.Abp.DependencyInjection;
namespace EShopOnAbp.Shared.Hosting.Microservices.DbMigrations
namespace EShopOnAbp.Shared.Hosting.Microservices.DbMigrations;
public abstract class PendingMigrationsCheckerBase : ITransientDependency
{
public abstract class PendingMigrationsCheckerBase : ITransientDependency
{
}
}

61
shared/EShopOnAbp.Shared.Hosting.Microservices/EShopOnAbpSharedHostingMicroservicesModule.cs

@ -13,43 +13,42 @@ using Volo.Abp.EventBus.RabbitMq;
using Volo.Abp.Modularity;
using Volo.Abp.MultiTenancy;
namespace EShopOnAbp.Shared.Hosting.Microservices
namespace EShopOnAbp.Shared.Hosting.Microservices;
[DependsOn(
typeof(EShopOnAbpSharedHostingAspNetCoreModule),
typeof(AbpBackgroundJobsRabbitMqModule),
typeof(AbpAspNetCoreMultiTenancyModule),
typeof(AbpEventBusRabbitMqModule),
typeof(AbpCachingStackExchangeRedisModule),
typeof(AdministrationServiceEntityFrameworkCoreModule)
)]
public class EShopOnAbpSharedHostingMicroservicesModule : AbpModule
{
[DependsOn(
typeof(EShopOnAbpSharedHostingAspNetCoreModule),
typeof(AbpBackgroundJobsRabbitMqModule),
typeof(AbpAspNetCoreMultiTenancyModule),
typeof(AbpEventBusRabbitMqModule),
typeof(AbpCachingStackExchangeRedisModule),
typeof(AdministrationServiceEntityFrameworkCoreModule)
)]
public class EShopOnAbpSharedHostingMicroservicesModule : AbpModule
public override void ConfigureServices(ServiceConfigurationContext context)
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
var configuration = context.Services.GetConfiguration();
var configuration = context.Services.GetConfiguration();
Configure<AbpMultiTenancyOptions>(options =>
{
options.IsEnabled = true;
});
Configure<AbpMultiTenancyOptions>(options =>
{
options.IsEnabled = true;
});
Configure<AbpDistributedCacheOptions>(options =>
{
options.KeyPrefix = "EShopOnAbp:";
});
Configure<AbpDistributedCacheOptions>(options =>
{
options.KeyPrefix = "EShopOnAbp:";
});
var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
context.Services
.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "EShopOnAbp-Protection-Keys");
var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
context.Services
.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "EShopOnAbp-Protection-Keys");
context.Services.AddSingleton<IDistributedLockProvider>(sp =>
{
var connection = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
return new RedisDistributedSynchronizationProvider(connection.GetDatabase());
});
}
context.Services.AddSingleton<IDistributedLockProvider>(sp =>
{
var connection = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
return new RedisDistributedSynchronizationProvider(connection.GetDatabase());
});
}
}

29
shared/EShopOnAbp.Shared.Hosting.Microservices/JwtBearerConfigurationHelper.cs

@ -3,23 +3,22 @@ using Microsoft.Extensions.DependencyInjection;
using System;
using Volo.Abp.Modularity;
namespace EShopOnAbp.Shared.Hosting.Microservices
namespace EShopOnAbp.Shared.Hosting.Microservices;
public static class JwtBearerConfigurationHelper
{
public static class JwtBearerConfigurationHelper
public static void Configure(
ServiceConfigurationContext context,
string audience)
{
public static void Configure(
ServiceConfigurationContext context,
string audience)
{
var configuration = context.Services.GetConfiguration();
var configuration = context.Services.GetConfiguration();
context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
options.Audience = audience;
});
}
context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
options.Audience = audience;
});
}
}

39
shared/EShopOnAbp.Shared.Localization/EShopOnAbpSharedLocalizationModule.cs

@ -5,30 +5,29 @@ using Volo.Abp.Validation;
using Volo.Abp.Validation.Localization;
using Volo.Abp.VirtualFileSystem;
namespace EShopOnAbp
namespace EShopOnAbp;
[DependsOn(
typeof(AbpValidationModule)
)]
public class EShopOnAbpSharedLocalizationModule : AbpModule
{
[DependsOn(
typeof(AbpValidationModule)
)]
public class EShopOnAbpSharedLocalizationModule : AbpModule
public override void ConfigureServices(ServiceConfigurationContext context)
{
public override void ConfigureServices(ServiceConfigurationContext context)
Configure<AbpVirtualFileSystemOptions>(options =>
{
Configure<AbpVirtualFileSystemOptions>(options =>
{
options.FileSets.AddEmbedded<EShopOnAbpSharedLocalizationModule>();
});
options.FileSets.AddEmbedded<EShopOnAbpSharedLocalizationModule>();
});
Configure<AbpLocalizationOptions>(options =>
{
options.Resources
.Add<EShopOnAbpResource>("en")
.AddBaseTypes(
typeof(AbpValidationResource)
).AddVirtualJson("/Localization/EShopOnAbp");
Configure<AbpLocalizationOptions>(options =>
{
options.Resources
.Add<EShopOnAbpResource>("en")
.AddBaseTypes(
typeof(AbpValidationResource)
).AddVirtualJson("/Localization/EShopOnAbp");
options.DefaultResourceType = typeof(EShopOnAbpResource);
});
}
options.DefaultResourceType = typeof(EShopOnAbpResource);
});
}
}
Loading…
Cancel
Save