From 7c0e2a1c8603917fd7d6e48a03ddad417bab2dfe Mon Sep 17 00:00:00 2001 From: eiximenis Date: Wed, 26 Jun 2019 12:58:07 +0200 Subject: [PATCH 001/113] Catalog.API gRPC support for one endpoint --- docker-compose.override.yml | 6 +- .../Catalog/Catalog.API/Catalog.API.csproj | 23 +++-- .../Catalog.API/Controllers/PicController.cs | 4 +- src/Services/Catalog/Catalog.API/Dockerfile | 7 +- .../Catalog.API/Extensions/HostExtensions.cs | 83 ++++++++++++++++ .../Catalog.API/Grpc/CatalogService.cs | 61 ++++++++++++ .../Infrastructure/CatalogContextSeed.cs | 2 +- .../Filters/HttpGlobalExceptionFilter.cs | 5 +- src/Services/Catalog/Catalog.API/Program.cs | 90 +++++++++++++++--- .../Properties/launchSettings.json | 4 +- .../Catalog/Catalog.API/Proto/catalog.proto | 36 +++++++ src/Services/Catalog/Catalog.API/Startup.cs | 39 ++++---- .../Catalog.API/appsettings.Development.json | 12 +++ .../Catalog/Catalog.API/appsettings.json | 2 + src/Services/Catalog/Catalog.API/eshop.pfx | Bin 0 -> 2565 bytes src/Services/Catalog/Catalog.API/web.config | 11 ++- 16 files changed, 332 insertions(+), 53 deletions(-) create mode 100644 src/Services/Catalog/Catalog.API/Extensions/HostExtensions.cs create mode 100644 src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs create mode 100644 src/Services/Catalog/Catalog.API/Proto/catalog.proto create mode 100644 src/Services/Catalog/Catalog.API/appsettings.Development.json create mode 100644 src/Services/Catalog/Catalog.API/eshop.pfx diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 563d712c1..77530e213 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -77,7 +77,7 @@ services: catalog.api: environment: - ASPNETCORE_ENVIRONMENT=Development - - ASPNETCORE_URLS=http://0.0.0.0:80 + - ASPNETCORE_URLS=http://0.0.0.0:80;https://0.0.0.0:443; - ConnectionString=${ESHOP_AZURE_CATALOG_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.CatalogDb;User Id=sa;Password=Pass@word} - PicBaseUrl=${ESHOP_AZURE_STORAGE_CATALOG_URL:-http://localhost:5202/api/v1/c/catalog/items/[0]/pic/} #Local: You need to open your local dev-machine firewall at range 5100-5110. - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} @@ -91,8 +91,8 @@ services: - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - OrchestratorType=${ORCHESTRATOR_TYPE} ports: - - "5101:80" # Important: In a production environment your should remove the external port (5101) kept here for microservice debugging purposes. - # The API Gateway redirects and access through the internal port (80). + - "5101:80" + - "9101:443" ordering.api: environment: diff --git a/src/Services/Catalog/Catalog.API/Catalog.API.csproj b/src/Services/Catalog/Catalog.API/Catalog.API.csproj index 6150179ee..2b66b6f0c 100644 --- a/src/Services/Catalog/Catalog.API/Catalog.API.csproj +++ b/src/Services/Catalog/Catalog.API/Catalog.API.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + netcoreapp3.0 portable true Catalog.API @@ -32,8 +32,18 @@ + + + + + + + + + + @@ -43,18 +53,16 @@ - - - - + + - + - + @@ -63,7 +71,6 @@ - diff --git a/src/Services/Catalog/Catalog.API/Controllers/PicController.cs b/src/Services/Catalog/Catalog.API/Controllers/PicController.cs index 7d798597e..0aa376832 100644 --- a/src/Services/Catalog/Catalog.API/Controllers/PicController.cs +++ b/src/Services/Catalog/Catalog.API/Controllers/PicController.cs @@ -13,10 +13,10 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API.Controllers [ApiController] public class PicController : ControllerBase { - private readonly IHostingEnvironment _env; + private readonly IWebHostEnvironment _env; private readonly CatalogContext _catalogContext; - public PicController(IHostingEnvironment env, + public PicController(IWebHostEnvironment env, CatalogContext catalogContext) { _env = env; diff --git a/src/Services/Catalog/Catalog.API/Dockerfile b/src/Services/Catalog/Catalog.API/Dockerfile index facbb0ef3..d9f06d64d 100644 --- a/src/Services/Catalog/Catalog.API/Dockerfile +++ b/src/Services/Catalog/Catalog.API/Dockerfile @@ -1,8 +1,9 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 +EXPOSE 443 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ @@ -28,4 +29,6 @@ FROM build AS publish FROM base AS final WORKDIR /app COPY --from=publish /app . +COPY --from=build /src/src/Services/Catalog/Catalog.API/Proto /app/Proto +COPY --from=build /src/src/Services/Catalog/Catalog.API/eshop.pfx . ENTRYPOINT ["dotnet", "Catalog.API.dll"] diff --git a/src/Services/Catalog/Catalog.API/Extensions/HostExtensions.cs b/src/Services/Catalog/Catalog.API/Extensions/HostExtensions.cs new file mode 100644 index 000000000..cfa7e9d2f --- /dev/null +++ b/src/Services/Catalog/Catalog.API/Extensions/HostExtensions.cs @@ -0,0 +1,83 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using System; +using Microsoft.Extensions.DependencyInjection; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Polly; +using System.Data.SqlClient; + +namespace Catalog.API.Extensions +{ + public static class HostExtensions + { + public static bool IsInKubernetes(this IHost host) + { + var cfg = host.Services.GetService(); + var orchestratorType = cfg.GetValue("OrchestratorType"); + return orchestratorType?.ToUpper() == "K8S"; + } + + public static IHost MigrateDbContext(this IHost host, Action seeder) where TContext : DbContext + { + var underK8s = host.IsInKubernetes(); + + using (var scope = host.Services.CreateScope()) + { + var services = scope.ServiceProvider; + + var logger = services.GetRequiredService>(); + + var context = services.GetService(); + + try + { + logger.LogInformation("Migrating database associated with context {DbContextName}", typeof(TContext).Name); + + if (underK8s) + { + InvokeSeeder(seeder, context, services); + } + else + { + var retry = Policy.Handle() + .WaitAndRetry(new TimeSpan[] + { + TimeSpan.FromSeconds(3), + TimeSpan.FromSeconds(5), + TimeSpan.FromSeconds(8), + }); + + //if the sql server container is not created on run docker compose this + //migration can't fail for network related exception. The retry options for DbContext only + //apply to transient exceptions + // Note that this is NOT applied when running some orchestrators (let the orchestrator to recreate the failing service) + retry.Execute(() => InvokeSeeder(seeder, context, services)); + } + + logger.LogInformation("Migrated database associated with context {DbContextName}", typeof(TContext).Name); + } + catch (Exception ex) + { + logger.LogError(ex, "An error occurred while migrating the database used on context {DbContextName}", typeof(TContext).Name); + if (underK8s) + { + throw; // Rethrow under k8s because we rely on k8s to re-run the pod + } + } + } + + return host; + } + + private static void InvokeSeeder(Action seeder, TContext context, IServiceProvider services) + where TContext : DbContext + { + context.Database.Migrate(); + seeder(context, services); + } + } +} diff --git a/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs b/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs new file mode 100644 index 000000000..940a63c3b --- /dev/null +++ b/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using CatalogApi; +using Grpc.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.eShopOnContainers.Services.Catalog.API; +using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure; +using Microsoft.eShopOnContainers.Services.Catalog.API.Model; +using Microsoft.Extensions.Options; +using static CatalogApi.Catalog; + +namespace Catalog.API.Grpc +{ + public class CatalogService : CatalogBase + { + private readonly CatalogContext _catalogContext; + private readonly CatalogSettings _settings; + public CatalogService(CatalogContext dbContext, IOptions settings) + { + _settings = settings.Value; + _catalogContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); + } + + public override async Task GetItemById(CatalogItemRequest request, ServerCallContext context) + { + + if (request.Id <=0) + { + context.Status = new Status(StatusCode.FailedPrecondition, $"Id must be > 0 (received {request.Id})"); + return null; + } + + var item = await _catalogContext.CatalogItems.SingleOrDefaultAsync(ci => ci.Id == request.Id); + var baseUri = _settings.PicBaseUrl; + var azureStorageEnabled = _settings.AzureStorageEnabled; + item.FillProductUrl(baseUri, azureStorageEnabled: azureStorageEnabled); + + if (item != null) + { + return new CatalogItemResponse() + { + AvailableStock = item.AvailableStock, + Description = item.Description, + Id = item.Id, + MaxStockThreshold = item.MaxStockThreshold, + Name = item.Name, + OnReorder = item.OnReorder, + PictureFileName = item.PictureFileName, + PictureUri = item.PictureUri, + Price = (double)item.Price, + RestockThreshold = item.RestockThreshold + }; + } + + context.Status = new Status(StatusCode.NotFound, $"Product with id {request.Id} do not exist"); + return null; + } + } +} diff --git a/src/Services/Catalog/Catalog.API/Infrastructure/CatalogContextSeed.cs b/src/Services/Catalog/Catalog.API/Infrastructure/CatalogContextSeed.cs index 8bdd2a401..ab88002ce 100644 --- a/src/Services/Catalog/Catalog.API/Infrastructure/CatalogContextSeed.cs +++ b/src/Services/Catalog/Catalog.API/Infrastructure/CatalogContextSeed.cs @@ -18,7 +18,7 @@ public class CatalogContextSeed { - public async Task SeedAsync(CatalogContext context,IHostingEnvironment env,IOptions settings,ILogger logger) + public async Task SeedAsync(CatalogContext context,IWebHostEnvironment env,IOptions settings,ILogger logger) { var policy = CreatePolicy(logger, nameof(CatalogContextSeed)); diff --git a/src/Services/Catalog/Catalog.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs b/src/Services/Catalog/Catalog.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs index 1c1dfd45f..5ddb81d63 100644 --- a/src/Services/Catalog/Catalog.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs +++ b/src/Services/Catalog/Catalog.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Net; @@ -11,10 +12,10 @@ namespace Catalog.API.Infrastructure.Filters { public class HttpGlobalExceptionFilter : IExceptionFilter { - private readonly IHostingEnvironment env; + private readonly IWebHostEnvironment env; private readonly ILogger logger; - public HttpGlobalExceptionFilter(IHostingEnvironment env, ILogger logger) + public HttpGlobalExceptionFilter(IWebHostEnvironment env, ILogger logger) { this.env = env; this.logger = logger; diff --git a/src/Services/Catalog/Catalog.API/Program.cs b/src/Services/Catalog/Catalog.API/Program.cs index 39b071c46..3cd36a451 100644 --- a/src/Services/Catalog/Catalog.API/Program.cs +++ b/src/Services/Catalog/Catalog.API/Program.cs @@ -1,14 +1,21 @@ -using Microsoft.AspNetCore; +using Autofac.Extensions.DependencyInjection; +using Catalog.API.Extensions; +using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF; using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Serilog; using System; +using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Net; namespace Microsoft.eShopOnContainers.Services.Catalog.API { @@ -26,12 +33,12 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API try { Log.Information("Configuring web host ({ApplicationContext})...", AppName); - var host = BuildWebHost(configuration, args); + var host = CreateHostBuilder(configuration, args).Build(); Log.Information("Applying migrations ({ApplicationContext})...", AppName); host.MigrateDbContext((context, services) => { - var env = services.GetService(); + var env = services.GetService(); var settings = services.GetService>(); var logger = services.GetService>(); @@ -57,16 +64,37 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API } } - private static IWebHost BuildWebHost(IConfiguration configuration, string[] args) => - WebHost.CreateDefaultBuilder(args) - .CaptureStartupErrors(false) - .UseStartup() - .UseApplicationInsights() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseWebRoot("Pics") - .UseConfiguration(configuration) - .UseSerilog() - .Build(); + + private static IHostBuilder CreateHostBuilder(IConfiguration configuration, string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureServices(services => services.AddAutofac()) + .UseServiceProviderFactory(new AutofacServiceProviderFactory()) + .ConfigureWebHostDefaults(builder => + { + builder.CaptureStartupErrors(false) + .UseConfiguration(configuration) + .ConfigureKestrel(options => + { + var ports = GetDefinedPorts(configuration); + foreach (var port in ports.Distinct()) + { + options.ListenAnyIP(port.portNumber, listenOptions => + { + Console.WriteLine($"Binding to port {port.portNumber} (https is {port.https})"); + if (port.https) + { + listenOptions.UseHttps("eshop.pfx"); + listenOptions.Protocols = HttpProtocols.Http1AndHttp2; + } + }); + } + }) + .UseStartup() + .UseApplicationInsights() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseWebRoot("Pics") + .UseSerilog(); + }); private static Serilog.ILogger CreateSerilogLogger(IConfiguration configuration) { @@ -83,6 +111,40 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API .CreateLogger(); } + private static IEnumerable<(int portNumber, bool https)> GetDefinedPorts(IConfiguration config) + { + const string https = "https://"; + const string http = "http://"; + var defport = config.GetValue("ASPNETCORE_HTTPS_PORT", 0); + if (defport != 0) + { + yield return (defport, true); + } + + var urls = config.GetValue("ASPNETCORE_URLS", null)?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + if (urls?.Any() == true) + { + foreach (var urlString in urls) + { + var uri = urlString.ToLowerInvariant().Trim(); + var isHttps = uri.StartsWith(https); + var isHttp = uri.StartsWith(http); + if (!isHttp && !isHttps) + { + throw new ArgumentException($"Url {uri} must start with https:// or http://"); + } + + uri = uri.Substring(isHttps ? https.Length : http.Length); + var lastdots = uri.LastIndexOf(':'); + if (lastdots != -1) + { + var sport = uri.Substring(lastdots + 1); + yield return (int.TryParse(sport, out var nport) ? nport : isHttps ? 443 : 80, isHttps); + } + } + } + } + private static IConfiguration GetConfiguration() { var builder = new ConfigurationBuilder() @@ -103,4 +165,4 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API return builder.Build(); } } -} \ No newline at end of file +} diff --git a/src/Services/Catalog/Catalog.API/Properties/launchSettings.json b/src/Services/Catalog/Catalog.API/Properties/launchSettings.json index f842f80d0..a29630269 100644 --- a/src/Services/Catalog/Catalog.API/Properties/launchSettings.json +++ b/src/Services/Catalog/Catalog.API/Properties/launchSettings.json @@ -14,10 +14,10 @@ "launchUrl": "/swagger", "environmentVariables": { "ConnectionString": "server=localhost,5433;Database=Microsoft.eShopOnContainers.Services.CatalogDb;User Id=sa;Password=Pass@word", + "Serilog:LogstashgUrl": "http://locahost:8080", "ASPNETCORE_ENVIRONMENT": "Development", "EventBusConnection": "localhost", - "Serilog:SeqServerUrl": "http://locahost:5340", - "Serilog:LogstashgUrl":"http://locahost:8080", + "Serilog:SeqServerUrl": "http://locahost:5340" } }, "Microsoft.eShopOnContainers.Services.Catalog.API": { diff --git a/src/Services/Catalog/Catalog.API/Proto/catalog.proto b/src/Services/Catalog/Catalog.API/Proto/catalog.proto new file mode 100644 index 000000000..cee230070 --- /dev/null +++ b/src/Services/Catalog/Catalog.API/Proto/catalog.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; + +package CatalogApi; + +message CatalogItemRequest { + int32 id = 1; +} + +message CatalogItemResponse { + int32 id = 1; + string name = 2; + string description=3; + double price=4; + string picture_file_name=5; + string picture_uri=6; + CatalogType catalog_type=8; + CatalogBrand catalog_brand=10; + int32 available_stock=11; + int32 restock_threshold=12; + int32 max_stock_threshold=13; + bool on_reorder=14; +} + +message CatalogBrand { + int32 id = 1; + string name = 2; +} + +message CatalogType { + int32 id = 1; + string type = 2; +} + +service Catalog { + rpc GetItemById (CatalogItemRequest) returns (CatalogItemResponse) {} +} \ No newline at end of file diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 1a51a86fb..f81492c24 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -3,7 +3,6 @@ using Autofac.Extensions.DependencyInjection; using global::Catalog.API.Infrastructure.Filters; using global::Catalog.API.IntegrationEvents; using Microsoft.ApplicationInsights.Extensibility; -using Microsoft.ApplicationInsights.ServiceFabric; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; @@ -31,6 +30,8 @@ using System.Reflection; using HealthChecks.UI.Client; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; +using Catalog.API.Grpc; +using System.IO; namespace Microsoft.eShopOnContainers.Services.Catalog.API { @@ -43,9 +44,10 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API public IConfiguration Configuration { get; } - public IServiceProvider ConfigureServices(IServiceCollection services) + public void ConfigureServices(IServiceCollection services) { services.AddAppInsight(Configuration) + .AddGrpc().Services .AddCustomMVC(Configuration) .AddCustomDbContext(Configuration) .AddCustomOptions(Configuration) @@ -56,11 +58,10 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API var container = new ContainerBuilder(); container.Populate(services); - return new AutofacServiceProvider(container.Build()); } - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { //Configure logs @@ -88,7 +89,18 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API app.UseCors("CorsPolicy"); - app.UseMvcWithDefaultRoute(); + app.UseRouting(); + app.UseEndpoints(e => + { + e.MapDefaultControllerRoute(); + e.MapGet("/_proto/", async ctx => + { + var data = await File.ReadAllTextAsync(Path.Combine(env.ContentRootPath, "Proto", "catalog.proto")); + ctx.Response.ContentType = "text/plain"; + await ctx.Response.WriteAsync(data); + }); + e.MapGrpcService(); + }); app.UseSwagger() .UseSwaggerUI(c => @@ -119,23 +131,17 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API // Enable K8s telemetry initializer services.AddApplicationInsightsKubernetesEnricher(); } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } return services; } public static IServiceCollection AddCustomMVC(this IServiceCollection services, IConfiguration configuration) - { + { services.AddMvc(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }) - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); services.AddCors(options => @@ -166,7 +172,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API tags: new string[] { "catalogdb" }); if (!string.IsNullOrEmpty(accountName) && !string.IsNullOrEmpty(accountKey)) - { + { hcBuilder .AddAzureBlobStorage( $"DefaultEndpointsProtocol=https;AccountName={accountName};AccountKey={accountKey};EndpointSuffix=core.windows.net", @@ -256,12 +262,11 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info + options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo { Title = "eShopOnContainers - Catalog HTTP API", Version = "v1", - Description = "The Catalog Microservice HTTP API. This is a Data-Driven/CRUD microservice sample", - TermsOfService = "Terms Of Service" + Description = "The Catalog Microservice HTTP API. This is a Data-Driven/CRUD microservice sample" }); }); diff --git a/src/Services/Catalog/Catalog.API/appsettings.Development.json b/src/Services/Catalog/Catalog.API/appsettings.Development.json new file mode 100644 index 000000000..9d8370a39 --- /dev/null +++ b/src/Services/Catalog/Catalog.API/appsettings.Development.json @@ -0,0 +1,12 @@ +{ + "Serilog": { + "MinimumLevel": { + "Default": "Debug", + "Override": { + "Microsoft": "Warning", + "Microsoft.eShopOnContainers": "Debug", + "System": "Warning" + } + } + } +} \ No newline at end of file diff --git a/src/Services/Catalog/Catalog.API/appsettings.json b/src/Services/Catalog/Catalog.API/appsettings.json index cc7b1b1fb..cc450f89d 100644 --- a/src/Services/Catalog/Catalog.API/appsettings.json +++ b/src/Services/Catalog/Catalog.API/appsettings.json @@ -20,6 +20,7 @@ "ApplicationInsights": { "InstrumentationKey": "" }, + "EventBusConnection": "localhost", "EventBusRetryCount": 5, "UseVault": false, "Vault": { @@ -28,3 +29,4 @@ "ClientSecret": "your-client-secret" } } + \ No newline at end of file diff --git a/src/Services/Catalog/Catalog.API/eshop.pfx b/src/Services/Catalog/Catalog.API/eshop.pfx new file mode 100644 index 0000000000000000000000000000000000000000..8af82972f220725974b9943338a024eefb6ff3db GIT binary patch literal 2565 zcmY+^c{CJ?9tZHj7(-0RHnwbKsbTEhETOTEHS5?3!$jm-vW_MuGZ`A&FpM{<8)X+?~mX4o%8*k^ZoM!$MLYSvvI(2+`S-f6}$z0pO1}; zjgI4P1md{sPUC7g4v7A{0?~0mx6{apoegmMZ2oT8;F2Joe=qQ|f#47zSRPsVO;PeZ zoShvENWlSR8oU+5OEy(nM?NG%Z#v87&IQ^v?EU`IH%btw+Jcl<->&DlIPkhpE^{$? zTK?xJ6ebfSz#)5LpivV1v)MOtv%F-M+2u!DJvi|5*t(ck?_bhirrCOFI%A?{>QEGV z{%PulS2OOHW##5IQ|4Xbtpu}|Wir|XH|M3)ayk~m^F3>IT#v)GWd0-oImlOAFd@(p zmVI<`PvX9RnTF+g%qE-?cu$qpnt8B<5FC5{R>Z-^w#qZ%K@72O|3tkl>}&fVjzg{9 zS&%FgQw?Ky>!(p@Gndc>2Gj(NjLz(j>kkJt>P^u2WuM)*N+bqqY;ms^6SD)TZnOX% zNMHhGhK~Uawvh@El6-CIl>Mpay4fznd08*RN`<0@U<#M1W{L9|yxZO6tf%q8EVJ)R#Oz!wwgH2rNIF zbM(Mj$D_ZfeKRx*XcjrEKzH#h5Jp^cZFAmW#~&A7m%TEV0)zM(PFBwK z_JRD+Pd`zr3q;nctOCt8$VP)x{x3Ses?D%N+Oa+{<@PBjjd5rqD2W60FtrNJFI2js zaHD=AD}MNbLkcRf-e~1j9eG~tdJ4a;i5!%WPx3ow{L{IUBjTjdmdoJI4v+0ce)uCH*hcTTqFMRL42OW>{!iVSA@sF{#&p8Ma)0uVH{;Kh0H~QF!?XPZ-!8tU z1!?mPX0~@-Hp@h6HCg{wGd|Svn~CX)rrhn&*6mt;1zw~V))O>o@gCv6%Y-q{!3(+K z1 zlXLcTSm6CMAw#LOQt_`+qNx#MMXyz)&4807#XrON@l8ScZ$*gdI?SDLUiT3x$0_`g zcfh?EeCzN;4>d#5Qv*U_k=G8FWL3?zuhw%fRw`wog81}SZW;Daslt2s0})N8>5pPb z=4w?RT(pJG)-d@`w@QZTwxE+${v9M1ePT6RNU^!8Lm=$I13gwym{LY@zDg|W_Rh)G zXvy`AFM$cP!p0~_;(U`*wHb*#+_rSTVT^XD|MA5GB_W3wT=~{eorx(MSDi=61`;)# z7~RsQ_w2?=E^j|*`i$O_vbH!?h|~CgK%wI}HGnuy)zetz^e%$V{D+rQvrZk_It7UJ zf9i1jrA~oOgj8&79riDEfH+{^c)as#V-t%8!4U#mkYdWX1ZELjrAh1@kse%Y9WsP3 ztNGI_2#c+vUBMoVW!M?5+RP%+Z<0WmT-A-J7vb92P4bnDGS~Ig1tSDKS1P7~dYA|v zjuSg`G-AipszKLEZY3;>*NEEfAQCixY6peA!2^bpses9zycoT(uG%_fKu2J7R9Dsd8OV~~>yH8S7;(WU3b9IGxsHgAFg&vX?cj}*NdD7ed(;9i>9Iss= zwj;wXhl`@YiiHF7m!*#^Ve>hEQm2U3IR|vJ^heepSKGpUbIjcnRCvxB>SdtEljq-a z-7|92c9d^Cf4XSkIb$3NFNm;oY7G9xT^*@rmAf$~72*`)ABqpc(~}LilrwsE5^F1| z1G!kAhGK*p>muU|9UB_j=lkTG)mY1GG0yIt$^+e0ifUOlQZHwx1BQov?N*Z~$IFvE z))d}Vk(Rpa`q##DY5e8~Y2NktExm(3zORH3zN=c;zL+53yP4fG9PX(L?deJ*zt)+w*A(-R)qQE4 zhK4Y=Zh}s=#Py2IkshQ{7rfQuCO88VS1SDkL+mH=n;s1B>UFBBzalc%O+?-F^Tbw> zS$q_)GlBkcx0b~kotntOowupx&y{00{c}Ehyc^S6;=<1!{-N#S!?SK$kyl-`xpdXo zORdUDsbw|qc#aRoCSK15f}Fz=N#c$_NJtd#f+3A)8&Rv}VG}we>&ev9f0e#Wn%G>D z1*vU>a*8F>zgJ9_sVoYRKQcEfS;x?=X`Y3LZ<4m?UstEdLkbM+azVgz%RCaCSNk`{uB(Pa? z&#=yZW|>i{I5}hI#~(b*6MbCuBzFq@E3cIBsA36!gS=vnctm}8ukAd3Xf@U+Qu0kw zQ7l6&Lb#-KsP-3Y8i2b>g`UVD_r(T$N(I&R@jIUcvu`54K@z>|_KY7D(T2A^Ynw01 zW^W>)z$ZnwwqrfYFEd9M>3;TVKCaSgYXx2#+rwAxYQ0~_ji*2I|8P(*-&cIillgE# zqCNahezb%9bg404ghqsfV1Kk_^xzEupQ5E~E(w{W`459QX;lZhl|@w;AV}d=10@n_ zVqzrXJU(9|qb#?Ojjw#T#@S&7vUB|=jYBJA^Jyu5X-CciySqgLFsOET-tZN}(gyDr z?g;~K)r#WQUUd~;t>Wc9(n~US_8l4kFbKOs`q54H&MaDUf0fx0##_p^6&HxogsEcU z{l_pu^Nj7s;OR)mtj{$G;pq84mq&pmw<~X5a&7lObu-wYM~|t4)uUPwWJMW4@LD{p z;IT-k(XS#WERub>C(EWZ5#a%pZ43JW`OmnB~AtjI> z!99V{8{g6w37<5Wj&x;YVN&lif2_6))#=||rAa&F^goyqh=7px)Gxs0|EnXnu(}9P z$W020P<5P0Qww`_+8XS0-G849SBJ~Oxj~$lARO%CoB*KEb=f;VvY;L;usan~9{efp VChJlW5Iir_?L+PVQuddU{{l^PwHW{a literal 0 HcmV?d00001 diff --git a/src/Services/Catalog/Catalog.API/web.config b/src/Services/Catalog/Catalog.API/web.config index 2157aef31..6da4550d8 100644 --- a/src/Services/Catalog/Catalog.API/web.config +++ b/src/Services/Catalog/Catalog.API/web.config @@ -4,8 +4,15 @@ - - + + + + + + + + + \ No newline at end of file From db00159347c4a7a0735b983f0b1a822816880c12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ram=C3=B3n=20Tom=C3=A1s?= Date: Thu, 27 Jun 2019 11:15:24 +0200 Subject: [PATCH 002/113] Added envoy + config grpc json transcoder --- docker-compose.override.yml | 11 +++- docker-compose.yml | 8 ++- eShopOnContainers-ServicesAndWebApps.sln | 21 ++++++- src/ApiGateways/Envoy/Dockerfile | 1 + src/ApiGateways/Envoy/config/catalog.proto | 42 +++++++++++++ .../Envoy/config/catalog.proto-descriptor.pb | Bin 0 -> 9348 bytes src/ApiGateways/Envoy/config/envoy.yaml | 56 ++++++++++++++++++ .../Web.Bff.Shopping/apigw/configuration.json | 4 +- .../Catalog/Catalog.API/Catalog.API.csproj | 1 - src/Services/Catalog/Catalog.API/Program.cs | 20 +++---- 10 files changed, 142 insertions(+), 22 deletions(-) create mode 100644 src/ApiGateways/Envoy/Dockerfile create mode 100644 src/ApiGateways/Envoy/config/catalog.proto create mode 100644 src/ApiGateways/Envoy/config/catalog.proto-descriptor.pb create mode 100644 src/ApiGateways/Envoy/config/envoy.yaml diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 77530e213..c36cd2b3a 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -77,7 +77,6 @@ services: catalog.api: environment: - ASPNETCORE_ENVIRONMENT=Development - - ASPNETCORE_URLS=http://0.0.0.0:80;https://0.0.0.0:443; - ConnectionString=${ESHOP_AZURE_CATALOG_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.CatalogDb;User Id=sa;Password=Pass@word} - PicBaseUrl=${ESHOP_AZURE_STORAGE_CATALOG_URL:-http://localhost:5202/api/v1/c/catalog/items/[0]/pic/} #Local: You need to open your local dev-machine firewall at range 5100-5110. - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} @@ -92,7 +91,7 @@ services: - OrchestratorType=${ORCHESTRATOR_TYPE} ports: - "5101:80" - - "9101:443" + - "9101:81" ordering.api: environment: @@ -415,4 +414,10 @@ services: - WebhooksUrl=http://webhooks.api - SelfUrl=http://webhooks.client/ ports: - - "5114:80" \ No newline at end of file + - "5114:80" + + envoy: + volumes: + - ./src/ApiGateways/Envoy/config:/etc/envoy + ports: + - "51051:51051" \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 11839c8b8..3b2f4f77d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -237,4 +237,10 @@ services: context: . dockerfile: src/Web/WebhookClient/Dockerfile depends_on: - - webhooks.api \ No newline at end of file + - webhooks.api + + envoy: + image: envoy:v1 + build: + context: src/ApiGateways/Envoy + dockerfile: Dockerfile \ No newline at end of file diff --git a/eShopOnContainers-ServicesAndWebApps.sln b/eShopOnContainers-ServicesAndWebApps.sln index 882bca09f..4bf2fa51d 100644 --- a/eShopOnContainers-ServicesAndWebApps.sln +++ b/eShopOnContainers-ServicesAndWebApps.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27130.2027 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29020.237 MinimumVisualStudioVersion = 10.0.40219.1 Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{FEA0C318-FFED-4D39-8781-265718CA43DD}" EndProject @@ -148,7 +148,20 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebhookClient", "src\Web\We EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Devspace.Support", "Devspace.Support", "{68F5041D-51F2-4630-94B6-B49789F5E51A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Devspaces.Support", "src\BuildingBlocks\Devspaces.Support\Devspaces.Support.csproj", "{56C2EF0B-6BF2-41D9-BE07-6E6D08D06B35}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Devspaces.Support", "src\BuildingBlocks\Devspaces.Support\Devspaces.Support.csproj", "{56C2EF0B-6BF2-41D9-BE07-6E6D08D06B35}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Envoy", "Envoy", "{882A8F3A-C61F-4C44-86DD-A5A258714BF2}" + ProjectSection(SolutionItems) = preProject + src\ApiGateways\Envoy\Dockerfile = src\ApiGateways\Envoy\Dockerfile + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "config", "config", "{3ABEEE8C-35E0-4185-9825-C44326151F5B}" + ProjectSection(SolutionItems) = preProject + src\ApiGateways\Envoy\config\catalog.proto = src\ApiGateways\Envoy\config\catalog.proto + src\ApiGateways\Envoy\config\catalog.proto-descriptor.pb = src\ApiGateways\Envoy\config\catalog.proto-descriptor.pb + src\ApiGateways\Envoy\Dockerfile = src\ApiGateways\Envoy\Dockerfile + src\ApiGateways\Envoy\config\envoy.yaml = src\ApiGateways\Envoy\config\envoy.yaml + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -1862,6 +1875,8 @@ Global {766D7E92-6AF0-476C-ADD5-282BF4D8C576} = {E279BF0F-7F66-4F3A-A3AB-2CDA66C1CD04} {68F5041D-51F2-4630-94B6-B49789F5E51A} = {DB0EFB20-B024-4E5E-A75C-52143C131D25} {56C2EF0B-6BF2-41D9-BE07-6E6D08D06B35} = {68F5041D-51F2-4630-94B6-B49789F5E51A} + {882A8F3A-C61F-4C44-86DD-A5A258714BF2} = {77849D35-37D4-4802-81DC-9477B2775A40} + {3ABEEE8C-35E0-4185-9825-C44326151F5B} = {882A8F3A-C61F-4C44-86DD-A5A258714BF2} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {25728519-5F0F-4973-8A64-0A81EB4EA8D9} diff --git a/src/ApiGateways/Envoy/Dockerfile b/src/ApiGateways/Envoy/Dockerfile new file mode 100644 index 000000000..0f714330f --- /dev/null +++ b/src/ApiGateways/Envoy/Dockerfile @@ -0,0 +1 @@ +FROM envoyproxy/envoy \ No newline at end of file diff --git a/src/ApiGateways/Envoy/config/catalog.proto b/src/ApiGateways/Envoy/config/catalog.proto new file mode 100644 index 000000000..5fda69526 --- /dev/null +++ b/src/ApiGateways/Envoy/config/catalog.proto @@ -0,0 +1,42 @@ +syntax = "proto3"; + +package CatalogApi; + +import "google/api/annotations.proto"; + +message CatalogItemRequest { + int32 id = 1; +} + +message CatalogItemResponse { + int32 id = 1; + string name = 2; + string description=3; + double price=4; + string picture_file_name=5; + string picture_uri=6; + CatalogType catalog_type=8; + CatalogBrand catalog_brand=10; + int32 available_stock=11; + int32 restock_threshold=12; + int32 max_stock_threshold=13; + bool on_reorder=14; +} + +message CatalogBrand { + int32 id = 1; + string name = 2; +} + +message CatalogType { + int32 id = 1; + string type = 2; +} + +service Catalog { + rpc GetItemById (CatalogItemRequest) returns (CatalogItemResponse) { + option (google.api.http) = { + get: "/api/v1/catalog/items/{id}" + }; + } +} \ No newline at end of file diff --git a/src/ApiGateways/Envoy/config/catalog.proto-descriptor.pb b/src/ApiGateways/Envoy/config/catalog.proto-descriptor.pb new file mode 100644 index 0000000000000000000000000000000000000000..7c94ce9f05ec461731aea1a9659446fde3810e23 GIT binary patch literal 9348 zcmc&4O>ZMvaqZZN{hTjiCJ=p z`qitdSFc`Gy{cCx-^-J8eb?>Ve8U)88z(_9tPVXla4C`CDuC5flDh>n^cu-~Bb)n` z%;mYOrP^9`j8jDf29r#pP>ozV9@+M(-s7g*Ck3C|+zea~M95q%vUp4>nd|dF@GRbXjNt%b!%#n9QlDes1#tLRC_Y1 zjHZ}DxjRM>aL<9&Lv#=-cjWd?D+|bviEmKWs?qCN0cgdr^&`vaSx(=tls-kxbWG3) z@f$_50J7qG>P@ne5(1aL3%H@~#5cl#=0qxviSNc8Qa0T|VndCh*b5p)C-YuCJodh8 z8&1FKdi{+)cZAt&$SE)yUl^3(IBsCzzWkes?|)}9zsTlx>Ydinyr6r9{PZTdEQvP+ zMk16rwHlsA$NM*F;Btz=HQ$Y5c(on8IF!@ z%LLzu(FmaBnIb2)VmQ4*mhW@pZW0yEBG1YQP9QeP;(+@;$fF0RLkY=rdf>X=<8&`9SX|}J@n!X7B+8792Ozd7Eye6D3KTnpYB%f(wH%a~&cL@fDiaetZ zB+aA}VanthS zQfpOKj~M;8^+7ERC_)p?j+~weXrjjOA{M7>(c7C$hn!U={sa? zvegL|5_qjx_}7B+ZTQQoKb|LRvjWdd_XYQd zpm@YRk%8n{ID#OXw~ZriiyWj}doiWESu0d`k%UP~`XZJ*@1q~utz*hV-`c;*AYf9k&^T(NH+Kb z5k2!vI$8@MxcnX8bt2OgnH&Pd@;AoDHI-T=Zg7Z-(>A64E=zK_N4iW(2k&+?eXD)g z*wvH_EfXRD+q>=hfs&2Kt^I@7UsdK}f#MaiJ`j_O4Qhd3Fz2Ykx;6#yode`>>;sn8Tjd?bdfRr4(Z{-aXK|%3{m{#eyZ4;w7~G z!#$-;SIClBvAd080mkwa2qaZvE?voGWdZ;gRBe*Hur9FT@@~DM?dt8$L94xA-v!;p zFs6O&u*I}3&|d=9(dq{Pn^R4)HY-lf^o+z2V-b+Zp5r4Hyi!N}k1Sc8k$%ivyHsuf5l2N-(u}6#Q_v>~u^cExWlDt#E3%@1 zh~S06a}>n$C<~Mi5+o4b7%LTv*i!AOlv1TI({j=;5XH1D?gY9Yc-$C3ktyok!e;*1 zuzk*!<#aciMG7Cwb}vDJ*TtAZPRA7L4~wLPB~-XLeVQ!ZG42_9R4d66s)VqPET3SJ zHGu+qgoRAo@O_c9VDv9CigRt8YDP2kHL@xw25=8qL!0YZ@A(yylxzht_Cf@d$cJq2 zNkInHD))?l>-_x@>{~aSo_=EZCzUm1(8yLY>~Tcg3Gp<6R(E>00Eupr^MVWL5EQ7J zC)~WNkAmYjDo-TW7ZQSA0H=v4hk!x5WYL9!V_)3#VC;ttRWtzI!GnAZoUQnC)6(uR`ifM|?T4reD zKKR4Av9gkcD@j7J%V|AvLe#&{kwsCc;4#7b9+ovG))1n2EZ3e%-AYO9Y7_6W z&3Ty}Gf9aLCg3=C!HI?TSU93PWd4pXc;n?$uBD5)3EsE6f_d?FSKn{5z4|T-$?4-H zXB!`!PTqO~bk;)v4*2jkdDjTgqdNk1gXD$2C?TQ7l*ed+2+ef!&qGZ0XBkos zulm{IJ^gNdXz?<}ea8tKQvi504?G2Jeb zZLYSqw7pLIK-+J=s~_&awcmbwpD79U0__pHeTOL1LeUFkmRR7~t7Lh<4R<13jN10L z);#FShmUv@@bHoJvY*V6)frD<5XNP%Lsre#Q&D^dO%-#74!j#OL5jH$XvqnzV+#^` zS%k|vW_b)3MIU{MP-w?N=j$HV;qfj+#=0g4&5&@W*W`Qi$|` z4_prD1X3sQn3{!*v48+n66SxF4}H+6!;!t5y;@);%a0#6)sG-ynQSgV@lvo|$Z+AV z4Le&`Q)e?tQr!*lSxmY9=L{)CV7P8&?+@F#`9@aB$o?O~A(zAkZ4AdTo~z9b>`g*% zWH5je_GNRGEr;-C2*w^);2D-Zfh&5hOo=99DmuIe^<+Jg=j2|g0dKDNWOu|XZ{P-v7Vw& z%;Q-pM8*OAa;#nb2pVQRk%*USm52hA9DO!$o<&QE5w_FeVaJ003v2>@zG2>lUs<5z zm1A%hp%}oRS%#l_Z~|W^F7#osjSEfsaN;0>(<)gV7!M@B1p1OdUx6vXbBqr!Hqia> zxa;+xJ5&a=0`?P`1gJH#7^*@FJ!Js14px1cltLPzrWqsw)@GqC;CJmqvJjF`kCb+J zfJWCiZS}wb!-<486BfCC>7nz|6jk**fBED`*^6{t{0ijW%NwS2fej0m@Hf6`^*)S# G`SBmHwv - diff --git a/src/Services/Catalog/Catalog.API/Program.cs b/src/Services/Catalog/Catalog.API/Program.cs index 3cd36a451..73d644526 100644 --- a/src/Services/Catalog/Catalog.API/Program.cs +++ b/src/Services/Catalog/Catalog.API/Program.cs @@ -75,19 +75,15 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API .UseConfiguration(configuration) .ConfigureKestrel(options => { - var ports = GetDefinedPorts(configuration); - foreach (var port in ports.Distinct()) + options.Listen(IPAddress.Any, 80, listenOptions => { - options.ListenAnyIP(port.portNumber, listenOptions => - { - Console.WriteLine($"Binding to port {port.portNumber} (https is {port.https})"); - if (port.https) - { - listenOptions.UseHttps("eshop.pfx"); - listenOptions.Protocols = HttpProtocols.Http1AndHttp2; - } - }); - } + listenOptions.Protocols = HttpProtocols.Http1; + }); + options.Listen(IPAddress.Any, 81, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http2; + }); + }) .UseStartup() .UseApplicationInsights() From 591086956d80c9db65fbc7b117036887a1ef8d91 Mon Sep 17 00:00:00 2001 From: eiximenis Date: Thu, 27 Jun 2019 16:16:11 +0200 Subject: [PATCH 003/113] grpc poc working on k8s, using envoy as a sidecar in catalog api --- docker-compose.override.yml | 2 + docker-compose.yml | 5 +- .../apigwws/configuration-web-shopping.json | 16 ++++- .../envoycfg/_catalog.proto-descriptor.pb | Bin 0 -> 9348 bytes k8s/helm/catalog-api/envoycfg/_envoy.yaml | 56 ++++++++++++++++++ .../catalog-api/templates/deployment.yaml | 24 +++++++- k8s/helm/catalog-api/templates/envoy-cm.yaml | 16 +++++ k8s/helm/catalog-api/templates/service.yaml | 8 +++ k8s/helm/catalog-api/values.yaml | 12 +++- .../aggregator/Config/UrlsConfig.cs | 4 +- .../aggregator/Services/CatalogService.cs | 3 +- .../Catalog.API/Grpc/CatalogService.cs | 7 ++- src/Services/Catalog/Catalog.API/Program.cs | 42 +++---------- 13 files changed, 147 insertions(+), 48 deletions(-) create mode 100644 k8s/helm/catalog-api/envoycfg/_catalog.proto-descriptor.pb create mode 100644 k8s/helm/catalog-api/envoycfg/_envoy.yaml create mode 100644 k8s/helm/catalog-api/templates/envoy-cm.yaml diff --git a/docker-compose.override.yml b/docker-compose.override.yml index c36cd2b3a..11ea6138c 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -89,6 +89,8 @@ services: - AzureStorageEnabled=False - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - OrchestratorType=${ORCHESTRATOR_TYPE} + - GRPC_PORT=81 + - PORT=80 ports: - "5101:80" - "9101:81" diff --git a/docker-compose.yml b/docker-compose.yml index 3b2f4f77d..243fbf2c6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -240,7 +240,4 @@ services: - webhooks.api envoy: - image: envoy:v1 - build: - context: src/ApiGateways/Envoy - dockerfile: Dockerfile \ No newline at end of file + image: envoyproxy/envoy \ No newline at end of file diff --git a/k8s/helm/apigwws/configuration-web-shopping.json b/k8s/helm/apigwws/configuration-web-shopping.json index 021056f43..208406793 100644 --- a/k8s/helm/apigwws/configuration-web-shopping.json +++ b/k8s/helm/apigwws/configuration-web-shopping.json @@ -6,12 +6,24 @@ "DownstreamHostAndPorts": [ { "Host": "catalog", - "Port": 80 + "Port": 5000 } ], "UpstreamPathTemplate": "/api/{version}/c/{everything}", "UpstreamHttpMethod": [ "GET" ] }, + { + "DownstreamPathTemplate": "/api/{version}/{everything}", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "catalog", + "Port": 80 + } + ], + "UpstreamPathTemplate": "/grpc/{version}/c/{everything}", + "UpstreamHttpMethod": [ "GET" ] + }, { "DownstreamPathTemplate": "/api/{version}/{everything}", "DownstreamScheme": "http", @@ -102,7 +114,7 @@ "DownstreamHostAndPorts": [ { "Host": "catalog", - "Port": 80 + "Port": 5000 } ], "UpstreamPathTemplate": "/catalog-api/{everything}", diff --git a/k8s/helm/catalog-api/envoycfg/_catalog.proto-descriptor.pb b/k8s/helm/catalog-api/envoycfg/_catalog.proto-descriptor.pb new file mode 100644 index 0000000000000000000000000000000000000000..7c94ce9f05ec461731aea1a9659446fde3810e23 GIT binary patch literal 9348 zcmc&4O>ZMvaqZZN{hTjiCJ=p z`qitdSFc`Gy{cCx-^-J8eb?>Ve8U)88z(_9tPVXla4C`CDuC5flDh>n^cu-~Bb)n` z%;mYOrP^9`j8jDf29r#pP>ozV9@+M(-s7g*Ck3C|+zea~M95q%vUp4>nd|dF@GRbXjNt%b!%#n9QlDes1#tLRC_Y1 zjHZ}DxjRM>aL<9&Lv#=-cjWd?D+|bviEmKWs?qCN0cgdr^&`vaSx(=tls-kxbWG3) z@f$_50J7qG>P@ne5(1aL3%H@~#5cl#=0qxviSNc8Qa0T|VndCh*b5p)C-YuCJodh8 z8&1FKdi{+)cZAt&$SE)yUl^3(IBsCzzWkes?|)}9zsTlx>Ydinyr6r9{PZTdEQvP+ zMk16rwHlsA$NM*F;Btz=HQ$Y5c(on8IF!@ z%LLzu(FmaBnIb2)VmQ4*mhW@pZW0yEBG1YQP9QeP;(+@;$fF0RLkY=rdf>X=<8&`9SX|}J@n!X7B+8792Ozd7Eye6D3KTnpYB%f(wH%a~&cL@fDiaetZ zB+aA}VanthS zQfpOKj~M;8^+7ERC_)p?j+~weXrjjOA{M7>(c7C$hn!U={sa? zvegL|5_qjx_}7B+ZTQQoKb|LRvjWdd_XYQd zpm@YRk%8n{ID#OXw~ZriiyWj}doiWESu0d`k%UP~`XZJ*@1q~utz*hV-`c;*AYf9k&^T(NH+Kb z5k2!vI$8@MxcnX8bt2OgnH&Pd@;AoDHI-T=Zg7Z-(>A64E=zK_N4iW(2k&+?eXD)g z*wvH_EfXRD+q>=hfs&2Kt^I@7UsdK}f#MaiJ`j_O4Qhd3Fz2Ykx;6#yode`>>;sn8Tjd?bdfRr4(Z{-aXK|%3{m{#eyZ4;w7~G z!#$-;SIClBvAd080mkwa2qaZvE?voGWdZ;gRBe*Hur9FT@@~DM?dt8$L94xA-v!;p zFs6O&u*I}3&|d=9(dq{Pn^R4)HY-lf^o+z2V-b+Zp5r4Hyi!N}k1Sc8k$%ivyHsuf5l2N-(u}6#Q_v>~u^cExWlDt#E3%@1 zh~S06a}>n$C<~Mi5+o4b7%LTv*i!AOlv1TI({j=;5XH1D?gY9Yc-$C3ktyok!e;*1 zuzk*!<#aciMG7Cwb}vDJ*TtAZPRA7L4~wLPB~-XLeVQ!ZG42_9R4d66s)VqPET3SJ zHGu+qgoRAo@O_c9VDv9CigRt8YDP2kHL@xw25=8qL!0YZ@A(yylxzht_Cf@d$cJq2 zNkInHD))?l>-_x@>{~aSo_=EZCzUm1(8yLY>~Tcg3Gp<6R(E>00Eupr^MVWL5EQ7J zC)~WNkAmYjDo-TW7ZQSA0H=v4hk!x5WYL9!V_)3#VC;ttRWtzI!GnAZoUQnC)6(uR`ifM|?T4reD zKKR4Av9gkcD@j7J%V|AvLe#&{kwsCc;4#7b9+ovG))1n2EZ3e%-AYO9Y7_6W z&3Ty}Gf9aLCg3=C!HI?TSU93PWd4pXc;n?$uBD5)3EsE6f_d?FSKn{5z4|T-$?4-H zXB!`!PTqO~bk;)v4*2jkdDjTgqdNk1gXD$2C?TQ7l*ed+2+ef!&qGZ0XBkos zulm{IJ^gNdXz?<}ea8tKQvi504?G2Jeb zZLYSqw7pLIK-+J=s~_&awcmbwpD79U0__pHeTOL1LeUFkmRR7~t7Lh<4R<13jN10L z);#FShmUv@@bHoJvY*V6)frD<5XNP%Lsre#Q&D^dO%-#74!j#OL5jH$XvqnzV+#^` zS%k|vW_b)3MIU{MP-w?N=j$HV;qfj+#=0g4&5&@W*W`Qi$|` z4_prD1X3sQn3{!*v48+n66SxF4}H+6!;!t5y;@);%a0#6)sG-ynQSgV@lvo|$Z+AV z4Le&`Q)e?tQr!*lSxmY9=L{)CV7P8&?+@F#`9@aB$o?O~A(zAkZ4AdTo~z9b>`g*% zWH5je_GNRGEr;-C2*w^);2D-Zfh&5hOo=99DmuIe^<+Jg=j2|g0dKDNWOu|XZ{P-v7Vw& z%;Q-pM8*OAa;#nb2pVQRk%*USm52hA9DO!$o<&QE5w_FeVaJ003v2>@zG2>lUs<5z zm1A%hp%}oRS%#l_Z~|W^F7#osjSEfsaN;0>(<)gV7!M@B1p1OdUx6vXbBqr!Hqia> zxa;+xJ5&a=0`?P`1gJH#7^*@FJ!Js14px1cltLPzrWqsw)@GqC;CJmqvJjF`kCb+J zfJWCiZS}wb!-<486BfCC>7nz|6jk**fBED`*^6{t{0ijW%NwS2fej0m@Hf6`^*)S# G`SBmHwv $"/api/v1/catalog/items/{id}"; - public static string GetItemsById(IEnumerable ids) => $"/api/v1/catalog/items?ids={string.Join(',', ids)}"; + // REST call standard must go through port 5000 + public static string GetItemsById(IEnumerable ids) => $":5000/api/v1/catalog/items?ids={string.Join(',', ids)}"; } public class BasketOperations diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs index 159e56d85..4c98c031e 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs @@ -24,7 +24,8 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services public async Task GetCatalogItemAsync(int id) { - var stringContent = await _httpClient.GetStringAsync(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id)); + var uri=_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id); + var stringContent = await _httpClient.GetStringAsync(uri); return JsonConvert.DeserializeObject(stringContent); } diff --git a/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs b/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs index 940a63c3b..97f40240f 100644 --- a/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs +++ b/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs @@ -8,6 +8,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Catalog.API; using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure; using Microsoft.eShopOnContainers.Services.Catalog.API.Model; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using static CatalogApi.Catalog; @@ -17,15 +18,17 @@ namespace Catalog.API.Grpc { private readonly CatalogContext _catalogContext; private readonly CatalogSettings _settings; - public CatalogService(CatalogContext dbContext, IOptions settings) + private readonly ILogger _logger; + public CatalogService(CatalogContext dbContext, IOptions settings, ILogger logger) { _settings = settings.Value; _catalogContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); + _logger = logger; } public override async Task GetItemById(CatalogItemRequest request, ServerCallContext context) { - + _logger.LogInformation($"Begin grpc call CatalogService.GetItemById for product id {request.Id}"); if (request.Id <=0) { context.Status = new Status(StatusCode.FailedPrecondition, $"Id must be > 0 (received {request.Id})"); diff --git a/src/Services/Catalog/Catalog.API/Program.cs b/src/Services/Catalog/Catalog.API/Program.cs index 73d644526..39f3643d8 100644 --- a/src/Services/Catalog/Catalog.API/Program.cs +++ b/src/Services/Catalog/Catalog.API/Program.cs @@ -75,11 +75,12 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API .UseConfiguration(configuration) .ConfigureKestrel(options => { - options.Listen(IPAddress.Any, 80, listenOptions => + var ports = GetDefinedPorts(configuration); + options.Listen(IPAddress.Any, ports.httpPort, listenOptions => { - listenOptions.Protocols = HttpProtocols.Http1; + listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); - options.Listen(IPAddress.Any, 81, listenOptions => + options.Listen(IPAddress.Any, ports.grpcPort, listenOptions => { listenOptions.Protocols = HttpProtocols.Http2; }); @@ -107,38 +108,11 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API .CreateLogger(); } - private static IEnumerable<(int portNumber, bool https)> GetDefinedPorts(IConfiguration config) + private static (int httpPort, int grpcPort) GetDefinedPorts(IConfiguration config) { - const string https = "https://"; - const string http = "http://"; - var defport = config.GetValue("ASPNETCORE_HTTPS_PORT", 0); - if (defport != 0) - { - yield return (defport, true); - } - - var urls = config.GetValue("ASPNETCORE_URLS", null)?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - if (urls?.Any() == true) - { - foreach (var urlString in urls) - { - var uri = urlString.ToLowerInvariant().Trim(); - var isHttps = uri.StartsWith(https); - var isHttp = uri.StartsWith(http); - if (!isHttp && !isHttps) - { - throw new ArgumentException($"Url {uri} must start with https:// or http://"); - } - - uri = uri.Substring(isHttps ? https.Length : http.Length); - var lastdots = uri.LastIndexOf(':'); - if (lastdots != -1) - { - var sport = uri.Substring(lastdots + 1); - yield return (int.TryParse(sport, out var nport) ? nport : isHttps ? 443 : 80, isHttps); - } - } - } + var grpcPort = config.GetValue("GRPC_PORT", 5001); + var port = config.GetValue("PORT", 80); + return (port, grpcPort); } private static IConfiguration GetConfiguration() From 437bdd74314b1887ce57534220dec5163572e3d9 Mon Sep 17 00:00:00 2001 From: eiximenis Date: Wed, 17 Jul 2019 18:26:20 +0200 Subject: [PATCH 004/113] Using Directory.Build.props for handling versions. Needed to start the update to net3 --- src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj | 18 ++--- .../Mobile.Shopping.HttpAggregator.csproj | 19 +++-- .../Web.Shopping.HttpAggregator.csproj | 18 ++--- .../Devspaces.Support.csproj | 8 +- .../EventBus.Tests/EventBus.Tests.csproj | 8 +- .../EventBus/EventBus/EventBus.csproj | 4 +- .../EventBusRabbitMQ/EventBusRabbitMQ.csproj | 12 +-- .../EventBusServiceBus.csproj | 10 +-- .../IntegrationEventLogEF.csproj | 12 +-- .../WebHost.Customization.csproj | 4 +- src/Directory.Build.props | 3 + .../Basket/Basket.API/Basket.API.csproj | 38 ++++----- .../Basket.FunctionalTests.csproj | 8 +- .../Basket.UnitTests/Basket.UnitTests.csproj | 8 +- .../Catalog/Catalog.API/Catalog.API.csproj | 48 +++++------ .../Catalog/Catalog.API/Proto/catalog.proto | 13 ++- src/Services/Catalog/Catalog.API/Startup.cs | 12 ++- .../Catalog.FunctionalTests.csproj | 6 +- .../Catalog.UnitTests.csproj | 8 +- .../Identity/Identity.API/Identity.API.csproj | 39 +++++---- .../Locations.API/Locations.API.csproj | 49 ++++++----- .../Locations.FunctionalTests.csproj | 6 +- .../Marketing.API/Marketing.API.csproj | 52 ++++++------ .../Marketing.FunctionalTests.csproj | 6 +- .../Ordering/Ordering.API/Ordering.API.csproj | 42 +++++----- .../Ordering.BackgroundTasks.csproj | 28 +++---- .../Ordering.Domain/Ordering.Domain.csproj | 2 +- .../Ordering.FunctionalTests.csproj | 6 +- .../Ordering.Infrastructure.csproj | 6 +- .../Ordering.SignalrHub.csproj | 34 ++++---- .../Ordering.UnitTests.csproj | 8 +- .../Payment/Payment.API/Payment.API.csproj | 34 ++++---- .../Webhooks/Webhooks.API/Webhooks.API.csproj | 20 ++--- src/Web/WebMVC/WebMVC.csproj | 36 ++++----- src/Web/WebSPA/Startup.cs | 2 +- src/Web/WebSPA/WebSPA.csproj | 22 ++--- src/Web/WebStatus/Startup.cs | 2 +- src/Web/WebStatus/WebStatus.csproj | 33 ++++---- src/Web/WebhookClient/WebhookClient.csproj | 2 +- src/_build/dependencies.props | 81 +++++++++++++++++++ .../Application.FunctionalTests.csproj | 6 +- 41 files changed, 436 insertions(+), 337 deletions(-) create mode 100644 src/Directory.Build.props create mode 100644 src/_build/dependencies.props diff --git a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj index b1b6b1db6..5db2881d5 100644 --- a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj +++ b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj @@ -1,17 +1,17 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) - - - - - - - - + + + + + + + + diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj index 1dd1ba1b6..6efbcf389 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) Mobile.Shopping.HttpAggregator Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator ..\..\..\docker-compose.dcproj @@ -12,15 +12,14 @@ - - - - - - - - - + + + + + + + + diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj index d438e4602..d71cbee45 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) Web.Shopping.HttpAggregator Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator ..\..\..\docker-compose.dcproj @@ -12,14 +12,14 @@ - - - - - - - - + + + + + + + + diff --git a/src/BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj b/src/BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj index 81a897bad..05fc111a4 100644 --- a/src/BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj +++ b/src/BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj @@ -1,11 +1,11 @@  - netstandard2.0 + $(NetStandardTargetVersion) - - - + + + diff --git a/src/BuildingBlocks/EventBus/EventBus.Tests/EventBus.Tests.csproj b/src/BuildingBlocks/EventBus/EventBus.Tests/EventBus.Tests.csproj index ce65f7da8..ef1a920e9 100644 --- a/src/BuildingBlocks/EventBus/EventBus.Tests/EventBus.Tests.csproj +++ b/src/BuildingBlocks/EventBus/EventBus.Tests/EventBus.Tests.csproj @@ -1,13 +1,13 @@  - netstandard2.0 + $(NetStandardTargetVersion) - - - + + + diff --git a/src/BuildingBlocks/EventBus/EventBus/EventBus.csproj b/src/BuildingBlocks/EventBus/EventBus/EventBus.csproj index 9704f6ff5..842e6d937 100644 --- a/src/BuildingBlocks/EventBus/EventBus/EventBus.csproj +++ b/src/BuildingBlocks/EventBus/EventBus/EventBus.csproj @@ -1,12 +1,12 @@  - netstandard2.0 + $(NetStandardTargetVersion) Microsoft.eShopOnContainers.BuildingBlocks.EventBus - + \ No newline at end of file diff --git a/src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj b/src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj index 62373d1b3..6830ac9d7 100644 --- a/src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj +++ b/src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj @@ -1,16 +1,16 @@  - netstandard2.0 + $(NetStandardTargetVersion) Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ - - - - - + + + + + diff --git a/src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj b/src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj index 3de07e329..bace8a713 100644 --- a/src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj +++ b/src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj @@ -1,15 +1,15 @@  - netstandard2.0 + $(NetStandardTargetVersion) Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus - - - - + + + + diff --git a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj index ef3463cca..c518e8e92 100644 --- a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj +++ b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj @@ -1,16 +1,16 @@  - netstandard2.0 + $(NetStandardTargetVersion) Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF - - - - - + + + + + diff --git a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj index 1d4ea7a2d..14f473643 100644 --- a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj +++ b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj @@ -1,11 +1,11 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) - + diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 000000000..b137daefc --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index d5fc0a301..a949b2636 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj @@ -13,29 +13,29 @@ - - + + - - - - - + + + + + - - + + - - - - - - - - + + + + + + + + - + diff --git a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj index 4fd8cb9ec..120bfde02 100644 --- a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj +++ b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) false @@ -19,15 +19,15 @@ - + - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj index 27a851767..95b30667e 100644 --- a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj +++ b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) false @@ -9,15 +9,15 @@ - - + + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Catalog/Catalog.API/Catalog.API.csproj b/src/Services/Catalog/Catalog.API/Catalog.API.csproj index 2d5e36507..d88c92f09 100644 --- a/src/Services/Catalog/Catalog.API/Catalog.API.csproj +++ b/src/Services/Catalog/Catalog.API/Catalog.API.csproj @@ -1,7 +1,7 @@  - netcoreapp3.0 + $(NetCoreTargetVersion) portable true Catalog.API @@ -39,30 +39,30 @@ - - - + + + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + diff --git a/src/Services/Catalog/Catalog.API/Proto/catalog.proto b/src/Services/Catalog/Catalog.API/Proto/catalog.proto index cee230070..09d9c6e38 100644 --- a/src/Services/Catalog/Catalog.API/Proto/catalog.proto +++ b/src/Services/Catalog/Catalog.API/Proto/catalog.proto @@ -1,5 +1,10 @@ syntax = "proto3"; +/* >> +import "google/api/annotations.proto"; +<< */ + + package CatalogApi; message CatalogItemRequest { @@ -32,5 +37,11 @@ message CatalogType { } service Catalog { - rpc GetItemById (CatalogItemRequest) returns (CatalogItemResponse) {} + rpc GetItemById (CatalogItemRequest) returns (CatalogItemResponse) { + /* >> + option (google.api.http) = { + get: "/api/v1/catalog/items/{id}" + }; +<< */ + } } \ No newline at end of file diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index f81492c24..69580a926 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -95,9 +95,17 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API e.MapDefaultControllerRoute(); e.MapGet("/_proto/", async ctx => { - var data = await File.ReadAllTextAsync(Path.Combine(env.ContentRootPath, "Proto", "catalog.proto")); ctx.Response.ContentType = "text/plain"; - await ctx.Response.WriteAsync(data); + using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "catalog.proto"), FileMode.Open, FileAccess.Read); + using var sr = new StreamReader(fs); + while (!sr.EndOfStream) + { + var line = await sr.ReadLineAsync(); + if (line != "/* >>" || line != "<< */") + { + await ctx.Response.WriteAsync(line); + } + } }); e.MapGrpcService(); }); diff --git a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj index 455dfb0bc..0e0ccbe7a 100644 --- a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj +++ b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) false @@ -35,9 +35,9 @@ - + - + all runtime; build; native; contentfiles; analyzers diff --git a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj index efa9d56a4..58863148d 100644 --- a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj +++ b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) false @@ -9,14 +9,14 @@ - - + + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Identity/Identity.API/Identity.API.csproj b/src/Services/Identity/Identity.API/Identity.API.csproj index 728843f71..5fe2b3a86 100644 --- a/src/Services/Identity/Identity.API/Identity.API.csproj +++ b/src/Services/Identity/Identity.API/Identity.API.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) aspnet-eShopOnContainers.Identity-90487118-103c-4ff0-b9da-e5e26f7ab0c5 ..\..\..\..\docker-compose.dcproj @@ -13,29 +13,28 @@ - - - + + + - - - - + + + - - - - + + + + - - - - - - - + + + + + + + @@ -43,7 +42,7 @@ - + diff --git a/src/Services/Location/Locations.API/Locations.API.csproj b/src/Services/Location/Locations.API/Locations.API.csproj index 6c33656e1..cd110d9de 100644 --- a/src/Services/Location/Locations.API/Locations.API.csproj +++ b/src/Services/Location/Locations.API/Locations.API.csproj @@ -1,36 +1,35 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj aspnet-Locations.API-20161122013619 - - - - - - - - - + + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj index 27898f504..645c294f8 100644 --- a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj +++ b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) false @@ -19,9 +19,9 @@ - + - + all runtime; build; native; contentfiles; analyzers diff --git a/src/Services/Marketing/Marketing.API/Marketing.API.csproj b/src/Services/Marketing/Marketing.API/Marketing.API.csproj index c47989611..2409caf49 100644 --- a/src/Services/Marketing/Marketing.API/Marketing.API.csproj +++ b/src/Services/Marketing/Marketing.API/Marketing.API.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj Microsoft.eShopOnContainers.Services.Marketing.API $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; @@ -20,33 +20,33 @@ - - - - - - - - - - + + + + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj b/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj index eaedddbd5..2ecf7e8ea 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj +++ b/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) false @@ -19,9 +19,9 @@ - + - + all runtime; build; native; contentfiles; analyzers diff --git a/src/Services/Ordering/Ordering.API/Ordering.API.csproj b/src/Services/Ordering/Ordering.API/Ordering.API.csproj index e2b25c2a7..b839c0ea4 100644 --- a/src/Services/Ordering/Ordering.API/Ordering.API.csproj +++ b/src/Services/Ordering/Ordering.API/Ordering.API.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) aspnet-Ordering.API-20161122013547 $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj @@ -28,32 +28,32 @@ - - - - - + + + + + - - - + + + - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj index 63df5da80..d28d9e85f 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj @@ -14,21 +14,21 @@ - - - - + + + + - - - - - - - - - + + + + + + + + + diff --git a/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj b/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj index f79d76c60..04a6c1770 100644 --- a/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj +++ b/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj @@ -1,7 +1,7 @@  - netstandard2.0 + $(NetStandardTargetVersion) diff --git a/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj b/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj index 851a64895..c581d0807 100644 --- a/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj +++ b/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) false @@ -19,9 +19,9 @@ - + - + all runtime; build; native; contentfiles; analyzers diff --git a/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj b/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj index 4f1a74889..6f7f59f9e 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj +++ b/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj @@ -1,7 +1,7 @@  - netstandard2.0 + $(NetStandardTargetVersion) @@ -9,8 +9,8 @@ - - + + diff --git a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj index 00d70cbe6..52cd6d24a 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj +++ b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj @@ -10,27 +10,27 @@ - - - - - - - + + + + + + + - - + + - - - - - - - + + + + + + + diff --git a/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj b/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj index e94aae4f1..6ebbd9028 100644 --- a/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj +++ b/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj @@ -1,21 +1,21 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) false - - + + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Payment/Payment.API/Payment.API.csproj b/src/Services/Payment/Payment.API/Payment.API.csproj index efce8b8ab..6eff9b503 100644 --- a/src/Services/Payment/Payment.API/Payment.API.csproj +++ b/src/Services/Payment/Payment.API/Payment.API.csproj @@ -1,30 +1,30 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; - - - - - - - + + + + + + + - - - - - - - - - + + + + + + + + + diff --git a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj index 4b7fe7eae..b489d32d8 100644 --- a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj +++ b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) InProcess Linux @@ -10,16 +10,16 @@ - - - - + + + + - - - - - + + + + + diff --git a/src/Web/WebMVC/WebMVC.csproj b/src/Web/WebMVC/WebMVC.csproj index 878bcbe7f..09ecb1846 100644 --- a/src/Web/WebMVC/WebMVC.csproj +++ b/src/Web/WebMVC/WebMVC.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) aspnet-Microsoft.eShopOnContainers-946ae052-8305-4a99-965b-ec8636ddbae3 ..\..\..\docker-compose.dcproj 3.0 @@ -19,29 +19,29 @@ - - - + + + - - - + + + - - - - + + + + - - - - - - + + + + + + @@ -49,7 +49,7 @@ - + diff --git a/src/Web/WebSPA/Startup.cs b/src/Web/WebSPA/Startup.cs index 7a418c432..0c1f37b3f 100644 --- a/src/Web/WebSPA/Startup.cs +++ b/src/Web/WebSPA/Startup.cs @@ -64,7 +64,7 @@ namespace eShopConContainers.WebSPA services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); diff --git a/src/Web/WebSPA/WebSPA.csproj b/src/Web/WebSPA/WebSPA.csproj index 56f94d530..858d46eb3 100644 --- a/src/Web/WebSPA/WebSPA.csproj +++ b/src/Web/WebSPA/WebSPA.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) aspnetcorespa-c23d27a4-eb88-4b18-9b77-2a93f3b15119 ..\..\..\docker-compose.dcproj false @@ -85,19 +85,19 @@ - - - - - + + + + + - - + + - - - + + + diff --git a/src/Web/WebStatus/Startup.cs b/src/Web/WebStatus/Startup.cs index 5b35ee84f..d36b2df90 100644 --- a/src/Web/WebStatus/Startup.cs +++ b/src/Web/WebStatus/Startup.cs @@ -33,7 +33,7 @@ namespace WebStatus services.AddHealthChecksUI(); services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/src/Web/WebStatus/WebStatus.csproj b/src/Web/WebStatus/WebStatus.csproj index 7e83ddc7b..94559d506 100644 --- a/src/Web/WebStatus/WebStatus.csproj +++ b/src/Web/WebStatus/WebStatus.csproj @@ -1,28 +1,27 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\docker-compose.dcproj - - - - - - - + + + + + + - - - + + + - - - - - - + + + + + + diff --git a/src/Web/WebhookClient/WebhookClient.csproj b/src/Web/WebhookClient/WebhookClient.csproj index 895cbac54..51c99f974 100644 --- a/src/Web/WebhookClient/WebhookClient.csproj +++ b/src/Web/WebhookClient/WebhookClient.csproj @@ -1,7 +1,7 @@ - netcoreapp2.2 + $(NetCoreTargetVersion) InProcess Linux 36215d41-f31a-4aa6-9929-bd67d650e7b5 diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props new file mode 100644 index 000000000..33a049c2d --- /dev/null +++ b/src/_build/dependencies.props @@ -0,0 +1,81 @@ + + + netstandard2.1 + netcoreapp3.0 + 15.8.0 + latest + + + + 2.1.1 + 2.1.1 + + + + 2.9.406 + + + + 0.1.22-pre1 + 3.9.0-rc1 + 1.22.0 + + 2.2.0 + 2.2.0 + 2.2.0 + 2.2.0 + 2.2.0 + 2.2.22 + 2.2.3 + 2.2.2 + 4.9.2 + 4.2.1 + 2.2.1 + 2.6.1 + 1.0.2 + 2.2.0 + 1.0.0 + 2.2.0 + 3.0.0 + 4.5.0 + 2.2.2 + 2.2.2 + 2.2.2 + 2.2.2 + 2.2.0 + 2.2.0 + 2.2.0 + 2.2.0 + 2.2.0 + 2.2.0 + 3.0.0-preview6.19304.6 + 16.0.1 + 2.5.0 + 2.5.0 + 2.5.0 + 2.5.0 + 4.10.1 + 12.0.2 + 12.0.1 + 6.0.1 + 5.0.1 + 3.0.0-dev-00053 + 2.1.3 + 3.1.1-dev-00209 + 3.1.1 + 4.0.0 + 4.2.1 + 5.0.0-rc2 + 4.3.0 + 2.4.0 + 2.4.0 + + + + https://github.com/dotnet-architecture/eShopOnContainers/blob/master/LICENSE + https://github.com/dotnet-architecture/eShopOnContainers + https://github.com/dotnet-architecture/eShopOnContainers + Microsoft + + + \ No newline at end of file diff --git a/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj b/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj index 1d7ebd5a5..cd16dfad1 100644 --- a/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj +++ b/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + $(NetCoreTargetVersion) true false false @@ -67,9 +67,9 @@ - + - + all runtime; build; native; contentfiles; analyzers From 96c3b127217ded89f600efe1f5128b18c7f8f954 Mon Sep 17 00:00:00 2001 From: eiximenis Date: Thu, 18 Jul 2019 12:31:27 +0200 Subject: [PATCH 005/113] More package refs moved to dependencies.props --- .../EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj | 2 +- src/Services/Basket/Basket.API/Basket.API.csproj | 6 ++---- .../Basket.FunctionalTests/Basket.FunctionalTests.csproj | 5 ++--- .../Basket/Basket.UnitTests/Basket.UnitTests.csproj | 5 ++--- .../Catalog.FunctionalTests/Catalog.FunctionalTests.csproj | 4 ++-- .../Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj | 4 ++-- .../Locations.FunctionalTests.csproj | 4 ++-- .../Marketing.FunctionalTests.csproj | 4 ++-- src/Services/Ordering/Ordering.API/Ordering.API.csproj | 2 +- .../Ordering/Ordering.Domain/Ordering.Domain.csproj | 2 +- .../Ordering.FunctionalTests.csproj | 4 ++-- .../Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj | 6 +++--- src/_build/dependencies.props | 3 +++ .../Application.FunctionalTests.csproj | 2 +- 14 files changed, 26 insertions(+), 27 deletions(-) diff --git a/src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj b/src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj index 6830ac9d7..2e5e0fa24 100644 --- a/src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj +++ b/src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj @@ -11,7 +11,7 @@ - + diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index a949b2636..561860b31 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -15,17 +15,15 @@ - + - - @@ -34,7 +32,7 @@ - + diff --git a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj index 120bfde02..1db1b6eed 100644 --- a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj +++ b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj @@ -2,7 +2,6 @@ $(NetCoreTargetVersion) - false @@ -22,11 +21,11 @@ - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj index 95b30667e..4c062fccd 100644 --- a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj +++ b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj @@ -11,12 +11,11 @@ - + all runtime; build; native; contentfiles; analyzers - - + diff --git a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj index 0e0ccbe7a..88ec76d50 100644 --- a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj +++ b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj @@ -38,11 +38,11 @@ - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj index 58863148d..d0584bd60 100644 --- a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj +++ b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj @@ -11,11 +11,11 @@ - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj index 645c294f8..5ef4a4229 100644 --- a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj +++ b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj @@ -22,11 +22,11 @@ - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj b/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj index 2ecf7e8ea..8d28cd0ff 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj +++ b/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj @@ -22,11 +22,11 @@ - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Ordering/Ordering.API/Ordering.API.csproj b/src/Services/Ordering/Ordering.API/Ordering.API.csproj index b839c0ea4..bcc4151e1 100644 --- a/src/Services/Ordering/Ordering.API/Ordering.API.csproj +++ b/src/Services/Ordering/Ordering.API/Ordering.API.csproj @@ -35,7 +35,7 @@ - + diff --git a/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj b/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj index 04a6c1770..eac16c43f 100644 --- a/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj +++ b/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj @@ -5,7 +5,7 @@ - + diff --git a/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj b/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj index c581d0807..a79b9a7db 100644 --- a/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj +++ b/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj @@ -22,11 +22,11 @@ - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj b/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj index 6ebbd9028..6d5cb9186 100644 --- a/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj +++ b/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj @@ -9,12 +9,12 @@ - + all runtime; build; native; contentfiles; analyzers - - + + diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 33a049c2d..16791811e 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -24,12 +24,14 @@ 2.2.0 2.2.0 2.2.0 + 2.2.0 2.2.0 2.2.22 2.2.3 2.2.2 4.9.2 4.2.1 + 5.1.0 2.2.1 2.6.1 1.0.2 @@ -65,6 +67,7 @@ 3.1.1 4.0.0 4.2.1 + 1.2.6 5.0.0-rc2 4.3.0 2.4.0 diff --git a/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj b/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj index cd16dfad1..3f26ed8f0 100644 --- a/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj +++ b/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj @@ -70,7 +70,7 @@ - + all runtime; build; native; contentfiles; analyzers From 577aca1d4c040d1dd0f672211a8edee99ed23a45 Mon Sep 17 00:00:00 2001 From: eiximenis Date: Fri, 19 Jul 2019 13:09:30 +0200 Subject: [PATCH 006/113] Basket.API updated to net3 --- docker-compose.override.yml | 65 +++++++++---------- src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj | 1 - .../Web.Shopping.HttpAggregator.csproj | 1 - .../WebHost.Customization.csproj | 1 - ...orizationHeaderParameterOperationFilter.cs | 13 ++-- .../Auth/Server/IdentitySecurityScheme.cs | 20 ------ .../Basket/Basket.API/Basket.API.csproj | 2 +- .../Filters/AuthorizeCheckOperationFilter.cs | 31 --------- .../Filters/HttpGlobalExceptionFilter.cs | 6 +- src/Services/Basket/Basket.API/Startup.cs | 59 ++++++++--------- .../Basket.API/appsettings.Development.json | 17 +++++ .../Basket/Basket.API/appsettings.json | 3 - .../Basket.FunctionalTests.csproj | 2 +- src/Services/Catalog/Catalog.API/Startup.cs | 1 - .../Catalog.API/appsettings.Development.json | 5 +- .../Catalog/Catalog.API/appsettings.json | 4 +- .../Catalog.FunctionalTests.csproj | 3 +- .../Identity/Identity.API/Identity.API.csproj | 1 - .../Locations.API/Locations.API.csproj | 1 - .../Locations.FunctionalTests.csproj | 2 +- .../Marketing.API/Marketing.API.csproj | 1 - .../Marketing.FunctionalTests.csproj | 2 +- ...orizationHeaderParameterOperationFilter.cs | 14 ++-- .../Ordering/Ordering.API/Ordering.API.csproj | 1 - .../Ordering.BackgroundTasks.csproj | 3 +- .../Ordering.FunctionalTests.csproj | 2 +- .../Payment/Payment.API/Payment.API.csproj | 1 - .../Webhooks/Webhooks.API/Webhooks.API.csproj | 1 - src/Web/WebMVC/WebMVC.csproj | 1 - src/Web/WebSPA/WebSPA.csproj | 1 - src/Web/WebStatus/WebStatus.csproj | 1 - src/Web/WebhookClient/WebhookClient.csproj | 1 - src/_build/dependencies.props | 7 +- .../Application.FunctionalTests.csproj | 2 +- 34 files changed, 110 insertions(+), 166 deletions(-) delete mode 100644 src/Services/Basket/Basket.API/Auth/Server/IdentitySecurityScheme.cs delete mode 100644 src/Services/Basket/Basket.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs create mode 100644 src/Services/Basket/Basket.API/appsettings.Development.json diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 11ea6138c..e4ee76650 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -18,29 +18,29 @@ services: - SA_PASSWORD=Pass@word - ACCEPT_EULA=Y ports: - - "5433:1433" # Important: In a production environment your should remove the external port + - "5433:1433" nosql.data: ports: - - "27017:27017" # Important: In a production environment your should remove the external port + - "27017:27017" basket.data: ports: - - "6379:6379" # Important: In a production environment your should remove the external port + - "6379:6379" rabbitmq: ports: - - "15672:15672" # Important: In a production environment your should remove the external port - - "5672:5672" # Important: In a production environment your should remove the external port + - "15672:15672" + - "5672:5672" identity.api: environment: - ASPNETCORE_ENVIRONMENT=Development - ASPNETCORE_URLS=http://0.0.0.0:80 - SpaClient=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5104 - - XamarinCallback=http://${ESHOP_PROD_EXTERNAL_DNS_NAME_OR_IP}:5105/xamarincallback #localhost do not work for UWP login, so we have to use "external" IP always + - XamarinCallback=http://${ESHOP_PROD_EXTERNAL_DNS_NAME_OR_IP}:5105/xamarincallback - ConnectionString=${ESHOP_AZURE_IDENTITY_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Service.IdentityDb;User Id=sa;Password=Pass@word} - - MvcClient=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5100 #Local: You need to open your local dev-machine firewall at range 5100-5110. + - MvcClient=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5100 - LocationApiClient=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5109 - MarketingApiClient=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5110 - BasketApiClient=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5103 @@ -60,7 +60,7 @@ services: - ASPNETCORE_ENVIRONMENT=Development - ASPNETCORE_URLS=http://0.0.0.0:80 - ConnectionString=${ESHOP_AZURE_REDIS_BASKET_DB:-basket.data} - - identityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - identityUrl=http://identity.api - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} - EventBusUserName=${ESHOP_SERVICE_BUS_USERNAME} @@ -71,8 +71,7 @@ services: - UseLoadTest=${USE_LOADTEST:-False} ports: - - "5103:80" # Important: In a production environment your should remove the external port (5103) kept here for microservice debugging purposes. - # The API Gateway redirects and access through the internal port (80). + - "5103:80" catalog.api: environment: @@ -100,7 +99,7 @@ services: - ASPNETCORE_ENVIRONMENT=Development - ASPNETCORE_URLS=http://0.0.0.0:80 - ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word} - - identityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - identityUrl=http://identity.api - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} - EventBusUserName=${ESHOP_SERVICE_BUS_USERNAME} @@ -114,8 +113,7 @@ services: - Serilog__MinimumLevel__Override__Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ=Verbose - Serilog__MinimumLevel__Override__Ordering.API=Verbose ports: - - "5102:80" # Important: In a production environment your should remove the external port (5102) kept here for microservice debugging purposes. - # The API Gateway redirects and access through the internal port (80). + - "5102:80" ordering.backgroundtasks: @@ -147,7 +145,7 @@ services: - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} - EventBusUserName=${ESHOP_SERVICE_BUS_USERNAME} - EventBusPassword=${ESHOP_SERVICE_BUS_PASSWORD} - - identityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - identityUrl=http://identity.api - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 - CampaignDetailFunctionUri=${ESHOP_AZUREFUNC_CAMPAIGN_DETAILS_URI} - PicBaseUrl=${ESHOP_AZURE_STORAGE_MARKETING_URL:-http://localhost:5110/api/v1/campaigns/[0]/pic/} @@ -159,8 +157,7 @@ services: - OrchestratorType=${ORCHESTRATOR_TYPE} - UseLoadTest=${USE_LOADTEST:-False} ports: - - "5110:80" # Important: In a production environment your should remove the external port (5110) kept here for microservice debugging purposes. - # The API Gateway redirects and access through the internal port (80). + - "5110:80" payment.api: environment: @@ -175,8 +172,7 @@ services: - Serilog__MinimumLevel__Override__Payment.API.IntegrationEvents.EventHandling=Verbose - Serilog__MinimumLevel__Override__Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ=Verbose ports: - - "5108:80" # Important: In a production environment your should remove the external port (5108) kept here for microservice debugging purposes. - # The API Gateway redirects and access through the internal port (80). + - "5108:80" locations.api: environment: @@ -184,7 +180,7 @@ services: - ASPNETCORE_URLS=http://0.0.0.0:80 - ConnectionString=${ESHOP_AZURE_COSMOSDB:-mongodb://nosql.data} - Database=LocationsDb - - identityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - identityUrl=http://identity.api - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} - EventBusUserName=${ESHOP_SERVICE_BUS_USERNAME} @@ -194,8 +190,8 @@ services: - OrchestratorType=${ORCHESTRATOR_TYPE} - UseLoadTest=${USE_LOADTEST:-False} ports: - - "5109:80" # Important: In a production environment your should remove the external port (5109) kept here for microservice debugging purposes. - # The API Gateway redirects and access through the internal port (80). + - "5109:80" + webhooks.api: environment: - ASPNETCORE_ENVIRONMENT=Development @@ -207,13 +203,12 @@ services: - IdentityUrl=http://identity.api - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 ports: - - "5113:80" # Important: In a production environment your should remove the external port (5109) kept here for microservice debugging purposes. - # The API Gateway redirects and access through the internal port (80). + - "5113:80" mobileshoppingapigw: environment: - ASPNETCORE_ENVIRONMENT=Development - - IdentityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - IdentityUrl=http://identity.api - urls__basket=http://basket.api - urls__catalog=http://catalog.api - urls__orders=http://ordering.api @@ -233,7 +228,7 @@ services: mobilemarketingapigw: environment: - ASPNETCORE_ENVIRONMENT=Development - - IdentityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - IdentityUrl=http://identity.api - CatalogUrlHC=http://catalog.api/hc - OrderingUrlHC=http://ordering.api/hc - IdentityUrlHC=http://identity.api/hc @@ -249,7 +244,7 @@ services: webshoppingapigw: environment: - ASPNETCORE_ENVIRONMENT=Development - - IdentityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - IdentityUrl=http://identity.api - CatalogUrlHC=http://catalog.api/hc - OrderingUrlHC=http://ordering.api/hc - IdentityUrlHC=http://identity.api/hc @@ -265,7 +260,7 @@ services: webmarketingapigw: environment: - ASPNETCORE_ENVIRONMENT=Development - - IdentityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - IdentityUrl=http://identity.api - CatalogUrlHC=http://catalog.api/hc - OrderingUrlHC=http://ordering.api/hc - IdentityUrlHC=http://identity.api/hc @@ -284,7 +279,7 @@ services: - urls__basket=http://basket.api - urls__catalog=http://catalog.api - urls__orders=http://ordering.api - - urls__identity=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - urls__identity=http://identity.api - CatalogUrlHC=http://catalog.api/hc - OrderingUrlHC=http://ordering.api/hc - IdentityUrlHC=http://identity.api/hc @@ -293,8 +288,7 @@ services: - PaymentUrlHC=http://payment.api/hc - LocationUrlHC=http://locations.api/hc ports: - - "5120:80" # Important: In a production environment your should remove the external port (5120) kept here for microservice debugging purposes. - # The API Gateway redirects and access through the internal port (80). + - "5120:80" webshoppingagg: environment: @@ -302,7 +296,7 @@ services: - urls__basket=http://basket.api - urls__catalog=http://catalog.api - urls__orders=http://ordering.api - - urls__identity=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - urls__identity=http://identity.api - CatalogUrlHC=http://catalog.api/hc - OrderingUrlHC=http://ordering.api/hc - IdentityUrlHC=http://identity.api/hc @@ -311,8 +305,7 @@ services: - PaymentUrlHC=http://payment.api/hc - LocationUrlHC=http://locations.api/hc ports: - - "5121:80" # Important: In a production environment your should remove the external port (5121) kept here for microservice debugging purposes. - # The API Gateway redirects and access through the internal port (80). + - "5121:80" ordering.signalrhub: environment: @@ -324,7 +317,7 @@ services: - AzureServiceBusEnabled=False - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - OrchestratorType=${ORCHESTRATOR_TYPE} - - identityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5110. + - identityUrl=http://identity.api ports: - "5112:80" @@ -376,7 +369,7 @@ services: environment: - ASPNETCORE_ENVIRONMENT=Development - ASPNETCORE_URLS=http://0.0.0.0:80 - - IdentityUrl=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 #Local: You need to open your local dev-machine firewall at range 5100-5105. at range 5100-5105. + - IdentityUrl=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 - PurchaseUrl=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5202 - MarketingUrl=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5203 - PurchaseUrlHC=http://webshoppingapigw/hc @@ -394,7 +387,7 @@ services: - ASPNETCORE_ENVIRONMENT=Development - ASPNETCORE_URLS=http://0.0.0.0:80 - PurchaseUrl=http://webshoppingapigw - - IdentityUrl=http://10.0.75.1:5105 # Local Mac: Use http://docker.for.mac.localhost:5105 || Local Windows: Use 10.0.75.1 in a "Docker for Windows" environment, if using "localhost" from browser. || #Remote access: Use ${ESHOP_EXTERNAL_DNS_NAME_OR_IP} if using external IP or DNS name from browser. + - IdentityUrl=http://10.0.75.1:5105 - MarketingUrl=http://webmarketingapigw - SignalrHubUrl=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5202 - IdentityUrlHC=http://identity.api/hc diff --git a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj index 5db2881d5..ea011f624 100644 --- a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj +++ b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj @@ -7,7 +7,6 @@ - diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj index d71cbee45..faa609b06 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj @@ -14,7 +14,6 @@ - diff --git a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj index 14f473643..3c3f6a3e3 100644 --- a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj +++ b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj @@ -6,7 +6,6 @@ - diff --git a/src/Services/Basket/Basket.API/Auth/Server/AuthorizationHeaderParameterOperationFilter.cs b/src/Services/Basket/Basket.API/Auth/Server/AuthorizationHeaderParameterOperationFilter.cs index 90aa89322..7fe19bae3 100644 --- a/src/Services/Basket/Basket.API/Auth/Server/AuthorizationHeaderParameterOperationFilter.cs +++ b/src/Services/Basket/Basket.API/Auth/Server/AuthorizationHeaderParameterOperationFilter.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Mvc.Authorization; +using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; @@ -8,7 +9,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Auth.Server { public class AuthorizationHeaderParameterOperationFilter : IOperationFilter { - public void Apply(Operation operation, OperationFilterContext context) + public void Apply(OpenApiOperation operation, OperationFilterContext context) { var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors; var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter); @@ -17,15 +18,15 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Auth.Server if (isAuthorized && !allowAnonymous) { if (operation.Parameters == null) - operation.Parameters = new List(); + operation.Parameters = new List(); - operation.Parameters.Add(new NonBodyParameter + + operation.Parameters.Add(new OpenApiParameter { Name = "Authorization", - In = "header", + In = ParameterLocation.Header, Description = "access token", - Required = true, - Type = "string" + Required = true }); } } diff --git a/src/Services/Basket/Basket.API/Auth/Server/IdentitySecurityScheme.cs b/src/Services/Basket/Basket.API/Auth/Server/IdentitySecurityScheme.cs deleted file mode 100644 index 397f66db4..000000000 --- a/src/Services/Basket/Basket.API/Auth/Server/IdentitySecurityScheme.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Swashbuckle.AspNetCore.Swagger; -using System.Collections.Generic; - -namespace Microsoft.eShopOnContainers.Services.Basket.API.Auth.Server -{ - public class IdentitySecurityScheme:SecurityScheme - { - public IdentitySecurityScheme() - { - Type = "IdentitySecurityScheme"; - Description = "Security definition that provides to the user of Swagger a mechanism to obtain a token from the identity service that secures the api"; - Extensions.Add("authorizationUrl", "http://localhost:5103/Auth/Client/popup.html"); - Extensions.Add("flow", "implicit"); - Extensions.Add("scopes", new List - { - "basket" - }); - } - } -} diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index 561860b31..00718ad63 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -21,7 +21,7 @@ - + diff --git a/src/Services/Basket/Basket.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs b/src/Services/Basket/Basket.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs deleted file mode 100644 index 1ae38c8b0..000000000 --- a/src/Services/Basket/Basket.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Swashbuckle.AspNetCore.Swagger; -using Swashbuckle.AspNetCore.SwaggerGen; -using System.Collections.Generic; -using System.Linq; - -namespace Basket.API.Infrastructure.Filters -{ - public class AuthorizeCheckOperationFilter : IOperationFilter - { - public void Apply(Operation operation, OperationFilterContext context) - { - // Check for authorize attribute - var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || - context.MethodInfo.GetCustomAttributes(true).OfType().Any(); - - if (!hasAuthorize) return; - - operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); - - operation.Security = new List>> - { - new Dictionary> - { - { "oauth2", new [] { "basketapi" } } - } - }; - } - } -} \ No newline at end of file diff --git a/src/Services/Basket/Basket.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs b/src/Services/Basket/Basket.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs index dab725915..0fd08a0a9 100644 --- a/src/Services/Basket/Basket.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs +++ b/src/Services/Basket/Basket.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs @@ -3,17 +3,19 @@ using Basket.API.Infrastructure.Exceptions; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Net; + namespace Basket.API.Infrastructure.Filters { public partial class HttpGlobalExceptionFilter : IExceptionFilter { - private readonly IHostingEnvironment env; + private readonly IWebHostEnvironment env; private readonly ILogger logger; - public HttpGlobalExceptionFilter(IHostingEnvironment env, ILogger logger) + public HttpGlobalExceptionFilter(IWebHostEnvironment env, ILogger logger) { this.env = env; this.logger = logger; diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index 9cfabf20a..79208b19b 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -5,9 +5,6 @@ using Basket.API.Infrastructure.Middlewares; using Basket.API.IntegrationEvents.EventHandling; using Basket.API.IntegrationEvents.Events; using HealthChecks.UI.Client; - -using Microsoft.ApplicationInsights.Extensibility; -using Microsoft.ApplicationInsights.ServiceFabric; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; @@ -60,7 +57,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API options.Filters.Add(typeof(ValidateModelStateFilter)); }) - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); ConfigureAuthService(services); @@ -135,27 +132,29 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Info + options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo { Title = "Basket HTTP API", Version = "v1", - Description = "The Basket Service HTTP API", - TermsOfService = "Terms Of Service" + Description = "The Basket Service HTTP API" }); - options.AddSecurityDefinition("oauth2", new OAuth2Scheme + options.AddSecurityDefinition("oauth2", new OpenApi.Models.OpenApiSecurityScheme { - Type = "oauth2", - Flow = "implicit", - AuthorizationUrl = $"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize", - TokenUrl = $"{Configuration.GetValue("IdentityUrlExternal")}/connect/token", - Scopes = new Dictionary() + Flows = new OpenApi.Models.OpenApiOAuthFlows() { - { "basket", "Basket API" } + Implicit = new OpenApi.Models.OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "basket", "Basket API" } + } + } } }); - options.OperationFilter(); }); services.AddCors(options => @@ -178,10 +177,10 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API return new AutofacServiceProvider(container.Build()); } - + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { //loggerFactory.AddAzureWebAppDiagnostics(); //loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); @@ -203,18 +202,19 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API Predicate = r => r.Name.Contains("self") }); - app.UseStaticFiles(); + app.UseStaticFiles(); app.UseCors("CorsPolicy"); ConfigureAuth(app); - app.UseMvcWithDefaultRoute(); + app.UseRouting(); + app.UseEndpoints(e => e.MapDefaultControllerRoute()); app.UseSwagger() .UseSwaggerUI(c => { c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); - c.OAuthClientId ("basketswaggerui"); + c.OAuthClientId("basketswaggerui"); c.OAuthAppName("Basket Swagger UI"); }); @@ -226,18 +226,12 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API { services.AddApplicationInsightsTelemetry(Configuration); var orchestratorType = Configuration.GetValue("OrchestratorType"); - + if (orchestratorType?.ToUpper() == "K8S") { // Enable K8s telemetry initializer services.AddApplicationInsightsKubernetesEnricher(); } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } } private void ConfigureAuthService(IServiceCollection services) @@ -245,8 +239,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API // prevent from mapping "sub" claim to nameidentifier. JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); - var identityUrl = Configuration.GetValue("IdentityUrl"); - + var identityUrl = Configuration.GetValue("IdentityUrl"); + services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; @@ -268,6 +262,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API } app.UseAuthentication(); + app.UseAuthorization(); } private void RegisterEventBus(IServiceCollection services) @@ -281,7 +276,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API var serviceBusPersisterConnection = sp.GetRequiredService(); var iLifetimeScope = sp.GetRequiredService(); var logger = sp.GetRequiredService>(); - var eventBusSubcriptionsManager = sp.GetRequiredService(); + var eventBusSubcriptionsManager = sp.GetRequiredService(); return new EventBusServiceBus(serviceBusPersisterConnection, logger, eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope); @@ -318,7 +313,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API eventBus.Subscribe(); eventBus.Subscribe(); - } + } } public static class CustomExtensionMethods @@ -329,7 +324,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy()); - hcBuilder + hcBuilder .AddRedis( configuration["ConnectionString"], name: "redis-check", diff --git a/src/Services/Basket/Basket.API/appsettings.Development.json b/src/Services/Basket/Basket.API/appsettings.Development.json new file mode 100644 index 000000000..f4a3b9407 --- /dev/null +++ b/src/Services/Basket/Basket.API/appsettings.Development.json @@ -0,0 +1,17 @@ +{ + "Serilog": { + "MinimumLevel": { + "Default": "Debug", + "Override": { + "Microsoft": "Warning", + "Microsoft.eShopOnContainers": "Debug", + "System": "Warning" + } + } + }, + "IdentityUrlExternal": "http://localhost:5105", + "IdentityUrl": "http://localhost:5105", + "ConnectionString": "127.0.0.1", + "AzureServiceBusEnabled": false, + "EventBusConnection": "localhost" +} \ No newline at end of file diff --git a/src/Services/Basket/Basket.API/appsettings.json b/src/Services/Basket/Basket.API/appsettings.json index fc8fc544a..37d5b08d6 100644 --- a/src/Services/Basket/Basket.API/appsettings.json +++ b/src/Services/Basket/Basket.API/appsettings.json @@ -11,9 +11,6 @@ } } }, - "IdentityUrl": "http://localhost:5105", - "ConnectionString": "127.0.0.1", - "AzureServiceBusEnabled": false, "SubscriptionClientName": "Basket", "ApplicationInsights": { "InstrumentationKey": "" diff --git a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj index 1db1b6eed..168176aaf 100644 --- a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj +++ b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj @@ -19,7 +19,7 @@ - + all diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 69580a926..716e0f1ca 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -2,7 +2,6 @@ using Autofac.Extensions.DependencyInjection; using global::Catalog.API.Infrastructure.Filters; using global::Catalog.API.IntegrationEvents; -using Microsoft.ApplicationInsights.Extensibility; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; diff --git a/src/Services/Catalog/Catalog.API/appsettings.Development.json b/src/Services/Catalog/Catalog.API/appsettings.Development.json index 9d8370a39..1d5574f63 100644 --- a/src/Services/Catalog/Catalog.API/appsettings.Development.json +++ b/src/Services/Catalog/Catalog.API/appsettings.Development.json @@ -1,4 +1,6 @@ { + "ConnectionString": "Server=tcp:127.0.0.1,5433;Initial Catalog=Microsoft.eShopOnContainers.Services.CatalogDb;User Id=sa;Password=Pass@word", + "PicBaseUrl": "http://localhost:5101/api/v1/catalog/items/[0]/pic/", "Serilog": { "MinimumLevel": { "Default": "Debug", @@ -8,5 +10,6 @@ "System": "Warning" } } - } + }, + "EventBusConnection": "localhost" } \ No newline at end of file diff --git a/src/Services/Catalog/Catalog.API/appsettings.json b/src/Services/Catalog/Catalog.API/appsettings.json index cc450f89d..e9103c7a6 100644 --- a/src/Services/Catalog/Catalog.API/appsettings.json +++ b/src/Services/Catalog/Catalog.API/appsettings.json @@ -1,6 +1,4 @@ { - "ConnectionString": "Server=tcp:127.0.0.1,5433;Initial Catalog=Microsoft.eShopOnContainers.Services.CatalogDb;User Id=sa;Password=Pass@word", - "PicBaseUrl": "http://localhost:5101/api/v1/catalog/items/[0]/pic/", "UseCustomizationData": false, "Serilog": { "SeqServerUrl": null, @@ -20,7 +18,6 @@ "ApplicationInsights": { "InstrumentationKey": "" }, - "EventBusConnection": "localhost", "EventBusRetryCount": 5, "UseVault": false, "Vault": { @@ -28,5 +25,6 @@ "ClientId": "your-clien-id", "ClientSecret": "your-client-secret" } + } \ No newline at end of file diff --git a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj index 88ec76d50..a679d5d35 100644 --- a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj +++ b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj @@ -33,10 +33,9 @@ - - + all diff --git a/src/Services/Identity/Identity.API/Identity.API.csproj b/src/Services/Identity/Identity.API/Identity.API.csproj index 5fe2b3a86..e68e36a7e 100644 --- a/src/Services/Identity/Identity.API/Identity.API.csproj +++ b/src/Services/Identity/Identity.API/Identity.API.csproj @@ -21,7 +21,6 @@ - diff --git a/src/Services/Location/Locations.API/Locations.API.csproj b/src/Services/Location/Locations.API/Locations.API.csproj index cd110d9de..7f658ee2d 100644 --- a/src/Services/Location/Locations.API/Locations.API.csproj +++ b/src/Services/Location/Locations.API/Locations.API.csproj @@ -14,7 +14,6 @@ - diff --git a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj index 5ef4a4229..dd1432b48 100644 --- a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj +++ b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj @@ -20,7 +20,7 @@ - + all diff --git a/src/Services/Marketing/Marketing.API/Marketing.API.csproj b/src/Services/Marketing/Marketing.API/Marketing.API.csproj index 2409caf49..74d7574a6 100644 --- a/src/Services/Marketing/Marketing.API/Marketing.API.csproj +++ b/src/Services/Marketing/Marketing.API/Marketing.API.csproj @@ -31,7 +31,6 @@ - diff --git a/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj b/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj index 8d28cd0ff..eddf06086 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj +++ b/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj @@ -20,7 +20,7 @@ - + all diff --git a/src/Services/Ordering/Ordering.API/Infrastructure/Auth/AuthorizationHeaderParameterOperationFilter.cs b/src/Services/Ordering/Ordering.API/Infrastructure/Auth/AuthorizationHeaderParameterOperationFilter.cs index f780ff4a5..7e30a69fc 100644 --- a/src/Services/Ordering/Ordering.API/Infrastructure/Auth/AuthorizationHeaderParameterOperationFilter.cs +++ b/src/Services/Ordering/Ordering.API/Infrastructure/Auth/AuthorizationHeaderParameterOperationFilter.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Mvc.Authorization; +using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; @@ -8,7 +9,7 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API.Infrastructure.Auth { public class AuthorizationHeaderParameterOperationFilter : IOperationFilter { - public void Apply(Operation operation, OperationFilterContext context) + public void Apply(OpenApiOperation operation, OperationFilterContext context) { var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors; var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter); @@ -17,17 +18,18 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API.Infrastructure.Auth if (isAuthorized && !allowAnonymous) { if (operation.Parameters == null) - operation.Parameters = new List(); + operation.Parameters = new List(); - operation.Parameters.Add(new NonBodyParameter + + operation.Parameters.Add(new OpenApiParameter { Name = "Authorization", - In = "header", + In = ParameterLocation.Header, Description = "access token", - Required = true, - Type = "string" + Required = true }); } } + } } diff --git a/src/Services/Ordering/Ordering.API/Ordering.API.csproj b/src/Services/Ordering/Ordering.API/Ordering.API.csproj index bcc4151e1..4bbfab9d4 100644 --- a/src/Services/Ordering/Ordering.API/Ordering.API.csproj +++ b/src/Services/Ordering/Ordering.API/Ordering.API.csproj @@ -41,7 +41,6 @@ - diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj index d28d9e85f..5681288a8 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj @@ -18,8 +18,7 @@ - - + diff --git a/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj b/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj index a79b9a7db..5acad11ca 100644 --- a/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj +++ b/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj @@ -20,7 +20,7 @@ - + all diff --git a/src/Services/Payment/Payment.API/Payment.API.csproj b/src/Services/Payment/Payment.API/Payment.API.csproj index 6eff9b503..79e071e76 100644 --- a/src/Services/Payment/Payment.API/Payment.API.csproj +++ b/src/Services/Payment/Payment.API/Payment.API.csproj @@ -15,7 +15,6 @@ - diff --git a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj index b489d32d8..1dcf916f5 100644 --- a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj +++ b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj @@ -7,7 +7,6 @@ - diff --git a/src/Web/WebMVC/WebMVC.csproj b/src/Web/WebMVC/WebMVC.csproj index 09ecb1846..42f8f16dd 100644 --- a/src/Web/WebMVC/WebMVC.csproj +++ b/src/Web/WebMVC/WebMVC.csproj @@ -31,7 +31,6 @@ - diff --git a/src/Web/WebSPA/WebSPA.csproj b/src/Web/WebSPA/WebSPA.csproj index 858d46eb3..365b3205a 100644 --- a/src/Web/WebSPA/WebSPA.csproj +++ b/src/Web/WebSPA/WebSPA.csproj @@ -93,7 +93,6 @@ - diff --git a/src/Web/WebStatus/WebStatus.csproj b/src/Web/WebStatus/WebStatus.csproj index 94559d506..9364cd5e2 100644 --- a/src/Web/WebStatus/WebStatus.csproj +++ b/src/Web/WebStatus/WebStatus.csproj @@ -11,7 +11,6 @@ - diff --git a/src/Web/WebhookClient/WebhookClient.csproj b/src/Web/WebhookClient/WebhookClient.csproj index 51c99f974..95ec6e8fb 100644 --- a/src/Web/WebhookClient/WebhookClient.csproj +++ b/src/Web/WebhookClient/WebhookClient.csproj @@ -9,7 +9,6 @@ - diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 16791811e..de5ed4901 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -31,19 +31,22 @@ 2.2.2 4.9.2 4.2.1 + 1.50.7 5.1.0 2.2.1 2.6.1 1.0.2 + 3.0.0-preview6.19307.2 2.2.0 1.0.0 2.2.0 + 3.0.0-preview6.19307.2 3.0.0 - 4.5.0 + 4.5.0 2.2.2 2.2.2 2.2.2 - 2.2.2 + 2.2.2 2.2.0 2.2.0 2.2.0 diff --git a/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj b/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj index 3f26ed8f0..96ef8f046 100644 --- a/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj +++ b/test/ServicesTests/Application.FunctionalTests/Application.FunctionalTests.csproj @@ -68,7 +68,7 @@ - + all From 66bee87584ff922a173fa244af2338623213fa5e Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Mon, 22 Jul 2019 16:16:57 +0200 Subject: [PATCH 007/113] migrate marketing --- .../WebHost.Customization.csproj | 6 +++ .../WebHostExtensions.cs | 5 +-- .../Basket/Basket.API/Basket.API.csproj | 1 + src/Services/Basket/Basket.API/Dockerfile | 4 +- .../Catalog/Catalog.API/Catalog.API.csproj | 1 + .../Marketing/Marketing.API/Dockerfile | 4 +- .../Marketing.API/Marketing.API.csproj | 3 +- .../Marketing/Marketing.API/Startup.cs | 44 ++++++++----------- src/_build/dependencies.props | 13 ++++-- 9 files changed, 44 insertions(+), 37 deletions(-) diff --git a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj index 3c3f6a3e3..acae2354a 100644 --- a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj +++ b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj @@ -6,6 +6,12 @@ + + + + + + diff --git a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs index fa06e0a0b..fd17f4a0d 100644 --- a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs +++ b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs @@ -3,7 +3,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Polly; -using Polly.Retry; using System; using System.Data.SqlClient; @@ -18,7 +17,7 @@ namespace Microsoft.AspNetCore.Hosting return orchestratorType?.ToUpper() == "K8S"; } - public static IWebHost MigrateDbContext(this IWebHost webHost, Action seeder) where TContext : DbContext + public static IWebHost MigrateDbContext(this IWebHost webHost, Action seeder) where TContext : DbContext { var underK8s = webHost.IsInKubernetes(); @@ -71,7 +70,7 @@ namespace Microsoft.AspNetCore.Hosting } private static void InvokeSeeder(Action seeder, TContext context, IServiceProvider services) - where TContext : DbContext + where TContext : DbContext { context.Database.Migrate(); seeder(context, services); diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index 00718ad63..22c562da0 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -4,6 +4,7 @@ $(NetCoreTargetVersion) $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj + 8.0 diff --git a/src/Services/Basket/Basket.API/Dockerfile b/src/Services/Basket/Basket.API/Dockerfile index 909567b2c..c70aa3a96 100644 --- a/src/Services/Basket/Basket.API/Dockerfile +++ b/src/Services/Basket/Basket.API/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Services/Catalog/Catalog.API/Catalog.API.csproj b/src/Services/Catalog/Catalog.API/Catalog.API.csproj index d88c92f09..2640185d1 100644 --- a/src/Services/Catalog/Catalog.API/Catalog.API.csproj +++ b/src/Services/Catalog/Catalog.API/Catalog.API.csproj @@ -8,6 +8,7 @@ Catalog.API aspnet-Catalog.API-20161122013618 ..\..\..\..\docker-compose.dcproj + 8.0 diff --git a/src/Services/Marketing/Marketing.API/Dockerfile b/src/Services/Marketing/Marketing.API/Dockerfile index 3e0936e81..108b63f28 100644 --- a/src/Services/Marketing/Marketing.API/Dockerfile +++ b/src/Services/Marketing/Marketing.API/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Services/Marketing/Marketing.API/Marketing.API.csproj b/src/Services/Marketing/Marketing.API/Marketing.API.csproj index 74d7574a6..8eb50e2a3 100644 --- a/src/Services/Marketing/Marketing.API/Marketing.API.csproj +++ b/src/Services/Marketing/Marketing.API/Marketing.API.csproj @@ -9,6 +9,7 @@ /subscriptions/6c22bb55-0221-4ce4-9bf1-3c4a10a7294c/resourcegroups/eshop-log/providers/microsoft.insights/components/eshopappinsights /subscriptions/6c22bb55-0221-4ce4-9bf1-3c4a10a7294c/resourcegroups/eshop-log/providers/microsoft.insights/components/eshopappinsights + 8.0 @@ -30,7 +31,6 @@ - @@ -46,6 +46,7 @@ + diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index 7f990e3ad..cb82dbf88 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -21,8 +21,6 @@ using Infrastructure.Services; using IntegrationEvents.Events; using Marketing.API.IntegrationEvents.Handlers; - using Microsoft.ApplicationInsights.Extensibility; - using Microsoft.ApplicationInsights.ServiceFabric; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Mvc; @@ -30,7 +28,6 @@ using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Middlewares; using Microsoft.Extensions.Diagnostics.HealthChecks; using RabbitMQ.Client; - using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; @@ -63,7 +60,7 @@ services.Configure(Configuration); - ConfigureAuthService(services); + ConfigureAuthService(services); services.AddDbContext(options => { @@ -123,29 +120,32 @@ return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount); }); - } + } // Add framework services. services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info + options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo { Title = "Marketing HTTP API", Version = "v1", - Description = "The Marketing Service HTTP API", - TermsOfService = "Terms Of Service" + Description = "The Marketing Service HTTP API" }); - options.AddSecurityDefinition("oauth2", new OAuth2Scheme + options.AddSecurityDefinition("oauth2", new OpenApi.Models.OpenApiSecurityScheme { - Type = "oauth2", - Flow = "implicit", - AuthorizationUrl = $"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize", - TokenUrl = $"{Configuration.GetValue("IdentityUrlExternal")}/connect/token", - Scopes = new Dictionary() + Flows = new OpenApi.Models.OpenApiOAuthFlows() { - { "marketing", "Marketing API" } + Implicit = new OpenApi.Models.OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "marketing", "Marketing API" } + } + } } }); @@ -178,7 +178,7 @@ } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory) + public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //loggerFactory.AddAzureWebAppDiagnostics(); //loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); @@ -213,7 +213,7 @@ c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Marketing.API V1"); c.OAuthClientId("marketingswaggerui"); c.OAuthAppName("Marketing Swagger UI"); - }); + }); ConfigureEventBus(app); } @@ -228,12 +228,6 @@ // Enable K8s telemetry initializer services.AddApplicationInsightsKubernetesEnricher(); } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } } private void ConfigureAuthService(IServiceCollection services) @@ -241,7 +235,7 @@ // prevent from mapping "sub" claim to nameidentifier. JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); - services.AddAuthentication(options=> + services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; @@ -265,7 +259,7 @@ var serviceBusPersisterConnection = sp.GetRequiredService(); var iLifetimeScope = sp.GetRequiredService(); var logger = sp.GetRequiredService>(); - var eventBusSubcriptionsManager = sp.GetRequiredService(); + var eventBusSubcriptionsManager = sp.GetRequiredService(); return new EventBusServiceBus(serviceBusPersisterConnection, logger, eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope); diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index de5ed4901..6a91b3f6a 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -43,10 +43,15 @@ 3.0.0-preview6.19307.2 3.0.0 4.5.0 - 2.2.2 - 2.2.2 - 2.2.2 - 2.2.2 + + 3.0.0-preview4-19123-01 + 4.7.0-preview6.19303.8 + + 3.0.0-preview6.19304.10 + 3.0.0-preview6.19304.10 + 3.0.0-preview6.19304.10 + 3.0.0-preview6.19304.10 + 2.2.0 2.2.0 2.2.0 From e7f26be573a2717ce3a7b3ef39f2104b5be12a72 Mon Sep 17 00:00:00 2001 From: = Date: Mon, 22 Jul 2019 16:23:30 +0200 Subject: [PATCH 008/113] Migrate locations api --- .../Filters/AuthorizeCheckOperationFilter.cs | 23 +++++++----- .../Filters/HttpGlobalExceptionFilter.cs | 5 +-- .../Locations.API/Locations.API.csproj | 2 ++ .../Location/Locations.API/Startup.cs | 36 +++++++++---------- src/_build/dependencies.props | 4 ++- 5 files changed, 38 insertions(+), 32 deletions(-) diff --git a/src/Services/Location/Locations.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs b/src/Services/Location/Locations.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs index e4194daeb..e2d4c9aed 100644 --- a/src/Services/Location/Locations.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs +++ b/src/Services/Location/Locations.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs @@ -1,6 +1,6 @@  using Microsoft.AspNetCore.Authorization; -using Swashbuckle.AspNetCore.Swagger; +using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using System.Linq; @@ -9,7 +9,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.Filt { internal class AuthorizeCheckOperationFilter : IOperationFilter { - public void Apply(Operation operation, OperationFilterContext context) + public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || @@ -17,16 +17,21 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.Filt if (!hasAuthorize) return; - operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); + operation.Responses.TryAdd("401", new OpenApiResponse() { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new OpenApiResponse() { Description = "Forbidden" }); - operation.Security = new List>> + var oAuthScheme = new OpenApiSecurityScheme { - new Dictionary> - { - { "oauth2", new [] { "locationsapi" } } - } + Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }; + + operation.Security = new List + { + new OpenApiSecurityRequirement + { + [ oAuthScheme ] = new [] { "locationsapi" } + } + }; } } } diff --git a/src/Services/Location/Locations.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs b/src/Services/Location/Locations.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs index 30b9df1fa..12cffe878 100644 --- a/src/Services/Location/Locations.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs +++ b/src/Services/Location/Locations.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs @@ -5,15 +5,16 @@ using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.ActionResults; using Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.Exceptions; + using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Net; public class HttpGlobalExceptionFilter : IExceptionFilter { - private readonly IHostingEnvironment env; + private readonly IHostEnvironment env; private readonly ILogger logger; - public HttpGlobalExceptionFilter(IHostingEnvironment env, ILogger logger) + public HttpGlobalExceptionFilter(IHostEnvironment env, ILogger logger) { this.env = env; this.logger = logger; diff --git a/src/Services/Location/Locations.API/Locations.API.csproj b/src/Services/Location/Locations.API/Locations.API.csproj index 7f658ee2d..653b7b7b5 100644 --- a/src/Services/Location/Locations.API/Locations.API.csproj +++ b/src/Services/Location/Locations.API/Locations.API.csproj @@ -4,6 +4,7 @@ $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj aspnet-Locations.API-20161122013619 + $(LangVersion) @@ -14,6 +15,7 @@ + diff --git a/src/Services/Location/Locations.API/Startup.cs b/src/Services/Location/Locations.API/Startup.cs index 4664381d0..cfb9d7e22 100644 --- a/src/Services/Location/Locations.API/Startup.cs +++ b/src/Services/Location/Locations.API/Startup.cs @@ -1,8 +1,6 @@ using Autofac; using Autofac.Extensions.DependencyInjection; using HealthChecks.UI.Client; -using Microsoft.ApplicationInsights.Extensibility; -using Microsoft.ApplicationInsights.ServiceFabric; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; @@ -23,8 +21,8 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Models; using RabbitMQ.Client; -using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; @@ -50,7 +48,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }) - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); ConfigureAuthService(services); @@ -99,7 +97,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount); }); - } + } RegisterEventBus(services); @@ -107,23 +105,27 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info + options.SwaggerDoc("v1", new OpenApiInfo { Title = "eShopOnContainers - Location HTTP API", Version = "v1", Description = "The Location Microservice HTTP API. This is a Data-Driven/CRUD microservice sample", - TermsOfService = "Terms Of Service" }); - options.AddSecurityDefinition("oauth2", new OAuth2Scheme + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { - Type = "oauth2", - Flow = "implicit", - AuthorizationUrl = $"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize", - TokenUrl = $"{Configuration.GetValue("IdentityUrlExternal")}/connect/token", - Scopes = new Dictionary() + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() { - { "locations", "Locations API" } + Implicit = new OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "locations", "Locations API" } + } + } } }); @@ -204,12 +206,6 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API // Enable K8s telemetry initializer services.AddApplicationInsightsKubernetesEnricher(); } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } } private void ConfigureAuthService(IServiceCollection services) diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index de5ed4901..d3e5890de 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -3,7 +3,7 @@ netstandard2.1 netcoreapp3.0 15.8.0 - latest + preview @@ -37,9 +37,11 @@ 2.6.1 1.0.2 3.0.0-preview6.19307.2 + 3.0.0-preview6.19307.2 2.2.0 1.0.0 2.2.0 + 3.0.0-preview6.19307.2 3.0.0-preview6.19307.2 3.0.0 4.5.0 From 58cf030e02a6d1f7f1ee959fc79807db4eb66616 Mon Sep 17 00:00:00 2001 From: ericuss Date: Mon, 22 Jul 2019 16:52:29 +0200 Subject: [PATCH 009/113] migration of payments api --- src/Services/Payment/Payment.API/Payment.API.csproj | 2 +- src/Services/Payment/Payment.API/Startup.cs | 11 +---------- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/src/Services/Payment/Payment.API/Payment.API.csproj b/src/Services/Payment/Payment.API/Payment.API.csproj index 79e071e76..df0f93690 100644 --- a/src/Services/Payment/Payment.API/Payment.API.csproj +++ b/src/Services/Payment/Payment.API/Payment.API.csproj @@ -4,6 +4,7 @@ $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; + $(LangVersion) @@ -14,7 +15,6 @@ - diff --git a/src/Services/Payment/Payment.API/Startup.cs b/src/Services/Payment/Payment.API/Startup.cs index 39bb78f91..bd3b7241b 100644 --- a/src/Services/Payment/Payment.API/Startup.cs +++ b/src/Services/Payment/Payment.API/Startup.cs @@ -1,9 +1,6 @@ using Autofac; using Autofac.Extensions.DependencyInjection; -using Microsoft.ApplicationInsights.Extensibility; -using Microsoft.ApplicationInsights.ServiceFabric; using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; using Microsoft.Azure.ServiceBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; @@ -90,7 +87,7 @@ namespace Payment.API } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) + public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { //loggerFactory.AddAzureWebAppDiagnostics(); //loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); @@ -126,12 +123,6 @@ namespace Payment.API // Enable K8s telemetry initializer services.AddApplicationInsightsKubernetesEnricher(); } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } } private void RegisterEventBus(IServiceCollection services) From 1e4908484419e6b50b95b57601f3b4652d21ee14 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Tue, 23 Jul 2019 08:30:05 +0200 Subject: [PATCH 010/113] netcore 3 ordering --- .../Location/Locations.API/Dockerfile | 4 +- src/Services/Ordering/Ordering.API/Dockerfile | 4 +- .../Ordering/Ordering.API/Ordering.API.csproj | 14 +++--- src/Services/Ordering/Ordering.API/Startup.cs | 43 ++++++++----------- .../Ordering.BackgroundTasks/Dockerfile | 4 +- .../Ordering.Domain/Ordering.Domain.csproj | 4 +- .../Ordering.Infrastructure.csproj | 2 +- .../Ordering/Ordering.SignalrHub/Dockerfile | 4 +- .../Ordering.SignalrHub.csproj | 10 +++-- .../Ordering/Ordering.SignalrHub/Startup.cs | 7 ++- src/_build/dependencies.props | 11 +++-- 11 files changed, 53 insertions(+), 54 deletions(-) diff --git a/src/Services/Location/Locations.API/Dockerfile b/src/Services/Location/Locations.API/Dockerfile index 8a173cbc1..d61b5dbdd 100644 --- a/src/Services/Location/Locations.API/Dockerfile +++ b/src/Services/Location/Locations.API/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Services/Ordering/Ordering.API/Dockerfile b/src/Services/Ordering/Ordering.API/Dockerfile index 63813c5ae..dcb0d3022 100644 --- a/src/Services/Ordering/Ordering.API/Dockerfile +++ b/src/Services/Ordering/Ordering.API/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Services/Ordering/Ordering.API/Ordering.API.csproj b/src/Services/Ordering/Ordering.API/Ordering.API.csproj index 4bbfab9d4..ea2ac2d77 100644 --- a/src/Services/Ordering/Ordering.API/Ordering.API.csproj +++ b/src/Services/Ordering/Ordering.API/Ordering.API.csproj @@ -5,7 +5,7 @@ aspnet-Ordering.API-20161122013547 $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj - latest + 8.0 @@ -33,14 +33,13 @@ - - + + - + - @@ -53,8 +52,9 @@ - - + + + diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index b77354052..9f8de6092 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -7,13 +7,12 @@ using global::Ordering.API.Application.IntegrationEvents.Events; using global::Ordering.API.Infrastructure.Filters; using global::Ordering.API.Infrastructure.Middlewares; + using HealthChecks.UI.Client; using Infrastructure.AutofacModules; using Infrastructure.Filters; using Infrastructure.Services; - using Microsoft.ApplicationInsights.Extensibility; - using Microsoft.ApplicationInsights.ServiceFabric; - using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.ServiceBus; @@ -26,18 +25,15 @@ using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Ordering.Infrastructure; using RabbitMQ.Client; - using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; using System.Data.Common; using System.IdentityModel.Tokens.Jwt; using System.Reflection; - using HealthChecks.UI.Client; - using Microsoft.AspNetCore.Diagnostics.HealthChecks; - using Microsoft.Extensions.Diagnostics.HealthChecks; public class Startup { @@ -148,12 +144,6 @@ // Enable K8s telemetry initializer services.AddApplicationInsightsKubernetesEnricher(); } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } return services; } @@ -249,23 +239,26 @@ services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info + options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo { Title = "Ordering HTTP API", Version = "v1", - Description = "The Ordering Service HTTP API", - TermsOfService = "Terms Of Service" + Description = "The Ordering Service HTTP API" }); - options.AddSecurityDefinition("oauth2", new OAuth2Scheme + options.AddSecurityDefinition("oauth2", new OpenApi.Models.OpenApiSecurityScheme { - Type = "oauth2", - Flow = "implicit", - AuthorizationUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize", - TokenUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/token", - Scopes = new Dictionary() + Flows = new OpenApi.Models.OpenApiOAuthFlows() { - { "orders", "Ordering API" } + Implicit = new OpenApi.Models.OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "orders", "Ordering API" } + } + } } }); @@ -407,8 +400,8 @@ services.AddAuthentication(options => { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultAuthenticateScheme = AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile index f1dbea6b1..820f8d4b1 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj b/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj index eac16c43f..626c6e526 100644 --- a/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj +++ b/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj @@ -6,8 +6,8 @@ - - + + diff --git a/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj b/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj index 6f7f59f9e..1ec58ec38 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj +++ b/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj @@ -11,7 +11,7 @@ - + diff --git a/src/Services/Ordering/Ordering.SignalrHub/Dockerfile b/src/Services/Ordering/Ordering.SignalrHub/Dockerfile index 1dfffd839..15389786c 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Dockerfile +++ b/src/Services/Ordering/Ordering.SignalrHub/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj index 52cd6d24a..82e1a0df9 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj +++ b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj @@ -3,6 +3,8 @@ $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj + $(PackageTargetFallback);portable-net45+win8+wp8+wpa81; + $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; @@ -17,13 +19,12 @@ - - - - + + + @@ -31,6 +32,7 @@ + diff --git a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs index edcc80521..c754d98e4 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs @@ -1,7 +1,8 @@ using Autofac; using Autofac.Extensions.DependencyInjection; -using Microsoft.AspNetCore.Authentication.JwtBearer; +using HealthChecks.UI.Client; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Azure.ServiceBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; @@ -9,6 +10,7 @@ using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ; using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Ordering.SignalrHub.AutofacModules; using Ordering.SignalrHub.IntegrationEvents; @@ -17,9 +19,6 @@ using Ordering.SignalrHub.IntegrationEvents.Events; using RabbitMQ.Client; using System; using System.IdentityModel.Tokens.Jwt; -using HealthChecks.UI.Client; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.Extensions.Diagnostics.HealthChecks; namespace Ordering.SignalrHub { diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 6a91b3f6a..9a37da908 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -32,7 +32,14 @@ 4.9.2 4.2.1 1.50.7 + 4.3.0 + 4.5.1 + 4.5.0 5.1.0 + 3.0.0-preview4-19123-01 + 3.0.0-preview4-19123-01 + 3.0.0-alpha1-34847 + 5.1.0 2.2.1 2.6.1 1.0.2 @@ -43,15 +50,13 @@ 3.0.0-preview6.19307.2 3.0.0 4.5.0 - 3.0.0-preview4-19123-01 4.7.0-preview6.19303.8 - + 7.5.0 3.0.0-preview6.19304.10 3.0.0-preview6.19304.10 3.0.0-preview6.19304.10 3.0.0-preview6.19304.10 - 2.2.0 2.2.0 2.2.0 From 1c5c0c11c4b0b9858497c2e98047d5a176505b79 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Tue, 23 Jul 2019 09:41:04 +0200 Subject: [PATCH 011/113] fix error csproj --- .../Ordering.SignalrHub/Ordering.SignalrHub.csproj | 11 +++++------ src/Services/Ordering/Ordering.SignalrHub/Startup.cs | 5 +++-- src/_build/dependencies.props | 2 -- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj index 82e1a0df9..e4084087f 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj +++ b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj @@ -3,10 +3,12 @@ $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj - $(PackageTargetFallback);portable-net45+win8+wp8+wpa81; - $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; + false + 8.0 + + @@ -19,12 +21,9 @@ - - - - + diff --git a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs index c754d98e4..329fba070 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs @@ -1,6 +1,7 @@ using Autofac; using Autofac.Extensions.DependencyInjection; using HealthChecks.UI.Client; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Azure.ServiceBus; @@ -147,9 +148,9 @@ namespace Ordering.SignalrHub app.UseAuthentication(); - app.UseSignalR(routes => + app.UseEndpoints(endpoints => { - routes.MapHub("/notificationhub", options => + endpoints.MapHub("/notificationhub", options => options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransports.All); }); diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 9f1cd07d1..809b3e08c 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -36,8 +36,6 @@ 4.5.1 4.5.0 5.1.0 - 3.0.0-preview4-19123-01 - 3.0.0-preview4-19123-01 3.0.0-alpha1-34847 5.1.0 2.2.1 From 5b5b0d1b7d1b103dab37c22b13e86021c212615a Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Tue, 23 Jul 2019 10:07:50 +0200 Subject: [PATCH 012/113] migrate bffs --- src/ApiGateways/ApiGw-Base/Dockerfile | 4 +- src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj | 1 + src/ApiGateways/ApiGw-Base/Program.cs | 10 ++--- src/ApiGateways/ApiGw-Base/Startup.cs | 7 ++-- .../Mobile.Bff.Shopping/aggregator/Dockerfile | 4 +- .../Filters/AuthorizeCheckOperationFilter.cs | 19 +++++---- .../Mobile.Shopping.HttpAggregator.csproj | 3 ++ .../Mobile.Bff.Shopping/aggregator/Program.cs | 9 +--- .../Mobile.Bff.Shopping/aggregator/Startup.cs | 42 ++++++++++--------- .../Web.Bff.Shopping/aggregator/Dockerfile | 4 +- .../Filters/AuthorizeCheckOperationFilter.cs | 19 +++++---- .../Web.Bff.Shopping/aggregator/Program.cs | 9 +--- .../Web.Bff.Shopping/aggregator/Startup.cs | 37 ++++++++-------- .../Web.Shopping.HttpAggregator.csproj | 3 ++ .../Marketing/Marketing.API/Startup.cs | 2 +- .../Filters/AuthorizeCheckOperationFilter.cs | 25 ++++++----- src/Services/Ordering/Ordering.API/Startup.cs | 2 +- 17 files changed, 102 insertions(+), 98 deletions(-) diff --git a/src/ApiGateways/ApiGw-Base/Dockerfile b/src/ApiGateways/ApiGw-Base/Dockerfile index 9dc86a846..0d66ada6b 100644 --- a/src/ApiGateways/ApiGw-Base/Dockerfile +++ b/src/ApiGateways/ApiGw-Base/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj index ea011f624..8f311ab77 100644 --- a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj +++ b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj @@ -12,5 +12,6 @@ + diff --git a/src/ApiGateways/ApiGw-Base/Program.cs b/src/ApiGateways/ApiGw-Base/Program.cs index bcf1c8d60..4e689d5a1 100644 --- a/src/ApiGateways/ApiGw-Base/Program.cs +++ b/src/ApiGateways/ApiGw-Base/Program.cs @@ -1,14 +1,10 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore; +using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Serilog; +using System.IO; namespace OcelotApiGw { diff --git a/src/ApiGateways/ApiGw-Base/Startup.cs b/src/ApiGateways/ApiGw-Base/Startup.cs index 585c26471..be845edca 100644 --- a/src/ApiGateways/ApiGw-Base/Startup.cs +++ b/src/ApiGateways/ApiGw-Base/Startup.cs @@ -1,14 +1,13 @@ -using Microsoft.AspNetCore.Builder; +using HealthChecks.UI.Client; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Ocelot.DependencyInjection; using Ocelot.Middleware; using System; -using HealthChecks.UI.Client; -using Microsoft.Extensions.Diagnostics.HealthChecks; namespace OcelotApiGw { diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile index 9b03eccbd..3d89c9b27 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs index 21997360b..3b8298bfe 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs @@ -1,7 +1,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Filters { using Microsoft.AspNetCore.Authorization; - using Swashbuckle.AspNetCore.Swagger; + using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using System.Linq; @@ -10,7 +10,7 @@ { public class AuthorizeCheckOperationFilter : IOperationFilter { - public void Apply(Operation operation, OperationFilterContext context) + public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || @@ -18,14 +18,19 @@ if (!hasAuthorize) return; - operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); + operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" }); - operation.Security = new List>> + var oAuthScheme = new OpenApiSecurityScheme { - new Dictionary> + Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } + }; + + operation.Security = new List + { + new OpenApiSecurityRequirement { - { "oauth2", new [] { "Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator" } } + [ oAuthScheme ] = new [] { "Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator" } } }; } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj index 6efbcf389..87e6c31b3 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj @@ -5,6 +5,8 @@ Mobile.Shopping.HttpAggregator Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator ..\..\..\docker-compose.dcproj + false + 8.0 @@ -20,6 +22,7 @@ + diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs index fc21a70a4..5d1840192 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore; +using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; using Serilog; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index eee0d9c6e..a2997be05 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -1,9 +1,8 @@ -using System; -using System.Collections.Generic; -using System.IdentityModel.Tokens.Jwt; -using System.Net.Http; +using Devspaces.Support; +using HealthChecks.UI.Client; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -13,14 +12,14 @@ using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastructure; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Polly; using Polly.Extensions.Http; -using Swashbuckle.AspNetCore.Swagger; -using HealthChecks.UI.Client; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.Extensions.Diagnostics.HealthChecks; -using Devspaces.Support; +using System; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Net.Http; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator { @@ -110,28 +109,31 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator services.Configure(configuration.GetSection("urls")); services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info + options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo { Title = "Shopping Aggregator for Mobile Clients", Version = "v1", - Description = "Shopping Aggregator for Mobile Clients", - TermsOfService = "Terms Of Service" + Description = "Shopping Aggregator for Mobile Clients" }); - options.AddSecurityDefinition("oauth2", new OAuth2Scheme + options.AddSecurityDefinition("oauth2", new OpenApi.Models.OpenApiSecurityScheme { - Type = "oauth2", - Flow = "implicit", - AuthorizationUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize", - TokenUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/token", - Scopes = new Dictionary() + Flows = new OpenApi.Models.OpenApiOAuthFlows() { - { "mobileshoppingagg", "Shopping Aggregator for Mobile Clients" } + Implicit = new OpenApi.Models.OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "marketing", "Marketing API" } + } + } } }); diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile b/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile index fbce2f0ab..2a3b551a2 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs index e93ec157c..45c191104 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs @@ -1,7 +1,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Filters { using Microsoft.AspNetCore.Authorization; - using Swashbuckle.AspNetCore.Swagger; + using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using System.Linq; @@ -10,7 +10,7 @@ { public class AuthorizeCheckOperationFilter : IOperationFilter { - public void Apply(Operation operation, OperationFilterContext context) + public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || @@ -18,14 +18,19 @@ if (!hasAuthorize) return; - operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); + operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" }); - operation.Security = new List>> + var oAuthScheme = new OpenApiSecurityScheme { - new Dictionary> + Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } + }; + + operation.Security = new List + { + new OpenApiSecurityRequirement { - { "oauth2", new [] { "Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator" } } + [ oAuthScheme ] = new [] { "Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator" } } }; } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Program.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Program.cs index 4bbac21e6..6589719fa 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Program.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Program.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore; +using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; using Serilog; namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index dd5e1cc8c..747269f50 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -1,5 +1,8 @@ -using Microsoft.AspNetCore.Authentication.JwtBearer; +using Devspaces.Support; +using HealthChecks.UI.Client; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -9,19 +12,14 @@ using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Infrastructure; using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Polly; using Polly.Extensions.Http; -using Polly.Timeout; -using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Net.Http; -using HealthChecks.UI.Client; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.Extensions.Diagnostics.HealthChecks; -using Devspaces.Support; namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator { @@ -137,28 +135,31 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator services.Configure(configuration.GetSection("urls")); services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info + options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo { Title = "Shopping Aggregator for Web Clients", Version = "v1", - Description = "Shopping Aggregator for Web Clients", - TermsOfService = "Terms Of Service" + Description = "Shopping Aggregator for Web Clients" }); - options.AddSecurityDefinition("oauth2", new OAuth2Scheme + options.AddSecurityDefinition("oauth2", new OpenApi.Models.OpenApiSecurityScheme { - Type = "oauth2", - Flow = "implicit", - AuthorizationUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize", - TokenUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/token", - Scopes = new Dictionary() + Flows = new OpenApi.Models.OpenApiOAuthFlows() { - { "webshoppingagg", "Shopping Aggregator for Web Clients" } + Implicit = new OpenApi.Models.OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "webshoppingagg", "Shopping Aggregator for Web Clients" } + } + } } }); diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj index faa609b06..b7eb1a019 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj @@ -5,6 +5,8 @@ Web.Shopping.HttpAggregator Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator ..\..\..\docker-compose.dcproj + false + 8.0 @@ -19,6 +21,7 @@ + diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index cb82dbf88..187915343 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -55,7 +55,7 @@ { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }) - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); //Injecting Controllers themselves thru DIFor further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services services.Configure(Configuration); diff --git a/src/Services/Ordering/Ordering.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs b/src/Services/Ordering/Ordering.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs index ee0301cc5..34b897a40 100644 --- a/src/Services/Ordering/Ordering.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs +++ b/src/Services/Ordering/Ordering.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs @@ -1,16 +1,14 @@ using Microsoft.AspNetCore.Authorization; -using Swashbuckle.AspNetCore.Swagger; +using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; -using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; namespace Ordering.API.Infrastructure.Filters { public class AuthorizeCheckOperationFilter : IOperationFilter { - public void Apply(Operation operation, OperationFilterContext context) + public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || @@ -18,16 +16,21 @@ namespace Ordering.API.Infrastructure.Filters if (!hasAuthorize) return; - operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); + operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" }); - operation.Security = new List>> + var oAuthScheme = new OpenApiSecurityScheme { - new Dictionary> - { - { "oauth2", new [] { "orderingapi" } } - } + Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }; + + operation.Security = new List + { + new OpenApiSecurityRequirement + { + [ oAuthScheme ] = new [] { "orderingapi" } + } + }; } } } \ No newline at end of file diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index 9f8de6092..195fb90b7 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -155,7 +155,7 @@ { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }) - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); //Injecting Controllers themselves thru DI //For further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services From 31f77cb79e587b451a29457b8b28d63a7c2c0793 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Tue, 23 Jul 2019 10:26:33 +0200 Subject: [PATCH 013/113] update version and image docker --- .../Marketing/Marketing.API/Startup.cs | 3 ++- src/Services/Ordering/Ordering.API/Startup.cs | 5 ++-- .../Ordering/Ordering.SignalrHub/Startup.cs | 1 + src/Services/Payment/Payment.API/Dockerfile | 4 +-- src/Services/Webhooks/Webhooks.API/Dockerfile | 4 +-- src/Web/WebStatus/Dockerfile | 4 +-- src/Web/WebStatus/Program.cs | 2 +- src/Web/WebStatus/Startup.cs | 26 ++++++------------- 8 files changed, 21 insertions(+), 28 deletions(-) diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index cb82dbf88..bada0ec99 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -205,7 +205,8 @@ ConfigureAuth(app); - app.UseMvcWithDefaultRoute(); + app.UseRouting(); + app.UseEndpoints(e => e.MapDefaultControllerRoute()); app.UseSwagger() .UseSwaggerUI(c => diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index 9f8de6092..e4193a5f2 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -95,7 +95,8 @@ ConfigureAuth(app); - app.UseMvcWithDefaultRoute(); + app.UseRouting(); + app.UseEndpoints(e => e.MapDefaultControllerRoute()); app.UseSwagger() .UseSwaggerUI(c => @@ -155,7 +156,7 @@ { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }) - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); //Injecting Controllers themselves thru DI //For further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services diff --git a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs index 329fba070..23bca1977 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs @@ -148,6 +148,7 @@ namespace Ordering.SignalrHub app.UseAuthentication(); + app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHub("/notificationhub", options => diff --git a/src/Services/Payment/Payment.API/Dockerfile b/src/Services/Payment/Payment.API/Dockerfile index 65baf8278..1f2ab41d1 100644 --- a/src/Services/Payment/Payment.API/Dockerfile +++ b/src/Services/Payment/Payment.API/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Services/Webhooks/Webhooks.API/Dockerfile b/src/Services/Webhooks/Webhooks.API/Dockerfile index 9cc1828d9..5d3f6da5a 100644 --- a/src/Services/Webhooks/Webhooks.API/Dockerfile +++ b/src/Services/Webhooks/Webhooks.API/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Web/WebStatus/Dockerfile b/src/Web/WebStatus/Dockerfile index 92c1b2717..35c81d594 100644 --- a/src/Web/WebStatus/Dockerfile +++ b/src/Web/WebStatus/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Web/WebStatus/Program.cs b/src/Web/WebStatus/Program.cs index c8c850cfd..efe3f051b 100644 --- a/src/Web/WebStatus/Program.cs +++ b/src/Web/WebStatus/Program.cs @@ -54,7 +54,7 @@ namespace WebStatus .UseSerilog() .Build(); - private static Serilog.ILogger CreateSerilogLogger(IConfiguration configuration) + private static Serilog.ILogger CreateSerilogLogger(IConfiguration configuration) { var seqServerUrl = configuration["Serilog:SeqServerUrl"]; var logstashUrl = configuration["Serilog:LogstashgUrl"]; diff --git a/src/Web/WebStatus/Startup.cs b/src/Web/WebStatus/Startup.cs index d36b2df90..48875eab5 100644 --- a/src/Web/WebStatus/Startup.cs +++ b/src/Web/WebStatus/Startup.cs @@ -1,7 +1,4 @@ -using HealthChecks.UI.Client; -using Microsoft.ApplicationInsights.Extensibility; -using Microsoft.ApplicationInsights.ServiceFabric; -using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; @@ -31,7 +28,7 @@ namespace WebStatus .AddCheck("self", () => HealthCheckResult.Healthy()); services.AddHealthChecksUI(); - + services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); } @@ -64,20 +61,19 @@ namespace WebStatus Predicate = r => r.Name.Contains("self") }); - app.UseHealthChecksUI(config => { + app.UseHealthChecksUI(config => + { config.ResourcesPath = string.IsNullOrEmpty(pathBase) ? "/ui/resources" : $"{pathBase}/ui/resources"; - config.UIPath = "/hc-ui"; + config.UIPath = "/hc-ui"; }); - + app.UseStaticFiles(); app.UseHttpsRedirection(); - app.UseMvc(routes => + app.UseEndpoints(endpoints => { - routes.MapRoute( - name: "default", - template: "{controller=Home}/{action=Index}/{id?}"); + endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); } @@ -91,12 +87,6 @@ namespace WebStatus // Enable K8s telemetry initializer services.AddApplicationInsightsKubernetesEnricher(); } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } } } } From 756142db943f4036c24766ddb449d082207029b5 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Tue, 23 Jul 2019 12:14:09 +0200 Subject: [PATCH 014/113] upgrade net3 webapp --- src/Services/Basket/Basket.API/Startup.cs | 34 +++----- src/Services/Catalog/Catalog.API/Startup.cs | 35 ++++---- src/Services/Identity/Identity.API/Startup.cs | 26 ++---- .../Location/Locations.API/Startup.cs | 33 +++---- .../Marketing/Marketing.API/Startup.cs | 33 +++---- src/Services/Ordering/Ordering.API/Startup.cs | 22 +++-- .../Ordering.BackgroundTasks/Startup.cs | 26 +++--- .../Ordering/Ordering.SignalrHub/Startup.cs | 26 +++--- src/Services/Payment/Payment.API/Startup.cs | 40 ++++----- .../WebMVC/Controllers/AccountController.cs | 11 ++- src/Web/WebMVC/Dockerfile | 4 +- src/Web/WebMVC/Startup.cs | 85 +++++++++++-------- src/Web/WebMVC/WebMVC.csproj | 14 +-- src/Web/WebSPA/Dockerfile | 4 +- src/Web/WebSPA/Startup.cs | 60 +++++-------- src/Web/WebSPA/WebSPA.csproj | 4 +- src/Web/WebSPA/package.json | 2 +- src/Web/WebStatus/Startup.cs | 17 ++-- src/Web/WebStatus/WebStatus.csproj | 3 +- .../Controllers/AccountController.cs | 3 - src/Web/WebhookClient/Dockerfile | 4 +- src/Web/WebhookClient/WebhookClient.csproj | 11 ++- src/_build/dependencies.props | 11 ++- 23 files changed, 241 insertions(+), 267 deletions(-) diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index 79208b19b..46599c616 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -28,7 +28,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using RabbitMQ.Client; using StackExchange.Redis; -using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; @@ -191,24 +190,25 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UsePathBase(pathBase); } - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - app.UseStaticFiles(); app.UseCors("CorsPolicy"); ConfigureAuth(app); app.UseRouting(); - app.UseEndpoints(e => e.MapDefaultControllerRoute()); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + endpoints.MapDefaultControllerRoute(); + }); app.UseSwagger() .UseSwaggerUI(c => @@ -225,13 +225,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API private void RegisterAppInsights(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration); - var orchestratorType = Configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } + services.AddApplicationInsightsKubernetesEnricher(); } private void ConfigureAuthService(IServiceCollection services) diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 716e0f1ca..c34db7614 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -1,8 +1,11 @@ using Autofac; using Autofac.Extensions.DependencyInjection; +using Catalog.API.Grpc; using global::Catalog.API.Infrastructure.Filters; using global::Catalog.API.IntegrationEvents; +using HealthChecks.UI.Client; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -20,17 +23,14 @@ using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.EventHa using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using RabbitMQ.Client; using System; using System.Data.Common; -using System.Reflection; -using HealthChecks.UI.Client; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.Extensions.Diagnostics.HealthChecks; -using Catalog.API.Grpc; using System.IO; +using System.Reflection; namespace Microsoft.eShopOnContainers.Services.Catalog.API { @@ -89,10 +89,10 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API app.UseCors("CorsPolicy"); app.UseRouting(); - app.UseEndpoints(e => + app.UseEndpoints(endpoints => { - e.MapDefaultControllerRoute(); - e.MapGet("/_proto/", async ctx => + endpoints.MapDefaultControllerRoute(); + endpoints.MapGet("/_proto/", async ctx => { ctx.Response.ContentType = "text/plain"; using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "catalog.proto"), FileMode.Open, FileAccess.Read); @@ -106,7 +106,16 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API } } }); - e.MapGrpcService(); + endpoints.MapGrpcService(); + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); }); app.UseSwagger() @@ -131,13 +140,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API public static IServiceCollection AddAppInsight(this IServiceCollection services, IConfiguration configuration) { services.AddApplicationInsightsTelemetry(configuration); - var orchestratorType = configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } + services.AddApplicationInsightsKubernetesEnricher(); return services; } diff --git a/src/Services/Identity/Identity.API/Startup.cs b/src/Services/Identity/Identity.API/Startup.cs index 6ea7e3888..009773b62 100644 --- a/src/Services/Identity/Identity.API/Startup.cs +++ b/src/Services/Identity/Identity.API/Startup.cs @@ -1,28 +1,26 @@ using Autofac; using Autofac.Extensions.DependencyInjection; +using HealthChecks.UI.Client; using IdentityServer4.Services; -using Microsoft.ApplicationInsights.Extensibility; -using Microsoft.ApplicationInsights.ServiceFabric; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Identity.API.Certificates; using Microsoft.eShopOnContainers.Services.Identity.API.Data; +using Microsoft.eShopOnContainers.Services.Identity.API.Devspaces; using Microsoft.eShopOnContainers.Services.Identity.API.Models; using Microsoft.eShopOnContainers.Services.Identity.API.Services; -using Microsoft.eShopOnContainers.Services.Identity.API.Devspaces; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using StackExchange.Redis; using System; using System.Reflection; -using HealthChecks.UI.Client; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.Extensions.Diagnostics.HealthChecks; namespace Microsoft.eShopOnContainers.Services.Identity.API { @@ -73,7 +71,7 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API .AddSqlServer(Configuration["ConnectionString"], name: "IdentityDB-check", tags: new string[] { "IdentityDB" }); - + services.AddTransient, EFLoginService>(); services.AddTransient(); @@ -179,19 +177,7 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API private void RegisterAppInsights(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration); - var orchestratorType = Configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } + services.AddApplicationInsightsKubernetesEnricher(); } } } diff --git a/src/Services/Location/Locations.API/Startup.cs b/src/Services/Location/Locations.API/Startup.cs index cfb9d7e22..7b4a391af 100644 --- a/src/Services/Location/Locations.API/Startup.cs +++ b/src/Services/Location/Locations.API/Startup.cs @@ -167,22 +167,23 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API app.UsePathBase(pathBase); } - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - app.UseCors("CorsPolicy"); ConfigureAuth(app); - app.UseMvcWithDefaultRoute(); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + }); app.UseSwagger() .UseSwaggerUI(c => @@ -199,13 +200,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API private void RegisterAppInsights(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration); - var orchestratorType = Configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } + services.AddApplicationInsightsKubernetesEnricher(); } private void ConfigureAuthService(IServiceCollection services) diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index 3e9c92324..289a9c351 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -190,23 +190,24 @@ app.UsePathBase(pathBase); } - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - app.UseCors("CorsPolicy"); ConfigureAuth(app); app.UseRouting(); - app.UseEndpoints(e => e.MapDefaultControllerRoute()); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + endpoints.MapDefaultControllerRoute(); + }); app.UseSwagger() .UseSwaggerUI(c => @@ -222,13 +223,7 @@ private void RegisterAppInsights(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration); - var orchestratorType = Configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } + services.AddApplicationInsightsKubernetesEnricher(); } private void ConfigureAuthService(IServiceCollection services) diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index e4193a5f2..de9a88af1 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -96,7 +96,19 @@ ConfigureAuth(app); app.UseRouting(); - app.UseEndpoints(e => e.MapDefaultControllerRoute()); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + endpoints.MapDefaultControllerRoute(); + }); app.UseSwagger() .UseSwaggerUI(c => @@ -138,13 +150,7 @@ public static IServiceCollection AddApplicationInsights(this IServiceCollection services, IConfiguration configuration) { services.AddApplicationInsightsTelemetry(configuration); - var orchestratorType = configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } + services.AddApplicationInsightsKubernetesEnricher(); return services; } diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs index 9d6a78e38..6035beaeb 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs @@ -1,7 +1,8 @@ using Autofac; using Autofac.Extensions.DependencyInjection; +using HealthChecks.UI.Client; using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Azure.ServiceBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; @@ -9,15 +10,13 @@ using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ; using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Ordering.BackgroundTasks.Configuration; using Ordering.BackgroundTasks.Tasks; using RabbitMQ.Client; using System; -using HealthChecks.UI.Client; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.Extensions.Diagnostics.HealthChecks; namespace Ordering.BackgroundTasks { @@ -106,15 +105,18 @@ namespace Ordering.BackgroundTasks // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { - app.UseHealthChecks("/hc", new HealthCheckOptions() + app.UseRouting(); + app.UseEndpoints(endpoints => { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); }); } diff --git a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs index 23bca1977..78f10adb3 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs @@ -127,32 +127,28 @@ namespace Ordering.SignalrHub //loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); var pathBase = Configuration["PATH_BASE"]; + if (!string.IsNullOrEmpty(pathBase)) { loggerFactory.CreateLogger().LogDebug("Using PATH BASE '{pathBase}'", pathBase); app.UsePathBase(pathBase); } - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - app.UseCors("CorsPolicy"); - app.UseAuthentication(); - app.UseRouting(); app.UseEndpoints(endpoints => { - endpoints.MapHub("/notificationhub", options => - options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransports.All); + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + endpoints.MapHub("/notificationhub", options => options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransports.All); }); ConfigureEventBus(app); diff --git a/src/Services/Payment/Payment.API/Startup.cs b/src/Services/Payment/Payment.API/Startup.cs index bd3b7241b..77b8d55fd 100644 --- a/src/Services/Payment/Payment.API/Startup.cs +++ b/src/Services/Payment/Payment.API/Startup.cs @@ -1,6 +1,8 @@ using Autofac; using Autofac.Extensions.DependencyInjection; +using HealthChecks.UI.Client; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Azure.ServiceBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; @@ -8,14 +10,12 @@ using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ; using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Payment.API.IntegrationEvents.EventHandling; using Payment.API.IntegrationEvents.Events; using RabbitMQ.Client; using System; -using HealthChecks.UI.Client; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.Extensions.Diagnostics.HealthChecks; namespace Payment.API { @@ -77,7 +77,7 @@ namespace Payment.API return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount); }); - } + } RegisterEventBus(services); @@ -98,31 +98,27 @@ namespace Payment.API app.UsePathBase(pathBase); } + ConfigureEventBus(app); - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions + app.UseRouting(); + app.UseEndpoints(endpoints => { - Predicate = r => r.Name.Contains("self") + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); }); - - ConfigureEventBus(app); } private void RegisterAppInsights(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration); - var orchestratorType = Configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } + services.AddApplicationInsightsKubernetesEnricher(); } private void RegisterEventBus(IServiceCollection services) @@ -136,7 +132,7 @@ namespace Payment.API var serviceBusPersisterConnection = sp.GetRequiredService(); var iLifetimeScope = sp.GetRequiredService(); var logger = sp.GetRequiredService>(); - var eventBusSubcriptionsManager = sp.GetRequiredService(); + var eventBusSubcriptionsManager = sp.GetRequiredService(); return new EventBusServiceBus(serviceBusPersisterConnection, logger, eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope); diff --git a/src/Web/WebMVC/Controllers/AccountController.cs b/src/Web/WebMVC/Controllers/AccountController.cs index f4562b169..de10770f5 100644 --- a/src/Web/WebMVC/Controllers/AccountController.cs +++ b/src/Web/WebMVC/Controllers/AccountController.cs @@ -1,13 +1,12 @@ -using System.Security.Claims; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http.Authentication; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.OpenIdConnect; -using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.Extensions.Logging; using System; +using System.Security.Claims; +using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.WebMVC.Controllers { diff --git a/src/Web/WebMVC/Dockerfile b/src/Web/WebMVC/Dockerfile index 0e3445b57..c32a34295 100644 --- a/src/Web/WebMVC/Dockerfile +++ b/src/Web/WebMVC/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Web/WebMVC/Startup.cs b/src/Web/WebMVC/Startup.cs index 52a311369..e9c0a519f 100644 --- a/src/Web/WebMVC/Startup.cs +++ b/src/Web/WebMVC/Startup.cs @@ -1,9 +1,7 @@ using Devspaces.Support; using HealthChecks.UI.Client; -using Microsoft.ApplicationInsights.Extensibility; -using Microsoft.ApplicationInsights.ServiceFabric; using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; @@ -56,13 +54,6 @@ namespace Microsoft.eShopOnContainers.WebMVC //loggerFactory.AddAzureWebAppDiagnostics(); //loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); - - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); @@ -80,11 +71,6 @@ namespace Microsoft.eShopOnContainers.WebMVC app.UsePathBase(pathBase); } - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - app.UseSession(); app.UseStaticFiles(); @@ -98,15 +84,20 @@ namespace Microsoft.eShopOnContainers.WebMVC WebContextSeed.Seed(app, env, loggerFactory); app.UseHttpsRedirection(); - app.UseMvc(routes => + app.UseRouting(); + app.UseEndpoints(endpoints => { - routes.MapRoute( - name: "default", - template: "{controller=Catalog}/{action=Index}/{id?}"); - - routes.MapRoute( - name: "defaultError", - template: "{controller=Error}/{action=Error}"); + endpoints.MapControllerRoute("default", "{controller=Catalog}/{action=Index}/{id?}"); + endpoints.MapControllerRoute("defaultError", "{controller=Error}/{action=Error}"); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); }); } } @@ -125,13 +116,6 @@ namespace Microsoft.eShopOnContainers.WebMVC services.AddApplicationInsightsKubernetesEnricher(); } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } - return services; } @@ -141,8 +125,8 @@ namespace Microsoft.eShopOnContainers.WebMVC .AddCheck("self", () => HealthCheckResult.Healthy()) .AddUrlGroup(new Uri(configuration["PurchaseUrlHC"]), name: "purchaseapigw-check", tags: new string[] { "purchaseapigw" }) .AddUrlGroup(new Uri(configuration["MarketingUrlHC"]), name: "marketingapigw-check", tags: new string[] { "marketingapigw" }) - .AddUrlGroup(new Uri(configuration["IdentityUrlHC"]), name: "identityapi-check", tags: new string[] { "identityapi" }); - + .AddUrlGroup(new Uri(configuration["IdentityUrlHC"]), name: "identityapi-check", tags: new string[] { "identityapi" }); + return services; } @@ -152,7 +136,7 @@ namespace Microsoft.eShopOnContainers.WebMVC services.Configure(configuration); services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddSession(); @@ -245,10 +229,10 @@ namespace Microsoft.eShopOnContainers.WebMVC services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) - .AddCookie(setup=>setup.ExpireTimeSpan = TimeSpan.FromMinutes(sessionCookieLifetime)) - .AddOpenIdConnect(options => + .AddCookie(setup => setup.ExpireTimeSpan = TimeSpan.FromMinutes(sessionCookieLifetime)) + .AddJwtBearer(options => { options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.Authority = identityUrl.ToString(); @@ -266,7 +250,34 @@ namespace Microsoft.eShopOnContainers.WebMVC options.Scope.Add("marketing"); options.Scope.Add("locations"); options.Scope.Add("webshoppingagg"); - options.Scope.Add("orders.signalrhub"); + options.Scope.Add("orders.signalrhub"); + + /*options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; + options.Authority = identityUrl.ToString(); + options.SignedOutRedirectUri = callBackUrl.ToString(); + options.ClientId = useLoadTest ? "mvctest" : "mvc"; + options.ClientSecret = "secret"; + + if (useLoadTest) + { + options.Configuration.ResponseTypesSupported.Add("code id_token token"); + } + else + { + options.Configuration.ResponseTypesSupported.Add("code id_token"); + } + + options.SaveToken = true; + options.GetClaimsFromUserInfoEndpoint = true; + options.RequireHttpsMetadata = false; + options.Configuration.ScopesSupported.Add("openid"); + options.Configuration.ScopesSupported.Add("profile"); + options.Configuration.ScopesSupported.Add("orders"); + options.Configuration.ScopesSupported.Add("basket"); + options.Configuration.ScopesSupported.Add("marketing"); + options.Configuration.ScopesSupported.Add("locations"); + options.Configuration.ScopesSupported.Add("webshoppingagg"); + options.Configuration.ScopesSupported.Add("orders.signalrhub");*/ }); return services; diff --git a/src/Web/WebMVC/WebMVC.csproj b/src/Web/WebMVC/WebMVC.csproj index 42f8f16dd..adfc5587e 100644 --- a/src/Web/WebMVC/WebMVC.csproj +++ b/src/Web/WebMVC/WebMVC.csproj @@ -5,6 +5,8 @@ aspnet-Microsoft.eShopOnContainers-946ae052-8305-4a99-965b-ec8636ddbae3 ..\..\..\docker-compose.dcproj 3.0 + false + 8.0 @@ -22,25 +24,25 @@ - + - - - - - + + + + + diff --git a/src/Web/WebSPA/Dockerfile b/src/Web/WebSPA/Dockerfile index d7cb7631c..14617aaa7 100644 --- a/src/Web/WebSPA/Dockerfile +++ b/src/Web/WebSPA/Dockerfile @@ -1,5 +1,5 @@ ARG NODE_IMAGE=node:8.11 -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 @@ -9,7 +9,7 @@ COPY src/Web/WebSPA . RUN npm install RUN npm run build:prod -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Web/WebSPA/Startup.cs b/src/Web/WebSPA/Startup.cs index 0c1f37b3f..50e4dbef2 100644 --- a/src/Web/WebSPA/Startup.cs +++ b/src/Web/WebSPA/Startup.cs @@ -1,22 +1,19 @@ using eShopOnContainers.WebSPA; -using Microsoft.ApplicationInsights.Extensibility; -using Microsoft.ApplicationInsights.ServiceFabric; +using HealthChecks.UI.Client; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; -using Newtonsoft.Json.Serialization; using StackExchange.Redis; using System; using System.IO; using WebSPA.Infrastructure; -using HealthChecks.UI.Client; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.Extensions.Diagnostics.HealthChecks; namespace eShopConContainers.WebSPA { @@ -30,6 +27,7 @@ namespace eShopConContainers.WebSPA public IConfiguration Configuration { get; } private IHostingEnvironment _hostingEnv; + public Startup(IHostingEnvironment env) { _hostingEnv = env; @@ -48,7 +46,7 @@ namespace eShopConContainers.WebSPA .AddCheck("self", () => HealthCheckResult.Healthy()) .AddUrlGroup(new Uri(Configuration["PurchaseUrlHC"]), name: "purchaseapigw-check", tags: new string[] { "purchaseapigw" }) .AddUrlGroup(new Uri(Configuration["MarketingUrlHC"]), name: "marketingapigw-check", tags: new string[] { "marketingapigw" }) - .AddUrlGroup(new Uri(Configuration["IdentityUrlHC"]), name: "identityapi-check", tags: new string[] { "identityapi" }); + .AddUrlGroup(new Uri(Configuration["IdentityUrlHC"]), name: "identityapi-check", tags: new string[] { "identityapi" }); services.Configure(Configuration); @@ -67,7 +65,7 @@ namespace eShopConContainers.WebSPA .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddJsonOptions(options => { - options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); + options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; }); } @@ -86,18 +84,6 @@ namespace eShopConContainers.WebSPA // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - // Configure XSRF middleware, This pattern is for SPA style applications where XSRF token is added on Index page // load and passed back token on every subsequent async request // app.Use(async (context, next) => @@ -128,34 +114,34 @@ namespace eShopConContainers.WebSPA // Rewrite request to use app root if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value) && !context.Request.Path.Value.StartsWith("/api")) { - context.Request.Path = "/index.html"; + context.Request.Path = "/index.html"; context.Response.StatusCode = 200; // Make sure we update the status code, otherwise it returns 404 await next(); } }); - + app.UseDefaultFiles(); app.UseStaticFiles(); - - app.UseMvcWithDefaultRoute(); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + }); } private void RegisterAppInsights(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration); - var orchestratorType = Configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } + services.AddApplicationInsightsKubernetesEnricher(); } } } diff --git a/src/Web/WebSPA/WebSPA.csproj b/src/Web/WebSPA/WebSPA.csproj index 365b3205a..c2682716f 100644 --- a/src/Web/WebSPA/WebSPA.csproj +++ b/src/Web/WebSPA/WebSPA.csproj @@ -9,6 +9,7 @@ wwwroot/dist/** $(DefaultItemExcludes);$(GeneratedItemPatterns) 2.9 + 8.0 @@ -90,10 +91,9 @@ - - + diff --git a/src/Web/WebSPA/package.json b/src/Web/WebSPA/package.json index 41d25c640..ae4209a14 100644 --- a/src/Web/WebSPA/package.json +++ b/src/Web/WebSPA/package.json @@ -37,7 +37,7 @@ "@angular/platform-browser-dynamic": "^7.2.10", "@angular/platform-server": "^7.2.10", "@angular/router": "^7.2.10", - "@aspnet/signalr": "1.0.3", + "@aspnet/signalr": "3.0.0-preview6.19307.2", "@ng-bootstrap/ng-bootstrap": "3.3.0", "bootstrap": "4.3.1", "core-js": "^2.5.0", diff --git a/src/Web/WebStatus/Startup.cs b/src/Web/WebStatus/Startup.cs index 48875eab5..17f42de5c 100644 --- a/src/Web/WebStatus/Startup.cs +++ b/src/Web/WebStatus/Startup.cs @@ -56,11 +56,6 @@ namespace WebStatus app.UsePathBase(pathBase); } - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - app.UseHealthChecksUI(config => { config.ResourcesPath = string.IsNullOrEmpty(pathBase) ? "/ui/resources" : $"{pathBase}/ui/resources"; @@ -74,19 +69,17 @@ namespace WebStatus app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); }); } private void RegisterAppInsights(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration); - var orchestratorType = Configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } + services.AddApplicationInsightsKubernetesEnricher(); } } } diff --git a/src/Web/WebStatus/WebStatus.csproj b/src/Web/WebStatus/WebStatus.csproj index 9364cd5e2..43462a55e 100644 --- a/src/Web/WebStatus/WebStatus.csproj +++ b/src/Web/WebStatus/WebStatus.csproj @@ -3,6 +3,7 @@ $(NetCoreTargetVersion) $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\docker-compose.dcproj + 8.0 @@ -14,7 +15,7 @@ - + diff --git a/src/Web/WebhookClient/Controllers/AccountController.cs b/src/Web/WebhookClient/Controllers/AccountController.cs index 26fc4074e..461e3261d 100644 --- a/src/Web/WebhookClient/Controllers/AccountController.cs +++ b/src/Web/WebhookClient/Controllers/AccountController.cs @@ -3,9 +3,6 @@ using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Linq; using System.Security.Claims; using System.Threading.Tasks; diff --git a/src/Web/WebhookClient/Dockerfile b/src/Web/WebhookClient/Dockerfile index 9143fd8e1..b756936f7 100644 --- a/src/Web/WebhookClient/Dockerfile +++ b/src/Web/WebhookClient/Dockerfile @@ -1,9 +1,9 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 EXPOSE 443 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/Web/WebhookClient/WebhookClient.csproj b/src/Web/WebhookClient/WebhookClient.csproj index 95ec6e8fb..3e4eb8ed3 100644 --- a/src/Web/WebhookClient/WebhookClient.csproj +++ b/src/Web/WebhookClient/WebhookClient.csproj @@ -1,17 +1,20 @@ - + $(NetCoreTargetVersion) InProcess Linux 36215d41-f31a-4aa6-9929-bd67d650e7b5 + 8.0 - - - + + + + + diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 809b3e08c..7914c41c7 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -32,10 +32,19 @@ 4.9.2 4.2.1 1.50.7 - 4.3.0 + 3.0.0-alpha1-10670 + 1.0.2105168 + 3.0.0-preview6-19319-03 + 3.0.0-preview6-19253-01 + 4.3.0 4.5.1 4.5.0 5.1.0 + 2.6.375 + 2.2.0-preview2-35157 + 5.2.7 + 15.9.20 + 1.0.172 3.0.0-alpha1-34847 5.1.0 2.2.1 From fe93901f084c9a5589a0a32b5607088fc1846ae5 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Tue, 23 Jul 2019 15:23:26 +0200 Subject: [PATCH 015/113] identity service --- src/Services/Catalog/Catalog.API/Startup.cs | 11 ----- .../Identity/Identity.API/Identity.API.csproj | 10 ++-- src/Services/Identity/Identity.API/Startup.cs | 31 +++++------- .../Identity.API/Views/Account/Login.cshtml | 5 +- src/Web/WebMVC/Startup.cs | 48 +++++++++---------- src/_build/dependencies.props | 28 ++++++----- 6 files changed, 60 insertions(+), 73 deletions(-) diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index c34db7614..85fd3ba42 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -75,17 +75,6 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API app.UsePathBase(pathBase); } - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - app.UseCors("CorsPolicy"); app.UseRouting(); diff --git a/src/Services/Identity/Identity.API/Identity.API.csproj b/src/Services/Identity/Identity.API/Identity.API.csproj index e68e36a7e..6301e21e3 100644 --- a/src/Services/Identity/Identity.API/Identity.API.csproj +++ b/src/Services/Identity/Identity.API/Identity.API.csproj @@ -16,17 +16,17 @@ - - + + - + - + @@ -34,6 +34,8 @@ + + diff --git a/src/Services/Identity/Identity.API/Startup.cs b/src/Services/Identity/Identity.API/Startup.cs index 009773b62..644124da4 100644 --- a/src/Services/Identity/Identity.API/Startup.cs +++ b/src/Services/Identity/Identity.API/Startup.cs @@ -55,7 +55,7 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API services.Configure(Configuration); services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); if (Configuration.GetValue("IsClusterEnv") == bool.TrueString) { @@ -140,20 +140,8 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API app.UsePathBase(pathBase); } - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - app.UseStaticFiles(); - // Make work identity server redirections in Edge and lastest versions of browers. WARN: Not valid in a production environment. app.Use(async (context, next) => { @@ -164,13 +152,20 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API app.UseForwardedHeaders(); // Adds IdentityServer app.UseIdentityServer(); - app.UseHttpsRedirection(); - app.UseMvc(routes => + app.UseRouting(); + app.UseEndpoints(endpoints => { - routes.MapRoute( - name: "default", - template: "{controller=Home}/{action=Index}/{id?}"); + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + endpoints.MapDefaultControllerRoute(); }); } diff --git a/src/Services/Identity/Identity.API/Views/Account/Login.cshtml b/src/Services/Identity/Identity.API/Views/Account/Login.cshtml index 315810419..b74d7d8b9 100644 --- a/src/Services/Identity/Identity.API/Views/Account/Login.cshtml +++ b/src/Services/Identity/Identity.API/Views/Account/Login.cshtml @@ -1,7 +1,4 @@ -@using System.Collections.Generic -@using Microsoft.AspNetCore.Http -@using Microsoft.AspNetCore.Http.Authentication -@model Microsoft.eShopOnContainers.Services.Identity.API.Models.AccountViewModels.LoginViewModel +@model Microsoft.eShopOnContainers.Services.Identity.API.Models.AccountViewModels.LoginViewModel @{ diff --git a/src/Web/WebMVC/Startup.cs b/src/Web/WebMVC/Startup.cs index e9c0a519f..1d2908bf1 100644 --- a/src/Web/WebMVC/Startup.cs +++ b/src/Web/WebMVC/Startup.cs @@ -234,29 +234,29 @@ namespace Microsoft.eShopOnContainers.WebMVC .AddCookie(setup => setup.ExpireTimeSpan = TimeSpan.FromMinutes(sessionCookieLifetime)) .AddJwtBearer(options => { - options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; + //options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; + //options.Authority = identityUrl.ToString(); + //options.SignedOutRedirectUri = callBackUrl.ToString(); + //options.ClientId = useLoadTest ? "mvctest" : "mvc"; + //options.ClientSecret = "secret"; + //options.ResponseType = useLoadTest ? "code id_token token" : "code id_token"; + //options.SaveTokens = true; + //options.GetClaimsFromUserInfoEndpoint = true; + //options.RequireHttpsMetadata = false; + //options.Scope.Add("openid"); + //options.Scope.Add("profile"); + //options.Scope.Add("orders"); + //options.Scope.Add("basket"); + //options.Scope.Add("marketing"); + //options.Scope.Add("locations"); + //options.Scope.Add("webshoppingagg"); + //options.Scope.Add("orders.signalrhub"); + + //options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.Authority = identityUrl.ToString(); - options.SignedOutRedirectUri = callBackUrl.ToString(); - options.ClientId = useLoadTest ? "mvctest" : "mvc"; - options.ClientSecret = "secret"; - options.ResponseType = useLoadTest ? "code id_token token" : "code id_token"; - options.SaveTokens = true; - options.GetClaimsFromUserInfoEndpoint = true; - options.RequireHttpsMetadata = false; - options.Scope.Add("openid"); - options.Scope.Add("profile"); - options.Scope.Add("orders"); - options.Scope.Add("basket"); - options.Scope.Add("marketing"); - options.Scope.Add("locations"); - options.Scope.Add("webshoppingagg"); - options.Scope.Add("orders.signalrhub"); - - /*options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; - options.Authority = identityUrl.ToString(); - options.SignedOutRedirectUri = callBackUrl.ToString(); - options.ClientId = useLoadTest ? "mvctest" : "mvc"; - options.ClientSecret = "secret"; + options.ForwardSignOut = callBackUrl.ToString(); + //options.ClientId = useLoadTest ? "mvctest" : "mvc"; + //options.ClientSecret = "secret"; if (useLoadTest) { @@ -268,7 +268,7 @@ namespace Microsoft.eShopOnContainers.WebMVC } options.SaveToken = true; - options.GetClaimsFromUserInfoEndpoint = true; + //options.GetClaimsFromUserInfoEndpoint = true; options.RequireHttpsMetadata = false; options.Configuration.ScopesSupported.Add("openid"); options.Configuration.ScopesSupported.Add("profile"); @@ -277,7 +277,7 @@ namespace Microsoft.eShopOnContainers.WebMVC options.Configuration.ScopesSupported.Add("marketing"); options.Configuration.ScopesSupported.Add("locations"); options.Configuration.ScopesSupported.Add("webshoppingagg"); - options.Configuration.ScopesSupported.Add("orders.signalrhub");*/ + options.Configuration.ScopesSupported.Add("orders.signalrhub"); }); return services; diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 7914c41c7..b914b4ec3 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -15,7 +15,7 @@ 2.9.406 - + 0.1.22-pre1 3.9.0-rc1 1.22.0 @@ -32,24 +32,24 @@ 4.9.2 4.2.1 1.50.7 - 3.0.0-alpha1-10670 - 1.0.2105168 - 3.0.0-preview6-19319-03 - 3.0.0-preview6-19253-01 - 4.3.0 + 4.3.0 4.5.1 4.5.0 5.1.0 2.6.375 - 2.2.0-preview2-35157 - 5.2.7 + 5.2.7 15.9.20 1.0.172 - 3.0.0-alpha1-34847 + 1.0.2105168 + 3.0.0-preview6-19319-03 5.1.0 2.2.1 2.6.1 1.0.2 + 3.0.0-alpha1-10670 + 3.0.0-preview6-19253-01 + 2.2.0-preview2-35157 + 3.0.0-alpha1-34847 3.0.0-preview6.19307.2 3.0.0-preview6.19307.2 2.2.0 @@ -57,11 +57,13 @@ 2.2.0 3.0.0-preview6.19307.2 3.0.0-preview6.19307.2 + 3.0.0-preview6.19307.2 + 3.0.0-preview6-19253-01 + 3.0.0-preview4-19123-01 + 7.5.0 3.0.0 4.5.0 - 3.0.0-preview4-19123-01 4.7.0-preview6.19303.8 - 7.5.0 3.0.0-preview6.19304.10 3.0.0-preview6.19304.10 3.0.0-preview6.19304.10 @@ -82,6 +84,8 @@ 12.0.2 12.0.1 6.0.1 + 3.0.0-preview3.4 + 3.0.0-preview3.4 5.0.1 3.0.0-dev-00053 2.1.3 @@ -94,7 +98,7 @@ 4.3.0 2.4.0 2.4.0 - + https://github.com/dotnet-architecture/eShopOnContainers/blob/master/LICENSE From 49cc39d731914fafbb0cd4a9e2b151c18e36a097 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Wed, 24 Jul 2019 09:06:46 +0200 Subject: [PATCH 016/113] update startups --- src/ApiGateways/ApiGw-Base/Startup.cs | 19 ++-- .../Mobile.Bff.Shopping/aggregator/Startup.cs | 26 +++--- .../Web.Bff.Shopping/aggregator/Startup.cs | 26 +++--- .../AuthorizeCheckOperationFilter.cs | 25 +++--- src/Services/Webhooks/Webhooks.API/Startup.cs | 86 ++++++++----------- .../Webhooks/Webhooks.API/Webhooks.API.csproj | 9 +- src/Web/WebMVC/Startup.cs | 67 ++++----------- src/Web/WebhookClient/Startup.cs | 10 ++- src/Web/WebhookClient/WebhookClient.csproj | 3 +- 9 files changed, 122 insertions(+), 149 deletions(-) diff --git a/src/ApiGateways/ApiGw-Base/Startup.cs b/src/ApiGateways/ApiGw-Base/Startup.cs index be845edca..f4b7eaff7 100644 --- a/src/ApiGateways/ApiGw-Base/Startup.cs +++ b/src/ApiGateways/ApiGw-Base/Startup.cs @@ -89,15 +89,18 @@ namespace OcelotApiGw app.UseDeveloperExceptionPage(); } - app.UseHealthChecks("/hc", new HealthCheckOptions() + app.UseRouting(); + app.UseEndpoints(endpoints => { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); }); app.UseCors("CorsPolicy"); diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index a2997be05..efa9285c2 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -62,17 +62,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator app.UsePathBase(pathBase); } - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - app.UseCors("CorsPolicy"); if (env.IsDevelopment()) @@ -87,7 +76,20 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator app.UseAuthentication(); app.UseHttpsRedirection(); - app.UseMvc(); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + endpoints.MapDefaultControllerRoute(); + }); app.UseSwagger().UseSwaggerUI(c => { diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index 747269f50..b6d43b300 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -61,17 +61,6 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator app.UsePathBase(pathBase); } - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - app.UseCors("CorsPolicy"); if (env.IsDevelopment()) @@ -86,7 +75,20 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator app.UseAuthentication(); app.UseHttpsRedirection(); - app.UseMvc(); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + endpoints.MapDefaultControllerRoute(); + }); app.UseSwagger() .UseSwaggerUI(c => diff --git a/src/Services/Webhooks/Webhooks.API/Infrastructure/AuthorizeCheckOperationFilter.cs b/src/Services/Webhooks/Webhooks.API/Infrastructure/AuthorizeCheckOperationFilter.cs index 920f2ac8e..487a59981 100644 --- a/src/Services/Webhooks/Webhooks.API/Infrastructure/AuthorizeCheckOperationFilter.cs +++ b/src/Services/Webhooks/Webhooks.API/Infrastructure/AuthorizeCheckOperationFilter.cs @@ -1,16 +1,14 @@ using Microsoft.AspNetCore.Authorization; -using Swashbuckle.AspNetCore.Swagger; +using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; -using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; namespace Webhooks.API.Infrastructure { public class AuthorizeCheckOperationFilter : IOperationFilter { - public void Apply(Operation operation, OperationFilterContext context) + public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || @@ -18,16 +16,21 @@ namespace Webhooks.API.Infrastructure if (!hasAuthorize) return; - operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); + operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" }); - operation.Security = new List>> + var oAuthScheme = new OpenApiSecurityScheme { - new Dictionary> - { - { "oauth2", new [] { "webhooksapi" } } - } + Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }; + + operation.Security = new List + { + new OpenApiSecurityRequirement + { + [ oAuthScheme ] = new [] { "webhooksapi" } + } + }; } } } diff --git a/src/Services/Webhooks/Webhooks.API/Startup.cs b/src/Services/Webhooks/Webhooks.API/Startup.cs index f1a89d329..dfeb36a79 100644 --- a/src/Services/Webhooks/Webhooks.API/Startup.cs +++ b/src/Services/Webhooks/Webhooks.API/Startup.cs @@ -1,21 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Data.Common; -using System.IdentityModel.Tokens.Jwt; -using System.Linq; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Autofac; +using Autofac; using Autofac.Extensions.DependencyInjection; using Devspaces.Support; using HealthChecks.UI.Client; -using Microsoft.ApplicationInsights.Extensibility; -using Microsoft.ApplicationInsights.ServiceFabric; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.ServiceBus; @@ -31,7 +20,12 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using RabbitMQ.Client; -using Swashbuckle.AspNetCore.Swagger; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.IdentityModel.Tokens.Jwt; +using System.Reflection; +using System.Threading; using Webhooks.API.Infrastructure; using Webhooks.API.IntegrationEvents; using Webhooks.API.Services; @@ -84,22 +78,25 @@ namespace Webhooks.API app.UsePathBase(pathBase); } - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - app.UseCors("CorsPolicy"); ConfigureAuth(app); - app.UseMvcWithDefaultRoute(); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + + endpoints.MapDefaultControllerRoute(); + }); app.UseSwagger() .UseSwaggerUI(c => @@ -138,19 +135,7 @@ namespace Webhooks.API public static IServiceCollection AddAppInsight(this IServiceCollection services, IConfiguration configuration) { services.AddApplicationInsightsTelemetry(configuration); - var orchestratorType = configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } - if (orchestratorType?.ToUpper() == "SF") - { - // Enable SF telemetry initializer - services.AddSingleton((serviceProvider) => - new FabricTelemetryInitializer()); - } + services.AddApplicationInsightsKubernetesEnricher(); return services; } @@ -161,7 +146,7 @@ namespace Webhooks.API { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }) - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); services.AddCors(options => @@ -203,23 +188,26 @@ namespace Webhooks.API services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info + options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "eShopOnContainers - Webhooks HTTP API", Version = "v1", - Description = "The Webhooks Microservice HTTP API. This is a simple webhooks CRUD registration entrypoint", - TermsOfService = "Terms Of Service" + Description = "The Webhooks Microservice HTTP API. This is a simple webhooks CRUD registration entrypoint" }); - options.AddSecurityDefinition("oauth2", new OAuth2Scheme + options.AddSecurityDefinition("oauth2", new Microsoft.OpenApi.Models.OpenApiSecurityScheme { - Type = "oauth2", - Flow = "implicit", - AuthorizationUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize", - TokenUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/token", - Scopes = new Dictionary() + Flows = new Microsoft.OpenApi.Models.OpenApiOAuthFlows() { - { "webhooks", "Webhooks API" } + Implicit = new Microsoft.OpenApi.Models.OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "marketing", "Marketing API" } + } + } } }); diff --git a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj index 1dcf916f5..9ff40e01b 100644 --- a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj +++ b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj @@ -4,21 +4,24 @@ $(NetCoreTargetVersion) InProcess Linux + $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; + false + 8.0 - - + + - + diff --git a/src/Web/WebMVC/Startup.cs b/src/Web/WebMVC/Startup.cs index 1d2908bf1..db53a23b9 100644 --- a/src/Web/WebMVC/Startup.cs +++ b/src/Web/WebMVC/Startup.cs @@ -108,13 +108,7 @@ namespace Microsoft.eShopOnContainers.WebMVC public static IServiceCollection AddAppInsight(this IServiceCollection services, IConfiguration configuration) { services.AddApplicationInsightsTelemetry(configuration); - var orchestratorType = configuration.GetValue("OrchestratorType"); - - if (orchestratorType?.ToUpper() == "K8S") - { - // Enable K8s telemetry initializer - services.AddApplicationInsightsKubernetesEnricher(); - } + services.AddApplicationInsightsKubernetesEnricher(); return services; } @@ -232,52 +226,25 @@ namespace Microsoft.eShopOnContainers.WebMVC options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddCookie(setup => setup.ExpireTimeSpan = TimeSpan.FromMinutes(sessionCookieLifetime)) - .AddJwtBearer(options => + .AddOpenIdConnect(options => { - //options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; - //options.Authority = identityUrl.ToString(); - //options.SignedOutRedirectUri = callBackUrl.ToString(); - //options.ClientId = useLoadTest ? "mvctest" : "mvc"; - //options.ClientSecret = "secret"; - //options.ResponseType = useLoadTest ? "code id_token token" : "code id_token"; - //options.SaveTokens = true; - //options.GetClaimsFromUserInfoEndpoint = true; - //options.RequireHttpsMetadata = false; - //options.Scope.Add("openid"); - //options.Scope.Add("profile"); - //options.Scope.Add("orders"); - //options.Scope.Add("basket"); - //options.Scope.Add("marketing"); - //options.Scope.Add("locations"); - //options.Scope.Add("webshoppingagg"); - //options.Scope.Add("orders.signalrhub"); - - //options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; + options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.Authority = identityUrl.ToString(); - options.ForwardSignOut = callBackUrl.ToString(); - //options.ClientId = useLoadTest ? "mvctest" : "mvc"; - //options.ClientSecret = "secret"; - - if (useLoadTest) - { - options.Configuration.ResponseTypesSupported.Add("code id_token token"); - } - else - { - options.Configuration.ResponseTypesSupported.Add("code id_token"); - } - - options.SaveToken = true; - //options.GetClaimsFromUserInfoEndpoint = true; + options.SignedOutRedirectUri = callBackUrl.ToString(); + options.ClientId = useLoadTest ? "mvctest" : "mvc"; + options.ClientSecret = "secret"; + options.ResponseType = useLoadTest ? "code id_token token" : "code id_token"; + options.SaveTokens = true; + options.GetClaimsFromUserInfoEndpoint = true; options.RequireHttpsMetadata = false; - options.Configuration.ScopesSupported.Add("openid"); - options.Configuration.ScopesSupported.Add("profile"); - options.Configuration.ScopesSupported.Add("orders"); - options.Configuration.ScopesSupported.Add("basket"); - options.Configuration.ScopesSupported.Add("marketing"); - options.Configuration.ScopesSupported.Add("locations"); - options.Configuration.ScopesSupported.Add("webshoppingagg"); - options.Configuration.ScopesSupported.Add("orders.signalrhub"); + options.Scope.Add("openid"); + options.Scope.Add("profile"); + options.Scope.Add("orders"); + options.Scope.Add("basket"); + options.Scope.Add("marketing"); + options.Scope.Add("locations"); + options.Scope.Add("webshoppingagg"); + options.Scope.Add("orders.signalrhub"); }); return services; diff --git a/src/Web/WebhookClient/Startup.cs b/src/Web/WebhookClient/Startup.cs index 13ff70362..3b56d20fb 100644 --- a/src/Web/WebhookClient/Startup.cs +++ b/src/Web/WebhookClient/Startup.cs @@ -36,7 +36,7 @@ namespace WebhookClient .AddCustomAuthentication(Configuration) .AddTransient() .AddSingleton() - .AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + .AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -69,7 +69,7 @@ namespace WebhookClient var header = context.Request.Headers[HeaderNames.WebHookCheckHeader]; var value = header.FirstOrDefault(); var tokenToValidate = Configuration["Token"]; - if (!validateToken || value == tokenToValidate) + if (!validateToken || value == tokenToValidate) { if (!string.IsNullOrWhiteSpace(tokenToValidate)) { @@ -91,7 +91,11 @@ namespace WebhookClient }); app.UseStaticFiles(); app.UseSession(); - app.UseMvcWithDefaultRoute(); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); } } diff --git a/src/Web/WebhookClient/WebhookClient.csproj b/src/Web/WebhookClient/WebhookClient.csproj index 3e4eb8ed3..f9d46a63a 100644 --- a/src/Web/WebhookClient/WebhookClient.csproj +++ b/src/Web/WebhookClient/WebhookClient.csproj @@ -5,12 +5,13 @@ InProcess Linux 36215d41-f31a-4aa6-9929-bd67d650e7b5 + $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; + false 8.0 - From 754d91f3ef89a12589cfd1aae55b89fdcb656cc6 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Wed, 24 Jul 2019 09:51:34 +0200 Subject: [PATCH 017/113] update dockerfile image --- src/Services/Identity/Identity.API/Dockerfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Services/Identity/Identity.API/Dockerfile b/src/Services/Identity/Identity.API/Dockerfile index 8196b077a..0096fe7f4 100644 --- a/src/Services/Identity/Identity.API/Dockerfile +++ b/src/Services/Identity/Identity.API/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ From 072c82a92d0a9d5cbf9152a946c7c4663f832403 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Wed, 24 Jul 2019 09:58:02 +0200 Subject: [PATCH 018/113] add target references ignore --- src/Services/Basket/Basket.API/Basket.API.csproj | 1 + src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index 22c562da0..a28c52524 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -4,6 +4,7 @@ $(NetCoreTargetVersion) $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj + false 8.0 diff --git a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj index 4c062fccd..a678bc4ce 100644 --- a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj +++ b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj @@ -2,7 +2,7 @@ $(NetCoreTargetVersion) - + false false From 19dfd6862939cc9176e1c8dfac61fea62f666afb Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 24 Jul 2019 11:13:25 +0200 Subject: [PATCH 019/113] Migrate Basket.UnitTests --- .../Basket/Basket.UnitTests/Basket.UnitTests.csproj | 8 ++++++-- src/_build/dependencies.props | 4 ++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj index a678bc4ce..54d753de9 100644 --- a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj +++ b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj @@ -7,8 +7,12 @@ - - + + + + + + diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index b914b4ec3..df4140c77 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -46,6 +46,7 @@ 2.2.1 2.6.1 1.0.2 + 3.0.0-preview4-19123-01 3.0.0-alpha1-10670 3.0.0-preview6-19253-01 2.2.0-preview2-35157 @@ -60,14 +61,17 @@ 3.0.0-preview6.19307.2 3.0.0-preview6-19253-01 3.0.0-preview4-19123-01 + 3.0.0-preview4-19123-01 7.5.0 3.0.0 4.5.0 4.7.0-preview6.19303.8 + 3.0.0-preview6.19303.8 3.0.0-preview6.19304.10 3.0.0-preview6.19304.10 3.0.0-preview6.19304.10 3.0.0-preview6.19304.10 + 3.0.0-preview7.19365.7 2.2.0 2.2.0 2.2.0 From eb1c2705cb7645bf1cea17295391475b4d5e014b Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 24 Jul 2019 11:22:46 +0200 Subject: [PATCH 020/113] Migrate Catalog.UnitTests --- .../Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj index d0584bd60..027b7d5d7 100644 --- a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj +++ b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj @@ -7,8 +7,9 @@ - - + + + From 79405b89b073088341a2ac566762181c8b3feff4 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Wed, 24 Jul 2019 12:15:38 +0200 Subject: [PATCH 021/113] modify retries count --- global.json | 1 + src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj | 1 + .../Mobile.Shopping.HttpAggregator.csproj | 2 +- .../Web.Shopping.HttpAggregator.csproj | 2 +- .../Basket/Basket.API/Basket.API.csproj | 2 +- .../Catalog/Catalog.API/Catalog.API.csproj | 3 ++- src/Services/Catalog/Catalog.API/Startup.cs | 7 +++--- .../Identity/Identity.API/Identity.API.csproj | 2 ++ src/Services/Identity/Identity.API/Startup.cs | 4 ---- .../Locations.API/Locations.API.csproj | 1 + .../Filters/AuthorizeCheckOperationFilter.cs | 23 +++++++++++-------- .../Marketing.API/Marketing.API.csproj | 3 ++- .../Marketing/Marketing.API/Startup.cs | 5 ++-- .../Ordering/Ordering.API/Ordering.API.csproj | 3 ++- src/Services/Ordering/Ordering.API/Startup.cs | 16 ++----------- .../Ordering.BackgroundTasks.csproj | 2 ++ .../Ordering.SignalrHub.csproj | 2 +- .../Payment/Payment.API/Payment.API.csproj | 1 + src/Services/Webhooks/Webhooks.API/Startup.cs | 5 ++-- .../Webhooks/Webhooks.API/Webhooks.API.csproj | 2 +- src/Web/WebMVC/WebMVC.csproj | 2 +- src/Web/WebSPA/WebSPA.csproj | 2 +- src/Web/WebStatus/Startup.cs | 3 +-- src/Web/WebStatus/WebStatus.csproj | 2 +- src/Web/WebhookClient/WebhookClient.csproj | 2 +- 25 files changed, 50 insertions(+), 48 deletions(-) create mode 100644 global.json diff --git a/global.json b/global.json new file mode 100644 index 000000000..9e26dfeeb --- /dev/null +++ b/global.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj index 8f311ab77..c7855f18e 100644 --- a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj +++ b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj @@ -2,6 +2,7 @@ $(NetCoreTargetVersion) + $(LangVersion) diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj index 87e6c31b3..d8d54643f 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj @@ -6,7 +6,7 @@ Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator ..\..\..\docker-compose.dcproj false - 8.0 + $(LangVersion) diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj index b7eb1a019..10d890062 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj @@ -6,7 +6,7 @@ Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator ..\..\..\docker-compose.dcproj false - 8.0 + $(LangVersion) diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index a28c52524..9c09a08bc 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -5,7 +5,7 @@ $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj false - 8.0 + $(LangVersion) diff --git a/src/Services/Catalog/Catalog.API/Catalog.API.csproj b/src/Services/Catalog/Catalog.API/Catalog.API.csproj index 2640185d1..f20ba1c7d 100644 --- a/src/Services/Catalog/Catalog.API/Catalog.API.csproj +++ b/src/Services/Catalog/Catalog.API/Catalog.API.csproj @@ -8,7 +8,8 @@ Catalog.API aspnet-Catalog.API-20161122013618 ..\..\..\..\docker-compose.dcproj - 8.0 + false + $(LangVersion) diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 85fd3ba42..24d3395b0 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -202,14 +202,15 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API public static IServiceCollection AddCustomDbContext(this IServiceCollection services, IConfiguration configuration) { - services.AddDbContext(options => + services.AddEntityFrameworkSqlServer() + .AddDbContext(options => { options.UseSqlServer(configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency - sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); + sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); // Changing default behavior when client evaluation occurs to throw. @@ -225,7 +226,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency - sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); + sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); }); diff --git a/src/Services/Identity/Identity.API/Identity.API.csproj b/src/Services/Identity/Identity.API/Identity.API.csproj index 6301e21e3..1fe8e7ac4 100644 --- a/src/Services/Identity/Identity.API/Identity.API.csproj +++ b/src/Services/Identity/Identity.API/Identity.API.csproj @@ -4,6 +4,8 @@ $(NetCoreTargetVersion) aspnet-eShopOnContainers.Identity-90487118-103c-4ff0-b9da-e5e26f7ab0c5 ..\..\..\..\docker-compose.dcproj + false + $(LangVersion) diff --git a/src/Services/Identity/Identity.API/Startup.cs b/src/Services/Identity/Identity.API/Startup.cs index 644124da4..fd8e94c59 100644 --- a/src/Services/Identity/Identity.API/Startup.cs +++ b/src/Services/Identity/Identity.API/Startup.cs @@ -7,7 +7,6 @@ using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Identity.API.Certificates; using Microsoft.eShopOnContainers.Services.Identity.API.Data; @@ -54,9 +53,6 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API services.Configure(Configuration); - services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); - if (Configuration.GetValue("IsClusterEnv") == bool.TrueString) { services.AddDataProtection(opts => diff --git a/src/Services/Location/Locations.API/Locations.API.csproj b/src/Services/Location/Locations.API/Locations.API.csproj index 653b7b7b5..10b2a6f9b 100644 --- a/src/Services/Location/Locations.API/Locations.API.csproj +++ b/src/Services/Location/Locations.API/Locations.API.csproj @@ -4,6 +4,7 @@ $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj aspnet-Locations.API-20161122013619 + false $(LangVersion) diff --git a/src/Services/Marketing/Marketing.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs b/src/Services/Marketing/Marketing.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs index 3f19140bf..d013597d9 100644 --- a/src/Services/Marketing/Marketing.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs +++ b/src/Services/Marketing/Marketing.API/Infrastructure/Filters/AuthorizeCheckOperationFilter.cs @@ -1,5 +1,5 @@ using Microsoft.AspNetCore.Authorization; -using Swashbuckle.AspNetCore.Swagger; +using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using System.Linq; @@ -8,7 +8,7 @@ namespace Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Filt { public class AuthorizeCheckOperationFilter : IOperationFilter { - public void Apply(Operation operation, OperationFilterContext context) + public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || @@ -16,16 +16,21 @@ namespace Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Filt if (!hasAuthorize) return; - operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); + operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" }); - operation.Security = new List>> + var oAuthScheme = new OpenApiSecurityScheme { - new Dictionary> - { - { "oauth2", new [] { "marketingapi" } } - } + Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }; + + operation.Security = new List + { + new OpenApiSecurityRequirement + { + [ oAuthScheme ] = new [] { "marketingapi" } + } + }; } } } \ No newline at end of file diff --git a/src/Services/Marketing/Marketing.API/Marketing.API.csproj b/src/Services/Marketing/Marketing.API/Marketing.API.csproj index 8eb50e2a3..e07d4e444 100644 --- a/src/Services/Marketing/Marketing.API/Marketing.API.csproj +++ b/src/Services/Marketing/Marketing.API/Marketing.API.csproj @@ -5,11 +5,12 @@ ..\..\..\..\docker-compose.dcproj Microsoft.eShopOnContainers.Services.Marketing.API $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; + false aspnet-Marketing.API-20161122013619 /subscriptions/6c22bb55-0221-4ce4-9bf1-3c4a10a7294c/resourcegroups/eshop-log/providers/microsoft.insights/components/eshopappinsights /subscriptions/6c22bb55-0221-4ce4-9bf1-3c4a10a7294c/resourcegroups/eshop-log/providers/microsoft.insights/components/eshopappinsights - 8.0 + $(LangVersion) diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index 289a9c351..533827ae2 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -62,14 +62,15 @@ ConfigureAuthService(services); - services.AddDbContext(options => + services.AddEntityFrameworkSqlServer() + .AddDbContext(options => { options.UseSqlServer(Configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency - sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); + sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); // Changing default behavior when client evaluation occurs to throw. diff --git a/src/Services/Ordering/Ordering.API/Ordering.API.csproj b/src/Services/Ordering/Ordering.API/Ordering.API.csproj index ea2ac2d77..bb038d2e5 100644 --- a/src/Services/Ordering/Ordering.API/Ordering.API.csproj +++ b/src/Services/Ordering/Ordering.API/Ordering.API.csproj @@ -5,7 +5,8 @@ aspnet-Ordering.API-20161122013547 $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj - 8.0 + false + $(LangVersion) diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index de9a88af1..ddd53489a 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -13,7 +13,6 @@ using Infrastructure.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; - using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.ServiceBus; using Microsoft.EntityFrameworkCore; @@ -82,17 +81,6 @@ app.UseCors("CorsPolicy"); - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - ConfigureAuth(app); app.UseRouting(); @@ -221,7 +209,7 @@ sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); - sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); + sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); }, ServiceLifetime.Scoped //Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request) @@ -234,7 +222,7 @@ { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency - sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); + sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); }); diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj index 5681288a8..ab193ddb9 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj @@ -4,6 +4,8 @@ $(NetCoreTargetVersion) $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj + false + $(LangVersion) diff --git a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj index e4084087f..93bed4711 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj +++ b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj @@ -4,7 +4,7 @@ $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj false - 8.0 + $(LangVersion) diff --git a/src/Services/Payment/Payment.API/Payment.API.csproj b/src/Services/Payment/Payment.API/Payment.API.csproj index df0f93690..341dfd383 100644 --- a/src/Services/Payment/Payment.API/Payment.API.csproj +++ b/src/Services/Payment/Payment.API/Payment.API.csproj @@ -4,6 +4,7 @@ $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; + false $(LangVersion) diff --git a/src/Services/Webhooks/Webhooks.API/Startup.cs b/src/Services/Webhooks/Webhooks.API/Startup.cs index dfeb36a79..c7f896b0b 100644 --- a/src/Services/Webhooks/Webhooks.API/Startup.cs +++ b/src/Services/Webhooks/Webhooks.API/Startup.cs @@ -164,14 +164,15 @@ namespace Webhooks.API public static IServiceCollection AddCustomDbContext(this IServiceCollection services, IConfiguration configuration) { - services.AddDbContext(options => + services.AddEntityFrameworkSqlServer() + .AddDbContext(options => { options.UseSqlServer(configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency - sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); + sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); // Changing default behavior when client evaluation occurs to throw. diff --git a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj index 9ff40e01b..ed474e741 100644 --- a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj +++ b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj @@ -6,7 +6,7 @@ Linux $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; false - 8.0 + $(LangVersion) diff --git a/src/Web/WebMVC/WebMVC.csproj b/src/Web/WebMVC/WebMVC.csproj index adfc5587e..25fc670fd 100644 --- a/src/Web/WebMVC/WebMVC.csproj +++ b/src/Web/WebMVC/WebMVC.csproj @@ -6,7 +6,7 @@ ..\..\..\docker-compose.dcproj 3.0 false - 8.0 + $(LangVersion) diff --git a/src/Web/WebSPA/WebSPA.csproj b/src/Web/WebSPA/WebSPA.csproj index c2682716f..f219dc5aa 100644 --- a/src/Web/WebSPA/WebSPA.csproj +++ b/src/Web/WebSPA/WebSPA.csproj @@ -9,7 +9,7 @@ wwwroot/dist/** $(DefaultItemExcludes);$(GeneratedItemPatterns) 2.9 - 8.0 + $(LangVersion) diff --git a/src/Web/WebStatus/Startup.cs b/src/Web/WebStatus/Startup.cs index 17f42de5c..eeabd0912 100644 --- a/src/Web/WebStatus/Startup.cs +++ b/src/Web/WebStatus/Startup.cs @@ -28,7 +28,6 @@ namespace WebStatus .AddCheck("self", () => HealthCheckResult.Healthy()); services.AddHealthChecksUI(); - services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); } @@ -65,7 +64,7 @@ namespace WebStatus app.UseStaticFiles(); app.UseHttpsRedirection(); - + app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); diff --git a/src/Web/WebStatus/WebStatus.csproj b/src/Web/WebStatus/WebStatus.csproj index 43462a55e..28f4bce18 100644 --- a/src/Web/WebStatus/WebStatus.csproj +++ b/src/Web/WebStatus/WebStatus.csproj @@ -3,7 +3,7 @@ $(NetCoreTargetVersion) $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\docker-compose.dcproj - 8.0 + $(LangVersion) diff --git a/src/Web/WebhookClient/WebhookClient.csproj b/src/Web/WebhookClient/WebhookClient.csproj index f9d46a63a..22cb5afe2 100644 --- a/src/Web/WebhookClient/WebhookClient.csproj +++ b/src/Web/WebhookClient/WebhookClient.csproj @@ -7,7 +7,7 @@ 36215d41-f31a-4aa6-9929-bd67d650e7b5 $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; false - 8.0 + $(LangVersion) From eb080668ab3288fb66713a8d89e10d4545e4642d Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Wed, 24 Jul 2019 16:20:08 +0200 Subject: [PATCH 022/113] add type securitySchema OAuth2 --- .../Mobile.Bff.Shopping/aggregator/Startup.cs | 10 ++++++---- src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs | 10 ++++++---- src/Services/Basket/Basket.API/Startup.cs | 10 ++++++---- src/Services/Identity/Identity.API/Identity.API.csproj | 5 +++-- src/Services/Marketing/Marketing.API/Startup.cs | 10 ++++++---- src/Services/Ordering/Ordering.API/Startup.cs | 10 ++++++---- src/Services/Webhooks/Webhooks.API/Startup.cs | 10 ++++++---- 7 files changed, 39 insertions(+), 26 deletions(-) diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index efa9285c2..716f0ec5c 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -14,6 +14,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Models; using Polly; using Polly.Extensions.Http; using System; @@ -116,18 +117,19 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo + options.SwaggerDoc("v1", new OpenApiInfo { Title = "Shopping Aggregator for Mobile Clients", Version = "v1", Description = "Shopping Aggregator for Mobile Clients" }); - options.AddSecurityDefinition("oauth2", new OpenApi.Models.OpenApiSecurityScheme + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { - Flows = new OpenApi.Models.OpenApiOAuthFlows() + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() { - Implicit = new OpenApi.Models.OpenApiOAuthFlow() + Implicit = new OpenApiOAuthFlow() { AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index b6d43b300..b8ef7b459 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -14,6 +14,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Models; using Polly; using Polly.Extensions.Http; using System; @@ -142,18 +143,19 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo + options.SwaggerDoc("v1", new OpenApiInfo { Title = "Shopping Aggregator for Web Clients", Version = "v1", Description = "Shopping Aggregator for Web Clients" }); - options.AddSecurityDefinition("oauth2", new OpenApi.Models.OpenApiSecurityScheme + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { - Flows = new OpenApi.Models.OpenApiOAuthFlows() + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() { - Implicit = new OpenApi.Models.OpenApiOAuthFlow() + Implicit = new OpenApiOAuthFlow() { AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index 46599c616..6a23c76d4 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -26,6 +26,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.OpenApi.Models; using RabbitMQ.Client; using StackExchange.Redis; using System; @@ -131,18 +132,19 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo + options.SwaggerDoc("v1", new OpenApiInfo { Title = "Basket HTTP API", Version = "v1", Description = "The Basket Service HTTP API" }); - options.AddSecurityDefinition("oauth2", new OpenApi.Models.OpenApiSecurityScheme + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { - Flows = new OpenApi.Models.OpenApiOAuthFlows() + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() { - Implicit = new OpenApi.Models.OpenApiOAuthFlow() + Implicit = new OpenApiOAuthFlow() { AuthorizationUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), TokenUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/token"), diff --git a/src/Services/Identity/Identity.API/Identity.API.csproj b/src/Services/Identity/Identity.API/Identity.API.csproj index 1fe8e7ac4..b26032233 100644 --- a/src/Services/Identity/Identity.API/Identity.API.csproj +++ b/src/Services/Identity/Identity.API/Identity.API.csproj @@ -5,6 +5,7 @@ aspnet-eShopOnContainers.Identity-90487118-103c-4ff0-b9da-e5e26f7ab0c5 ..\..\..\..\docker-compose.dcproj false + true $(LangVersion) @@ -40,13 +41,13 @@ - + diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index 533827ae2..e2d54814b 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -27,6 +27,7 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Middlewares; using Microsoft.Extensions.Diagnostics.HealthChecks; + using Microsoft.OpenApi.Models; using RabbitMQ.Client; using System; using System.Collections.Generic; @@ -127,18 +128,19 @@ services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo + options.SwaggerDoc("v1", new OpenApiInfo { Title = "Marketing HTTP API", Version = "v1", Description = "The Marketing Service HTTP API" }); - options.AddSecurityDefinition("oauth2", new OpenApi.Models.OpenApiSecurityScheme + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { - Flows = new OpenApi.Models.OpenApiOAuthFlows() + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() { - Implicit = new OpenApi.Models.OpenApiOAuthFlow() + Implicit = new OpenApiOAuthFlow() { AuthorizationUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), TokenUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/token"), diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index ddd53489a..a987f7bcb 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -26,6 +26,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; + using Microsoft.OpenApi.Models; using Ordering.Infrastructure; using RabbitMQ.Client; using System; @@ -234,18 +235,19 @@ services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo + options.SwaggerDoc("v1", new OpenApiInfo { Title = "Ordering HTTP API", Version = "v1", Description = "The Ordering Service HTTP API" }); - options.AddSecurityDefinition("oauth2", new OpenApi.Models.OpenApiSecurityScheme + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { - Flows = new OpenApi.Models.OpenApiOAuthFlows() + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() { - Implicit = new OpenApi.Models.OpenApiOAuthFlow() + Implicit = new OpenApiOAuthFlow() { AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), diff --git a/src/Services/Webhooks/Webhooks.API/Startup.cs b/src/Services/Webhooks/Webhooks.API/Startup.cs index c7f896b0b..cf501d46c 100644 --- a/src/Services/Webhooks/Webhooks.API/Startup.cs +++ b/src/Services/Webhooks/Webhooks.API/Startup.cs @@ -19,6 +19,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Models; using RabbitMQ.Client; using System; using System.Collections.Generic; @@ -189,18 +190,19 @@ namespace Webhooks.API services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo + options.SwaggerDoc("v1", new OpenApiInfo { Title = "eShopOnContainers - Webhooks HTTP API", Version = "v1", Description = "The Webhooks Microservice HTTP API. This is a simple webhooks CRUD registration entrypoint" }); - options.AddSecurityDefinition("oauth2", new Microsoft.OpenApi.Models.OpenApiSecurityScheme + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { - Flows = new Microsoft.OpenApi.Models.OpenApiOAuthFlows() + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() { - Implicit = new Microsoft.OpenApi.Models.OpenApiOAuthFlow() + Implicit = new OpenApiOAuthFlow() { AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), From 50a1e1311e058290c69c91fc93f4d75f9eadc18a Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Thu, 25 Jul 2019 11:30:17 +0200 Subject: [PATCH 023/113] update preview7 --- .../Mobile.Shopping.HttpAggregator.csproj | 1 + .../Mobile.Bff.Shopping/aggregator/Startup.cs | 4 +- .../Web.Bff.Shopping/aggregator/Startup.cs | 4 +- .../Web.Shopping.HttpAggregator.csproj | 1 + .../Basket/Basket.API/Basket.API.csproj | 1 + src/Services/Basket/Basket.API/Startup.cs | 4 +- .../Catalog/Catalog.API/Catalog.API.csproj | 1 + src/Services/Catalog/Catalog.API/Startup.cs | 2 + src/Services/Identity/Identity.API/Startup.cs | 39 +++++++++++-------- .../Locations.API/Locations.API.csproj | 1 + .../Location/Locations.API/Startup.cs | 3 ++ .../Marketing.API/Marketing.API.csproj | 1 + .../Marketing/Marketing.API/Startup.cs | 3 +- .../Ordering/Ordering.API/Ordering.API.csproj | 1 + src/Services/Ordering/Ordering.API/Startup.cs | 4 +- .../Ordering.BackgroundTasks.csproj | 1 + .../Ordering.SignalrHub.csproj | 1 + .../Payment/Payment.API/Payment.API.csproj | 1 + src/Services/Webhooks/Webhooks.API/Startup.cs | 5 ++- .../Webhooks/Webhooks.API/Webhooks.API.csproj | 1 + src/Web/WebMVC/Startup.cs | 2 + src/Web/WebMVC/WebMVC.csproj | 5 ++- src/Web/WebSPA/Startup.cs | 3 +- src/Web/WebSPA/WebSPA.csproj | 1 + src/Web/WebStatus/Startup.cs | 4 +- src/Web/WebStatus/WebStatus.csproj | 1 + src/Web/WebhookClient/Startup.cs | 8 ++-- src/Web/WebhookClient/WebhookClient.csproj | 1 + src/_build/dependencies.props | 21 +++++----- 29 files changed, 83 insertions(+), 42 deletions(-) diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj index d8d54643f..fdf05ab76 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj @@ -6,6 +6,7 @@ Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator ..\..\..\docker-compose.dcproj false + true $(LangVersion) diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index 716f0ec5c..d63e82749 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -50,6 +50,8 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator .AddCustomAuthentication(Configuration) .AddDevspaces() .AddHttpServices(); + + services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -80,6 +82,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -89,7 +92,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator { Predicate = r => r.Name.Contains("self") }); - endpoints.MapDefaultControllerRoute(); }); app.UseSwagger().UseSwaggerUI(c => diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index b8ef7b459..1c4655132 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -50,6 +50,8 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator .AddCustomAuthentication(Configuration) .AddDevspaces() .AddApplicationServices(); + + services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -79,6 +81,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -88,7 +91,6 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator { Predicate = r => r.Name.Contains("self") }); - endpoints.MapDefaultControllerRoute(); }); app.UseSwagger() diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj index 10d890062..a3eaa1ae6 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj @@ -6,6 +6,7 @@ Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator ..\..\..\docker-compose.dcproj false + true $(LangVersion) diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index 9c09a08bc..5281f9107 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -5,6 +5,7 @@ $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj false + true $(LangVersion) diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index 6a23c76d4..1273428fd 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -60,6 +60,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); + services.AddControllers(); + ConfigureAuthService(services); services.AddCustomHealthCheck(Configuration); @@ -200,6 +202,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -209,7 +212,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API { Predicate = r => r.Name.Contains("self") }); - endpoints.MapDefaultControllerRoute(); }); app.UseSwagger() diff --git a/src/Services/Catalog/Catalog.API/Catalog.API.csproj b/src/Services/Catalog/Catalog.API/Catalog.API.csproj index f20ba1c7d..0b32dea4b 100644 --- a/src/Services/Catalog/Catalog.API/Catalog.API.csproj +++ b/src/Services/Catalog/Catalog.API/Catalog.API.csproj @@ -9,6 +9,7 @@ aspnet-Catalog.API-20161122013618 ..\..\..\..\docker-compose.dcproj false + true $(LangVersion) diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 24d3395b0..5e96f90d8 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -55,6 +55,8 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API .AddSwagger() .AddCustomHealthCheck(Configuration); + services.AddControllers(); + var container = new ContainerBuilder(); container.Populate(services); diff --git a/src/Services/Identity/Identity.API/Startup.cs b/src/Services/Identity/Identity.API/Startup.cs index fd8e94c59..fbfff9828 100644 --- a/src/Services/Identity/Identity.API/Startup.cs +++ b/src/Services/Identity/Identity.API/Startup.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Identity.API.Certificates; using Microsoft.eShopOnContainers.Services.Identity.API.Data; @@ -39,13 +40,13 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API // Add framework services. services.AddDbContext(options => - options.UseSqlServer(Configuration["ConnectionString"], - sqlServerOptionsAction: sqlOptions => - { - sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); - //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency - sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); - })); + options.UseSqlServer(Configuration["ConnectionString"], + sqlServerOptionsAction: sqlOptions => + { + sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); + //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency + sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); + })); services.AddIdentity() .AddEntityFrameworkStores() @@ -94,17 +95,20 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API }); }) .AddOperationalStore(options => - { - options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, - sqlServerOptionsAction: sqlOptions => - { - sqlOptions.MigrationsAssembly(migrationsAssembly); - //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency - sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); - }); - }) + { + options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, + sqlServerOptionsAction: sqlOptions => + { + sqlOptions.MigrationsAssembly(migrationsAssembly); + //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency + sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); + }); + }) .Services.AddTransient(); + services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); + services.AddControllers(); + var container = new ContainerBuilder(); container.Populate(services); @@ -152,6 +156,8 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -161,7 +167,6 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API { Predicate = r => r.Name.Contains("self") }); - endpoints.MapDefaultControllerRoute(); }); } diff --git a/src/Services/Location/Locations.API/Locations.API.csproj b/src/Services/Location/Locations.API/Locations.API.csproj index 10b2a6f9b..a085f48a9 100644 --- a/src/Services/Location/Locations.API/Locations.API.csproj +++ b/src/Services/Location/Locations.API/Locations.API.csproj @@ -5,6 +5,7 @@ ..\..\..\..\docker-compose.dcproj aspnet-Locations.API-20161122013619 false + true $(LangVersion) diff --git a/src/Services/Location/Locations.API/Startup.cs b/src/Services/Location/Locations.API/Startup.cs index 7b4a391af..d71f05d60 100644 --- a/src/Services/Location/Locations.API/Startup.cs +++ b/src/Services/Location/Locations.API/Startup.cs @@ -51,6 +51,8 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); + services.AddControllers(); + ConfigureAuthService(services); services.Configure(Configuration); @@ -174,6 +176,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, diff --git a/src/Services/Marketing/Marketing.API/Marketing.API.csproj b/src/Services/Marketing/Marketing.API/Marketing.API.csproj index e07d4e444..486ec9b39 100644 --- a/src/Services/Marketing/Marketing.API/Marketing.API.csproj +++ b/src/Services/Marketing/Marketing.API/Marketing.API.csproj @@ -6,6 +6,7 @@ Microsoft.eShopOnContainers.Services.Marketing.API $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; false + true aspnet-Marketing.API-20161122013619 /subscriptions/6c22bb55-0221-4ce4-9bf1-3c4a10a7294c/resourcegroups/eshop-log/providers/microsoft.insights/components/eshopappinsights diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index e2d54814b..24064d3a3 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -59,6 +59,7 @@ .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); //Injecting Controllers themselves thru DIFor further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services + services.AddControllers(); services.Configure(Configuration); ConfigureAuthService(services); @@ -200,6 +201,7 @@ app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -209,7 +211,6 @@ { Predicate = r => r.Name.Contains("self") }); - endpoints.MapDefaultControllerRoute(); }); app.UseSwagger() diff --git a/src/Services/Ordering/Ordering.API/Ordering.API.csproj b/src/Services/Ordering/Ordering.API/Ordering.API.csproj index bb038d2e5..f61a94b72 100644 --- a/src/Services/Ordering/Ordering.API/Ordering.API.csproj +++ b/src/Services/Ordering/Ordering.API/Ordering.API.csproj @@ -6,6 +6,7 @@ $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj false + true $(LangVersion) diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index a987f7bcb..4e9480e70 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -56,6 +56,8 @@ .AddEventBus(Configuration) .AddCustomAuthentication(Configuration); + services.AddControllers(); + //configure autofac var container = new ContainerBuilder(); @@ -87,6 +89,7 @@ app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -96,7 +99,6 @@ { Predicate = r => r.Name.Contains("self") }); - endpoints.MapDefaultControllerRoute(); }); app.UseSwagger() diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj index ab193ddb9..3cca3adb7 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj @@ -5,6 +5,7 @@ $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\..\docker-compose.dcproj false + true $(LangVersion) diff --git a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj index 93bed4711..3da5b61f7 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj +++ b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj @@ -4,6 +4,7 @@ $(NetCoreTargetVersion) ..\..\..\..\docker-compose.dcproj false + true $(LangVersion) diff --git a/src/Services/Payment/Payment.API/Payment.API.csproj b/src/Services/Payment/Payment.API/Payment.API.csproj index 341dfd383..fbb1ad6aa 100644 --- a/src/Services/Payment/Payment.API/Payment.API.csproj +++ b/src/Services/Payment/Payment.API/Payment.API.csproj @@ -5,6 +5,7 @@ ..\..\..\..\docker-compose.dcproj $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; false + true $(LangVersion) diff --git a/src/Services/Webhooks/Webhooks.API/Startup.cs b/src/Services/Webhooks/Webhooks.API/Startup.cs index cf501d46c..14781383d 100644 --- a/src/Services/Webhooks/Webhooks.API/Startup.cs +++ b/src/Services/Webhooks/Webhooks.API/Startup.cs @@ -62,6 +62,8 @@ namespace Webhooks.API .AddTransient() .AddTransient(); + services.AddControllers(); + var container = new ContainerBuilder(); container.Populate(services); return new AutofacServiceProvider(container.Build()); @@ -86,6 +88,7 @@ namespace Webhooks.API app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -95,8 +98,6 @@ namespace Webhooks.API { Predicate = r => r.Name.Contains("self") }); - - endpoints.MapDefaultControllerRoute(); }); app.UseSwagger() diff --git a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj index ed474e741..7acf9d3ed 100644 --- a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj +++ b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj @@ -6,6 +6,7 @@ Linux $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; false + true $(LangVersion) diff --git a/src/Web/WebMVC/Startup.cs b/src/Web/WebMVC/Startup.cs index db53a23b9..b250c365c 100644 --- a/src/Web/WebMVC/Startup.cs +++ b/src/Web/WebMVC/Startup.cs @@ -45,6 +45,8 @@ namespace Microsoft.eShopOnContainers.WebMVC .AddHttpClientServices(Configuration) //.AddHttpClientLogging(Configuration) //Opt-in HttpClientLogging config .AddCustomAuthentication(Configuration); + + services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/src/Web/WebMVC/WebMVC.csproj b/src/Web/WebMVC/WebMVC.csproj index 25fc670fd..570dd7f87 100644 --- a/src/Web/WebMVC/WebMVC.csproj +++ b/src/Web/WebMVC/WebMVC.csproj @@ -6,6 +6,7 @@ ..\..\..\docker-compose.dcproj 3.0 false + true $(LangVersion) @@ -45,13 +46,13 @@ - + diff --git a/src/Web/WebSPA/Startup.cs b/src/Web/WebSPA/Startup.cs index 50e4dbef2..431ea5fbb 100644 --- a/src/Web/WebSPA/Startup.cs +++ b/src/Web/WebSPA/Startup.cs @@ -48,6 +48,8 @@ namespace eShopConContainers.WebSPA .AddUrlGroup(new Uri(Configuration["MarketingUrlHC"]), name: "marketingapigw-check", tags: new string[] { "marketingapigw" }) .AddUrlGroup(new Uri(Configuration["IdentityUrlHC"]), name: "identityapi-check", tags: new string[] { "identityapi" }); + services.AddControllers(); + services.Configure(Configuration); if (Configuration.GetValue("IsClusterEnv") == bool.TrueString) @@ -125,7 +127,6 @@ namespace eShopConContainers.WebSPA app.UseRouting(); app.UseEndpoints(endpoints => { - endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/liveness", new HealthCheckOptions { Predicate = r => r.Name.Contains("self") diff --git a/src/Web/WebSPA/WebSPA.csproj b/src/Web/WebSPA/WebSPA.csproj index f219dc5aa..caafa33af 100644 --- a/src/Web/WebSPA/WebSPA.csproj +++ b/src/Web/WebSPA/WebSPA.csproj @@ -5,6 +5,7 @@ aspnetcorespa-c23d27a4-eb88-4b18-9b77-2a93f3b15119 ..\..\..\docker-compose.dcproj false + true true wwwroot/dist/** $(DefaultItemExcludes);$(GeneratedItemPatterns) diff --git a/src/Web/WebStatus/Startup.cs b/src/Web/WebStatus/Startup.cs index eeabd0912..3dadeb842 100644 --- a/src/Web/WebStatus/Startup.cs +++ b/src/Web/WebStatus/Startup.cs @@ -23,6 +23,8 @@ namespace WebStatus { RegisterAppInsights(services); + services.AddControllers(); + services.AddOptions(); services.AddHealthChecks() .AddCheck("self", () => HealthCheckResult.Healthy()); @@ -67,7 +69,7 @@ namespace WebStatus app.UseRouting(); app.UseEndpoints(endpoints => { - endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); + endpoints.MapDefaultControllerRoute(); endpoints.MapHealthChecks("/liveness", new HealthCheckOptions { Predicate = r => r.Name.Contains("self") diff --git a/src/Web/WebStatus/WebStatus.csproj b/src/Web/WebStatus/WebStatus.csproj index 28f4bce18..0d32dded9 100644 --- a/src/Web/WebStatus/WebStatus.csproj +++ b/src/Web/WebStatus/WebStatus.csproj @@ -3,6 +3,7 @@ $(NetCoreTargetVersion) $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; ..\..\..\docker-compose.dcproj + true $(LangVersion) diff --git a/src/Web/WebhookClient/Startup.cs b/src/Web/WebhookClient/Startup.cs index 3b56d20fb..f93f61a5f 100644 --- a/src/Web/WebhookClient/Startup.cs +++ b/src/Web/WebhookClient/Startup.cs @@ -26,8 +26,7 @@ namespace WebhookClient // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - services - .AddSession(opt => + services.AddSession(opt => { opt.Cookie.Name = ".eShopWebhooks.Session"; }) @@ -36,7 +35,10 @@ namespace WebhookClient .AddCustomAuthentication(Configuration) .AddTransient() .AddSingleton() - .AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); + .AddMvc() + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); + + services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/src/Web/WebhookClient/WebhookClient.csproj b/src/Web/WebhookClient/WebhookClient.csproj index 22cb5afe2..7ec831b97 100644 --- a/src/Web/WebhookClient/WebhookClient.csproj +++ b/src/Web/WebhookClient/WebhookClient.csproj @@ -7,6 +7,7 @@ 36215d41-f31a-4aa6-9929-bd67d650e7b5 $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; false + true $(LangVersion) diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index df4140c77..a5f7c6459 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -48,29 +48,28 @@ 1.0.2 3.0.0-preview4-19123-01 3.0.0-alpha1-10670 - 3.0.0-preview6-19253-01 2.2.0-preview2-35157 3.0.0-alpha1-34847 - 3.0.0-preview6.19307.2 - 3.0.0-preview6.19307.2 + 3.0.0-preview7.19365.7 + 3.0.0-preview7.19365.7 2.2.0 1.0.0 2.2.0 3.0.0-preview6.19307.2 3.0.0-preview6.19307.2 - 3.0.0-preview6.19307.2 - 3.0.0-preview6-19253-01 + 3.0.0-preview7.19365.7 + 3.0.0-preview7.19365.7 3.0.0-preview4-19123-01 3.0.0-preview4-19123-01 7.5.0 3.0.0 4.5.0 - 4.7.0-preview6.19303.8 + 4.7.0-preview7.19362.9 3.0.0-preview6.19303.8 - 3.0.0-preview6.19304.10 - 3.0.0-preview6.19304.10 - 3.0.0-preview6.19304.10 - 3.0.0-preview6.19304.10 + 3.0.0-preview7.19362.6 + 3.0.0-preview7.19362.6 + 3.0.0-preview7.19362.6 + 3.0.0-preview7.19362.6 3.0.0-preview7.19365.7 2.2.0 2.2.0 @@ -78,7 +77,7 @@ 2.2.0 2.2.0 2.2.0 - 3.0.0-preview6.19304.6 + 3.0.0-preview7.19362.4 16.0.1 2.5.0 2.5.0 From bacf302904fce53fc2b8783730ba4a13d4723e7d Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Fri, 26 Jul 2019 08:18:51 +0200 Subject: [PATCH 024/113] add migration core3 --- src/Services/Basket/Basket.API/Startup.cs | 23 +- .../Factories/ApplicationDbContextFactory.cs | 26 + .../ConfigurationDbContextFactory.cs | 28 + .../PersistedGrantDbContextFactory.cs | 28 + .../20190725132846_core3.Designer.cs | 708 ++++++++++++++++++ .../ConfigurationDb/20190725132846_core3.cs | 294 ++++++++ .../ConfigurationDbContextModelSnapshot.cs | 248 ++++-- src/Services/Identity/Identity.API/Startup.cs | 5 +- src/_build/dependencies.props | 1 + 9 files changed, 1284 insertions(+), 77 deletions(-) create mode 100644 src/Services/Identity/Identity.API/Factories/ApplicationDbContextFactory.cs create mode 100644 src/Services/Identity/Identity.API/Factories/ConfigurationDbContextFactory.cs create mode 100644 src/Services/Identity/Identity.API/Factories/PersistedGrantDbContextFactory.cs create mode 100644 src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.Designer.cs create mode 100644 src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.cs diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index 1273428fd..cce2c2b96 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -10,7 +10,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.ServiceBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; @@ -51,16 +50,22 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API RegisterAppInsights(services); // Add framework services. - services.AddMvc(options => - { - options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - options.Filters.Add(typeof(ValidateModelStateFilter)); + //services.AddMvc(options => + // { + // options.Filters.Add(typeof(HttpGlobalExceptionFilter)); + // options.Filters.Add(typeof(ValidateModelStateFilter)); + + // }) + // .AddNewtonsoftJson() + // .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) + // .AddControllersAsServices(); - }) - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) - .AddControllersAsServices(); + services.AddControllers(options => + { + options.Filters.Add(typeof(HttpGlobalExceptionFilter)); + options.Filters.Add(typeof(ValidateModelStateFilter)); - services.AddControllers(); + }).AddNewtonsoftJson(); ConfigureAuthService(services); diff --git a/src/Services/Identity/Identity.API/Factories/ApplicationDbContextFactory.cs b/src/Services/Identity/Identity.API/Factories/ApplicationDbContextFactory.cs new file mode 100644 index 000000000..bb3f7bfe2 --- /dev/null +++ b/src/Services/Identity/Identity.API/Factories/ApplicationDbContextFactory.cs @@ -0,0 +1,26 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.eShopOnContainers.Services.Identity.API.Data; +using Microsoft.Extensions.Configuration; +using System.IO; + +namespace Identity.API.Factories +{ + public class ApplicationDbContextFactory : IDesignTimeDbContextFactory + { + public ApplicationDbContext CreateDbContext(string[] args) + { + var config = new ConfigurationBuilder() + .SetBasePath(Path.Combine(Directory.GetCurrentDirectory())) + .AddJsonFile("appsettings.json") + .AddEnvironmentVariables() + .Build(); + + var optionsBuilder = new DbContextOptionsBuilder(); + + optionsBuilder.UseSqlServer(config["ConnectionString"], sqlServerOptionsAction: o => o.MigrationsAssembly("Identity.API")); + + return new ApplicationDbContext(optionsBuilder.Options); + } + } +} \ No newline at end of file diff --git a/src/Services/Identity/Identity.API/Factories/ConfigurationDbContextFactory.cs b/src/Services/Identity/Identity.API/Factories/ConfigurationDbContextFactory.cs new file mode 100644 index 000000000..e304f50a8 --- /dev/null +++ b/src/Services/Identity/Identity.API/Factories/ConfigurationDbContextFactory.cs @@ -0,0 +1,28 @@ +using IdentityServer4.EntityFramework.DbContexts; +using IdentityServer4.EntityFramework.Options; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.Extensions.Configuration; +using System.IO; + +namespace Identity.API.Factories +{ + public class ConfigurationDbContextFactory : IDesignTimeDbContextFactory + { + public ConfigurationDbContext CreateDbContext(string[] args) + { + var config = new ConfigurationBuilder() + .SetBasePath(Path.Combine(Directory.GetCurrentDirectory())) + .AddJsonFile("appsettings.json") + .AddEnvironmentVariables() + .Build(); + + var optionsBuilder = new DbContextOptionsBuilder(); + var storeOptions = new ConfigurationStoreOptions(); + + optionsBuilder.UseSqlServer(config["ConnectionString"], sqlServerOptionsAction: o => o.MigrationsAssembly("Identity.API")); + + return new ConfigurationDbContext(optionsBuilder.Options, storeOptions); + } + } +} \ No newline at end of file diff --git a/src/Services/Identity/Identity.API/Factories/PersistedGrantDbContextFactory.cs b/src/Services/Identity/Identity.API/Factories/PersistedGrantDbContextFactory.cs new file mode 100644 index 000000000..b3dff8d9a --- /dev/null +++ b/src/Services/Identity/Identity.API/Factories/PersistedGrantDbContextFactory.cs @@ -0,0 +1,28 @@ +using IdentityServer4.EntityFramework.DbContexts; +using IdentityServer4.EntityFramework.Options; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.Extensions.Configuration; +using System.IO; + +namespace Identity.API.Factories +{ + public class PersistedGrantDbContextFactory : IDesignTimeDbContextFactory + { + public PersistedGrantDbContext CreateDbContext(string[] args) + { + var config = new ConfigurationBuilder() + .SetBasePath(Path.Combine(Directory.GetCurrentDirectory())) + .AddJsonFile("appsettings.json") + .AddEnvironmentVariables() + .Build(); + + var optionsBuilder = new DbContextOptionsBuilder(); + var operationOptions = new OperationalStoreOptions(); + + optionsBuilder.UseSqlServer(config["ConnectionString"], sqlServerOptionsAction: o => o.MigrationsAssembly("Identity.API")); + + return new PersistedGrantDbContext(optionsBuilder.Options, operationOptions); + } + } +} \ No newline at end of file diff --git a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.Designer.cs b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.Designer.cs new file mode 100644 index 000000000..ed87031d4 --- /dev/null +++ b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.Designer.cs @@ -0,0 +1,708 @@ +// +using System; +using IdentityServer4.EntityFramework.DbContexts; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Identity.API.Migrations.ConfigurationDb +{ + [DbContext(typeof(ConfigurationDbContext))] + [Migration("20190725132846_core3")] + partial class core3 + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "3.0.0-preview7.19362.6") + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("Created"); + + b.Property("Description") + .HasMaxLength(1000); + + b.Property("DisplayName") + .HasMaxLength(200); + + b.Property("Enabled"); + + b.Property("LastAccessed"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200); + + b.Property("NonEditable"); + + b.Property("Updated"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("ApiResources"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ApiResourceId"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(200); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.ToTable("ApiClaims"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ApiResourceId"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(250); + + b.Property("Value") + .IsRequired() + .HasMaxLength(2000); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.ToTable("ApiProperties"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ApiResourceId"); + + b.Property("Description") + .HasMaxLength(1000); + + b.Property("DisplayName") + .HasMaxLength(200); + + b.Property("Emphasize"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200); + + b.Property("Required"); + + b.Property("ShowInDiscoveryDocument"); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("ApiScopes"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ApiScopeId"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(200); + + b.HasKey("Id"); + + b.HasIndex("ApiScopeId"); + + b.ToTable("ApiScopeClaims"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ApiResourceId"); + + b.Property("Created"); + + b.Property("Description") + .HasMaxLength(1000); + + b.Property("Expiration"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(250); + + b.Property("Value") + .IsRequired() + .HasMaxLength(4000); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.ToTable("ApiSecrets"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("AbsoluteRefreshTokenLifetime"); + + b.Property("AccessTokenLifetime"); + + b.Property("AccessTokenType"); + + b.Property("AllowAccessTokensViaBrowser"); + + b.Property("AllowOfflineAccess"); + + b.Property("AllowPlainTextPkce"); + + b.Property("AllowRememberConsent"); + + b.Property("AlwaysIncludeUserClaimsInIdToken"); + + b.Property("AlwaysSendClientClaims"); + + b.Property("AuthorizationCodeLifetime"); + + b.Property("BackChannelLogoutSessionRequired"); + + b.Property("BackChannelLogoutUri") + .HasMaxLength(2000); + + b.Property("ClientClaimsPrefix") + .HasMaxLength(200); + + b.Property("ClientId") + .IsRequired() + .HasMaxLength(200); + + b.Property("ClientName") + .HasMaxLength(200); + + b.Property("ClientUri") + .HasMaxLength(2000); + + b.Property("ConsentLifetime"); + + b.Property("Created"); + + b.Property("Description") + .HasMaxLength(1000); + + b.Property("DeviceCodeLifetime"); + + b.Property("EnableLocalLogin"); + + b.Property("Enabled"); + + b.Property("FrontChannelLogoutSessionRequired"); + + b.Property("FrontChannelLogoutUri") + .HasMaxLength(2000); + + b.Property("IdentityTokenLifetime"); + + b.Property("IncludeJwtId"); + + b.Property("LastAccessed"); + + b.Property("LogoUri") + .HasMaxLength(2000); + + b.Property("NonEditable"); + + b.Property("PairWiseSubjectSalt") + .HasMaxLength(200); + + b.Property("ProtocolType") + .IsRequired() + .HasMaxLength(200); + + b.Property("RefreshTokenExpiration"); + + b.Property("RefreshTokenUsage"); + + b.Property("RequireClientSecret"); + + b.Property("RequireConsent"); + + b.Property("RequirePkce"); + + b.Property("SlidingRefreshTokenLifetime"); + + b.Property("UpdateAccessTokenClaimsOnRefresh"); + + b.Property("Updated"); + + b.Property("UserCodeType") + .HasMaxLength(100); + + b.Property("UserSsoLifetime"); + + b.HasKey("Id"); + + b.HasIndex("ClientId") + .IsUnique(); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ClientId"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(250); + + b.Property("Value") + .IsRequired() + .HasMaxLength(250); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientClaims"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ClientId"); + + b.Property("Origin") + .IsRequired() + .HasMaxLength(150); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientCorsOrigins"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ClientId"); + + b.Property("GrantType") + .IsRequired() + .HasMaxLength(250); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientGrantTypes"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ClientId"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(200); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientIdPRestrictions"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ClientId"); + + b.Property("PostLogoutRedirectUri") + .IsRequired() + .HasMaxLength(2000); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientPostLogoutRedirectUris"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ClientId"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(250); + + b.Property("Value") + .IsRequired() + .HasMaxLength(2000); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientProperties"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ClientId"); + + b.Property("RedirectUri") + .IsRequired() + .HasMaxLength(2000); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientRedirectUris"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ClientId"); + + b.Property("Scope") + .IsRequired() + .HasMaxLength(200); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientScopes"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ClientId"); + + b.Property("Created"); + + b.Property("Description") + .HasMaxLength(2000); + + b.Property("Expiration"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(250); + + b.Property("Value") + .IsRequired() + .HasMaxLength(4000); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientSecrets"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("IdentityResourceId"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(200); + + b.HasKey("Id"); + + b.HasIndex("IdentityResourceId"); + + b.ToTable("IdentityClaims"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("Created"); + + b.Property("Description") + .HasMaxLength(1000); + + b.Property("DisplayName") + .HasMaxLength(200); + + b.Property("Emphasize"); + + b.Property("Enabled"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200); + + b.Property("NonEditable"); + + b.Property("Required"); + + b.Property("ShowInDiscoveryDocument"); + + b.Property("Updated"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("IdentityResources"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("IdentityResourceId"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(250); + + b.Property("Value") + .IsRequired() + .HasMaxLength(2000); + + b.HasKey("Id"); + + b.HasIndex("IdentityResourceId"); + + b.ToTable("IdentityProperties"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany("UserClaims") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany("Properties") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany("Scopes") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "ApiScope") + .WithMany("UserClaims") + .HasForeignKey("ApiScopeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany("Secrets") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("Claims") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("AllowedCorsOrigins") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("AllowedGrantTypes") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("IdentityProviderRestrictions") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("PostLogoutRedirectUris") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("Properties") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("RedirectUris") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("AllowedScopes") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("ClientSecrets") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") + .WithMany("UserClaims") + .HasForeignKey("IdentityResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") + .WithMany("Properties") + .HasForeignKey("IdentityResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.cs b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.cs new file mode 100644 index 000000000..7ecf04015 --- /dev/null +++ b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.cs @@ -0,0 +1,294 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Identity.API.Migrations.ConfigurationDb +{ + public partial class core3 : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Created", + table: "IdentityResources", + nullable: false, + defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + + migrationBuilder.AddColumn( + name: "NonEditable", + table: "IdentityResources", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "Updated", + table: "IdentityResources", + nullable: true); + + migrationBuilder.AlterColumn( + name: "Value", + table: "ClientSecrets", + maxLength: 4000, + nullable: false, + oldClrType: typeof(string), + oldMaxLength: 2000); + + migrationBuilder.AlterColumn( + name: "Type", + table: "ClientSecrets", + maxLength: 250, + nullable: false, + oldClrType: typeof(string), + oldMaxLength: 250, + oldNullable: true); + + migrationBuilder.AddColumn( + name: "Created", + table: "ClientSecrets", + nullable: false, + defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + + migrationBuilder.AddColumn( + name: "Created", + table: "Clients", + nullable: false, + defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + + migrationBuilder.AddColumn( + name: "DeviceCodeLifetime", + table: "Clients", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "LastAccessed", + table: "Clients", + nullable: true); + + migrationBuilder.AddColumn( + name: "NonEditable", + table: "Clients", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "Updated", + table: "Clients", + nullable: true); + + migrationBuilder.AddColumn( + name: "UserCodeType", + table: "Clients", + maxLength: 100, + nullable: true); + + migrationBuilder.AddColumn( + name: "UserSsoLifetime", + table: "Clients", + nullable: true); + + migrationBuilder.AlterColumn( + name: "Value", + table: "ApiSecrets", + maxLength: 4000, + nullable: false, + oldClrType: typeof(string), + oldMaxLength: 2000, + oldNullable: true); + + migrationBuilder.AlterColumn( + name: "Type", + table: "ApiSecrets", + maxLength: 250, + nullable: false, + oldClrType: typeof(string), + oldMaxLength: 250, + oldNullable: true); + + migrationBuilder.AddColumn( + name: "Created", + table: "ApiSecrets", + nullable: false, + defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + + migrationBuilder.AddColumn( + name: "Created", + table: "ApiResources", + nullable: false, + defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + + migrationBuilder.AddColumn( + name: "LastAccessed", + table: "ApiResources", + nullable: true); + + migrationBuilder.AddColumn( + name: "NonEditable", + table: "ApiResources", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "Updated", + table: "ApiResources", + nullable: true); + + migrationBuilder.CreateTable( + name: "ApiProperties", + columns: table => new + { + Id = table.Column(nullable: false) + .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), + Key = table.Column(maxLength: 250, nullable: false), + Value = table.Column(maxLength: 2000, nullable: false), + ApiResourceId = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiProperties", x => x.Id); + table.ForeignKey( + name: "FK_ApiProperties_ApiResources_ApiResourceId", + column: x => x.ApiResourceId, + principalTable: "ApiResources", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "IdentityProperties", + columns: table => new + { + Id = table.Column(nullable: false) + .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), + Key = table.Column(maxLength: 250, nullable: false), + Value = table.Column(maxLength: 2000, nullable: false), + IdentityResourceId = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_IdentityProperties", x => x.Id); + table.ForeignKey( + name: "FK_IdentityProperties_IdentityResources_IdentityResourceId", + column: x => x.IdentityResourceId, + principalTable: "IdentityResources", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ApiProperties_ApiResourceId", + table: "ApiProperties", + column: "ApiResourceId"); + + migrationBuilder.CreateIndex( + name: "IX_IdentityProperties_IdentityResourceId", + table: "IdentityProperties", + column: "IdentityResourceId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ApiProperties"); + + migrationBuilder.DropTable( + name: "IdentityProperties"); + + migrationBuilder.DropColumn( + name: "Created", + table: "IdentityResources"); + + migrationBuilder.DropColumn( + name: "NonEditable", + table: "IdentityResources"); + + migrationBuilder.DropColumn( + name: "Updated", + table: "IdentityResources"); + + migrationBuilder.DropColumn( + name: "Created", + table: "ClientSecrets"); + + migrationBuilder.DropColumn( + name: "Created", + table: "Clients"); + + migrationBuilder.DropColumn( + name: "DeviceCodeLifetime", + table: "Clients"); + + migrationBuilder.DropColumn( + name: "LastAccessed", + table: "Clients"); + + migrationBuilder.DropColumn( + name: "NonEditable", + table: "Clients"); + + migrationBuilder.DropColumn( + name: "Updated", + table: "Clients"); + + migrationBuilder.DropColumn( + name: "UserCodeType", + table: "Clients"); + + migrationBuilder.DropColumn( + name: "UserSsoLifetime", + table: "Clients"); + + migrationBuilder.DropColumn( + name: "Created", + table: "ApiSecrets"); + + migrationBuilder.DropColumn( + name: "Created", + table: "ApiResources"); + + migrationBuilder.DropColumn( + name: "LastAccessed", + table: "ApiResources"); + + migrationBuilder.DropColumn( + name: "NonEditable", + table: "ApiResources"); + + migrationBuilder.DropColumn( + name: "Updated", + table: "ApiResources"); + + migrationBuilder.AlterColumn( + name: "Value", + table: "ClientSecrets", + maxLength: 2000, + nullable: false, + oldClrType: typeof(string), + oldMaxLength: 4000); + + migrationBuilder.AlterColumn( + name: "Type", + table: "ClientSecrets", + maxLength: 250, + nullable: true, + oldClrType: typeof(string), + oldMaxLength: 250); + + migrationBuilder.AlterColumn( + name: "Value", + table: "ApiSecrets", + maxLength: 2000, + nullable: true, + oldClrType: typeof(string), + oldMaxLength: 4000); + + migrationBuilder.AlterColumn( + name: "Type", + table: "ApiSecrets", + maxLength: 250, + nullable: true, + oldClrType: typeof(string), + oldMaxLength: 250); + } + } +} diff --git a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/ConfigurationDbContextModelSnapshot.cs b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/ConfigurationDbContextModelSnapshot.cs index 88d9baba3..ec91a8841 100644 --- a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/ConfigurationDbContextModelSnapshot.cs +++ b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/ConfigurationDbContextModelSnapshot.cs @@ -1,12 +1,10 @@ // +using System; using IdentityServer4.EntityFramework.DbContexts; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage; -using Microsoft.EntityFrameworkCore.Storage.Internal; -using System; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Identity.API.Migrations.ConfigurationDb { @@ -17,13 +15,17 @@ namespace Identity.API.Migrations.ConfigurationDb { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "2.0.0-rtm-26452") + .HasAnnotation("ProductVersion", "3.0.0-preview7.19362.6") + .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("Created"); b.Property("Description") .HasMaxLength(1000); @@ -33,10 +35,16 @@ namespace Identity.API.Migrations.ConfigurationDb b.Property("Enabled"); + b.Property("LastAccessed"); + b.Property("Name") .IsRequired() .HasMaxLength(200); + b.Property("NonEditable"); + + b.Property("Updated"); + b.HasKey("Id"); b.HasIndex("Name") @@ -48,10 +56,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ApiResourceId") - .IsRequired(); + b.Property("ApiResourceId"); b.Property("Type") .IsRequired() @@ -64,13 +72,36 @@ namespace Identity.API.Migrations.ConfigurationDb b.ToTable("ApiClaims"); }); + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("ApiResourceId"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(250); + + b.Property("Value") + .IsRequired() + .HasMaxLength(2000); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.ToTable("ApiProperties"); + }); + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ApiResourceId") - .IsRequired(); + b.Property("ApiResourceId"); b.Property("Description") .HasMaxLength(1000); @@ -101,10 +132,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ApiScopeId") - .IsRequired(); + b.Property("ApiScopeId"); b.Property("Type") .IsRequired() @@ -120,10 +151,12 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ApiResourceId") - .IsRequired(); + b.Property("ApiResourceId"); + + b.Property("Created"); b.Property("Description") .HasMaxLength(1000); @@ -131,10 +164,12 @@ namespace Identity.API.Migrations.ConfigurationDb b.Property("Expiration"); b.Property("Type") + .IsRequired() .HasMaxLength(250); b.Property("Value") - .HasMaxLength(2000); + .IsRequired() + .HasMaxLength(4000); b.HasKey("Id"); @@ -146,7 +181,8 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property("AbsoluteRefreshTokenLifetime"); @@ -188,9 +224,13 @@ namespace Identity.API.Migrations.ConfigurationDb b.Property("ConsentLifetime"); + b.Property("Created"); + b.Property("Description") .HasMaxLength(1000); + b.Property("DeviceCodeLifetime"); + b.Property("EnableLocalLogin"); b.Property("Enabled"); @@ -204,9 +244,13 @@ namespace Identity.API.Migrations.ConfigurationDb b.Property("IncludeJwtId"); + b.Property("LastAccessed"); + b.Property("LogoUri") .HasMaxLength(2000); + b.Property("NonEditable"); + b.Property("PairWiseSubjectSalt") .HasMaxLength(200); @@ -228,6 +272,13 @@ namespace Identity.API.Migrations.ConfigurationDb b.Property("UpdateAccessTokenClaimsOnRefresh"); + b.Property("Updated"); + + b.Property("UserCodeType") + .HasMaxLength(100); + + b.Property("UserSsoLifetime"); + b.HasKey("Id"); b.HasIndex("ClientId") @@ -239,10 +290,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ClientId") - .IsRequired(); + b.Property("ClientId"); b.Property("Type") .IsRequired() @@ -262,10 +313,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ClientId") - .IsRequired(); + b.Property("ClientId"); b.Property("Origin") .IsRequired() @@ -281,10 +332,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ClientId") - .IsRequired(); + b.Property("ClientId"); b.Property("GrantType") .IsRequired() @@ -300,10 +351,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ClientId") - .IsRequired(); + b.Property("ClientId"); b.Property("Provider") .IsRequired() @@ -319,10 +370,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ClientId") - .IsRequired(); + b.Property("ClientId"); b.Property("PostLogoutRedirectUri") .IsRequired() @@ -338,10 +389,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ClientId") - .IsRequired(); + b.Property("ClientId"); b.Property("Key") .IsRequired() @@ -361,10 +412,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ClientId") - .IsRequired(); + b.Property("ClientId"); b.Property("RedirectUri") .IsRequired() @@ -380,10 +431,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ClientId") - .IsRequired(); + b.Property("ClientId"); b.Property("Scope") .IsRequired() @@ -399,10 +450,12 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("ClientId") - .IsRequired(); + b.Property("ClientId"); + + b.Property("Created"); b.Property("Description") .HasMaxLength(2000); @@ -410,11 +463,12 @@ namespace Identity.API.Migrations.ConfigurationDb b.Property("Expiration"); b.Property("Type") + .IsRequired() .HasMaxLength(250); b.Property("Value") .IsRequired() - .HasMaxLength(2000); + .HasMaxLength(4000); b.HasKey("Id"); @@ -426,10 +480,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("IdentityResourceId") - .IsRequired(); + b.Property("IdentityResourceId"); b.Property("Type") .IsRequired() @@ -445,7 +499,10 @@ namespace Identity.API.Migrations.ConfigurationDb modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("Created"); b.Property("Description") .HasMaxLength(1000); @@ -461,10 +518,14 @@ namespace Identity.API.Migrations.ConfigurationDb .IsRequired() .HasMaxLength(200); + b.Property("NonEditable"); + b.Property("Required"); b.Property("ShowInDiscoveryDocument"); + b.Property("Updated"); + b.HasKey("Id"); b.HasIndex("Name") @@ -473,12 +534,45 @@ namespace Identity.API.Migrations.ConfigurationDb b.ToTable("IdentityResources"); }); + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("IdentityResourceId"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(250); + + b.Property("Value") + .IsRequired() + .HasMaxLength(2000); + + b.HasKey("Id"); + + b.HasIndex("IdentityResourceId"); + + b.ToTable("IdentityProperties"); + }); + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") .WithMany("UserClaims") .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany("Properties") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => @@ -486,7 +580,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") .WithMany("Scopes") .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => @@ -494,7 +589,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "ApiScope") .WithMany("UserClaims") .HasForeignKey("ApiScopeId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => @@ -502,7 +598,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") .WithMany("Secrets") .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => @@ -510,7 +607,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("Claims") .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => @@ -518,7 +616,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("AllowedCorsOrigins") .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => @@ -526,7 +625,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("AllowedGrantTypes") .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => @@ -534,7 +634,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("IdentityProviderRestrictions") .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => @@ -542,7 +643,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("PostLogoutRedirectUris") .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => @@ -550,7 +652,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("Properties") .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => @@ -558,7 +661,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("RedirectUris") .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => @@ -566,7 +670,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("AllowedScopes") .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => @@ -574,7 +679,8 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("ClientSecrets") .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => @@ -582,7 +688,17 @@ namespace Identity.API.Migrations.ConfigurationDb b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") .WithMany("UserClaims") .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") + .WithMany("Properties") + .HasForeignKey("IdentityResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); #pragma warning restore 612, 618 } diff --git a/src/Services/Identity/Identity.API/Startup.cs b/src/Services/Identity/Identity.API/Startup.cs index fbfff9828..3552bdaa1 100644 --- a/src/Services/Identity/Identity.API/Startup.cs +++ b/src/Services/Identity/Identity.API/Startup.cs @@ -7,7 +7,6 @@ using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Identity.API.Certificates; using Microsoft.eShopOnContainers.Services.Identity.API.Data; @@ -106,8 +105,10 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API }) .Services.AddTransient(); - services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); + //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddControllers(); + services.AddControllersWithViews(); + services.AddRazorPages(); var container = new ContainerBuilder(); container.Populate(services); diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index a5f7c6459..04704261e 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -70,6 +70,7 @@ 3.0.0-preview7.19362.6 3.0.0-preview7.19362.6 3.0.0-preview7.19362.6 + 3.0.0-preview7.19362.6 3.0.0-preview7.19365.7 2.2.0 2.2.0 From 5f9a1b8b8fac9bbda32df1ea801e3d626732220c Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Fri, 26 Jul 2019 08:19:16 +0200 Subject: [PATCH 025/113] package --- src/Services/Identity/Identity.API/Identity.API.csproj | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Services/Identity/Identity.API/Identity.API.csproj b/src/Services/Identity/Identity.API/Identity.API.csproj index b26032233..ed9900f5c 100644 --- a/src/Services/Identity/Identity.API/Identity.API.csproj +++ b/src/Services/Identity/Identity.API/Identity.API.csproj @@ -27,6 +27,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + From 8b0ec9038f7824d8b180c4a6ed8ce5862d58ac29 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Fri, 26 Jul 2019 09:42:43 +0200 Subject: [PATCH 026/113] fix routing --- src/Services/Basket/Basket.API/Startup.cs | 13 ++----------- src/Services/Catalog/Catalog.API/Startup.cs | 14 +++++++------- src/Services/Location/Locations.API/Startup.cs | 6 +++++- src/Services/Marketing/Marketing.API/Startup.cs | 13 +++---------- src/_build/dependencies.props | 2 +- 5 files changed, 18 insertions(+), 30 deletions(-) diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index cce2c2b96..a85e7ddc0 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -49,17 +49,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API { RegisterAppInsights(services); - // Add framework services. - //services.AddMvc(options => - // { - // options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - // options.Filters.Add(typeof(ValidateModelStateFilter)); - - // }) - // .AddNewtonsoftJson() - // .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) - // .AddControllersAsServices(); - services.AddControllers(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); @@ -204,10 +193,12 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API ConfigureAuth(app); + app.UseAuthorization(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 5e96f90d8..2a5f2bfb8 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -55,8 +55,6 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API .AddSwagger() .AddCustomHealthCheck(Configuration); - services.AddControllers(); - var container = new ContainerBuilder(); container.Populate(services); @@ -139,11 +137,13 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API public static IServiceCollection AddCustomMVC(this IServiceCollection services, IConfiguration configuration) { services.AddMvc(options => - { - options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - }) - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) - .AddControllersAsServices(); + { + options.Filters.Add(typeof(HttpGlobalExceptionFilter)); + }) + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) + .AddControllersAsServices(); + + services.AddControllers(); services.AddCors(options => { diff --git a/src/Services/Location/Locations.API/Startup.cs b/src/Services/Location/Locations.API/Startup.cs index d71f05d60..2199157c8 100644 --- a/src/Services/Location/Locations.API/Startup.cs +++ b/src/Services/Location/Locations.API/Startup.cs @@ -51,7 +51,11 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices(); - services.AddControllers(); + services.AddControllers(options => + { + options.Filters.Add(typeof(HttpGlobalExceptionFilter)); + + }).AddNewtonsoftJson(); ConfigureAuthService(services); diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index 24064d3a3..5fc3c60d3 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -23,7 +23,6 @@ using Marketing.API.IntegrationEvents.Handlers; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Diagnostics.HealthChecks; - using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Middlewares; using Microsoft.Extensions.Diagnostics.HealthChecks; @@ -50,15 +49,7 @@ RegisterAppInsights(services); // Add framework services. - services - .AddCustomHealthCheck(Configuration) - .AddMvc(options => - { - options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - }) - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) - .AddControllersAsServices(); //Injecting Controllers themselves thru DIFor further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services - + services.AddCustomHealthCheck(Configuration); services.AddControllers(); services.Configure(Configuration); @@ -198,10 +189,12 @@ ConfigureAuth(app); + app.UseAuthorization(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 04704261e..5dc91f6ec 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -72,7 +72,7 @@ 3.0.0-preview7.19362.6 3.0.0-preview7.19362.6 3.0.0-preview7.19365.7 - 2.2.0 + 3.0.0-preview7.19362.4 2.2.0 2.2.0 2.2.0 From e10fbfd6ea2e1555ed3c1cf32d2352b39ef15642 Mon Sep 17 00:00:00 2001 From: ericuss Date: Fri, 26 Jul 2019 10:54:17 +0200 Subject: [PATCH 027/113] Migrate Ordering.UnitTests and fix packages of Ordering.API --- .../WebHost.Customization/WebHost.Customization.csproj | 2 ++ .../Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj | 2 +- src/Services/Ordering/Ordering.API/Ordering.API.csproj | 1 + src/Services/Ordering/Ordering.API/Startup.cs | 3 +-- .../Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj | 5 ++++- src/_build/dependencies.props | 2 +- 6 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj index acae2354a..3cf310aac 100644 --- a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj +++ b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj @@ -2,6 +2,7 @@ $(NetCoreTargetVersion) + false @@ -11,6 +12,7 @@ + diff --git a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj index 027b7d5d7..e603d6106 100644 --- a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj +++ b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj @@ -2,7 +2,7 @@ $(NetCoreTargetVersion) - + false false diff --git a/src/Services/Ordering/Ordering.API/Ordering.API.csproj b/src/Services/Ordering/Ordering.API/Ordering.API.csproj index f61a94b72..4bd20f8a3 100644 --- a/src/Services/Ordering/Ordering.API/Ordering.API.csproj +++ b/src/Services/Ordering/Ordering.API/Ordering.API.csproj @@ -46,6 +46,7 @@ + diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index 4e9480e70..bd0d8bda7 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -243,11 +243,10 @@ Version = "v1", Description = "The Ordering Service HTTP API" }); - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows() + Flows = new OpenApi.Models.OpenApiOAuthFlows() { Implicit = new OpenApiOAuthFlow() { diff --git a/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj b/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj index 6d5cb9186..98dcb53f8 100644 --- a/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj +++ b/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj @@ -2,12 +2,15 @@ $(NetCoreTargetVersion) - + false false + + + all diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 5dc91f6ec..18f81d6b3 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -65,12 +65,12 @@ 3.0.0 4.5.0 4.7.0-preview7.19362.9 - 3.0.0-preview6.19303.8 3.0.0-preview7.19362.6 3.0.0-preview7.19362.6 3.0.0-preview7.19362.6 3.0.0-preview7.19362.6 3.0.0-preview7.19362.6 + 3.0.0-preview7.19362.9 3.0.0-preview7.19365.7 3.0.0-preview7.19362.4 2.2.0 From 0a0b013b73d7a96f77cf37f30a1b5aef89c57709 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Fri, 26 Jul 2019 11:11:31 +0200 Subject: [PATCH 028/113] change startup routing --- src/Services/Catalog/Catalog.API/Startup.cs | 33 ++++++++++++++----- .../Location/Locations.API/Startup.cs | 12 ++----- src/Services/Ordering/Ordering.API/Startup.cs | 23 +++++++------ src/Services/Webhooks/Webhooks.API/Startup.cs | 17 ++++------ 4 files changed, 47 insertions(+), 38 deletions(-) diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 2a5f2bfb8..732e7cddd 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -26,8 +26,10 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.OpenApi.Models; using RabbitMQ.Client; using System; +using System.Collections.Generic; using System.Data.Common; using System.IO; using System.Reflection; @@ -52,7 +54,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API .AddCustomOptions(Configuration) .AddIntegrationServices(Configuration) .AddEventBus(Configuration) - .AddSwagger() + .AddSwagger(Configuration) .AddCustomHealthCheck(Configuration); var container = new ContainerBuilder(); @@ -76,11 +78,12 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API } app.UseCors("CorsPolicy"); - + app.UseAuthorization(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); endpoints.MapGet("/_proto/", async ctx => { ctx.Response.ContentType = "text/plain"; @@ -136,14 +139,10 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API public static IServiceCollection AddCustomMVC(this IServiceCollection services, IConfiguration configuration) { - services.AddMvc(options => + services.AddControllers(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - }) - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) - .AddControllersAsServices(); - - services.AddControllers(); + }); services.AddCors(options => { @@ -259,7 +258,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API return services; } - public static IServiceCollection AddSwagger(this IServiceCollection services) + public static IServiceCollection AddSwagger(this IServiceCollection services, IConfiguration configuration) { services.AddSwaggerGen(options => { @@ -270,6 +269,22 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API Version = "v1", Description = "The Catalog Microservice HTTP API. This is a Data-Driven/CRUD microservice sample" }); + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme + { + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() + { + Implicit = new OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "catalog", "Catalog API" } + } + } + } + }); }); return services; diff --git a/src/Services/Location/Locations.API/Startup.cs b/src/Services/Location/Locations.API/Startup.cs index 2199157c8..ff7c79416 100644 --- a/src/Services/Location/Locations.API/Startup.cs +++ b/src/Services/Location/Locations.API/Startup.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.ServiceBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; @@ -42,14 +41,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API { RegisterAppInsights(services); - services - .AddCustomHealthCheck(Configuration) - .AddMvc(options => - { - options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - }) - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) - .AddControllersAsServices(); + services.AddCustomHealthCheck(Configuration); services.AddControllers(options => { @@ -177,10 +169,12 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API ConfigureAuth(app); + app.UseAuthorization(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index 4e9480e70..b3dfa840c 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -55,9 +55,6 @@ .AddCustomConfiguration(Configuration) .AddEventBus(Configuration) .AddCustomAuthentication(Configuration); - - services.AddControllers(); - //configure autofac var container = new ContainerBuilder(); @@ -86,10 +83,12 @@ ConfigureAuth(app); + app.UseAuthorization(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -149,13 +148,17 @@ public static IServiceCollection AddCustomMvc(this IServiceCollection services) { // Add framework services. - services.AddMvc(options => - { - options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - }) - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) - .AddControllersAsServices(); //Injecting Controllers themselves thru DI - //For further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services + services.AddControllers(options => + { + options.Filters.Add(typeof(HttpGlobalExceptionFilter)); + }); + //services.AddMvc(options => + // { + // options.Filters.Add(typeof(HttpGlobalExceptionFilter)); + // }) + // .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) + // .AddControllersAsServices(); //Injecting Controllers themselves thru DI + // //For further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services services.AddCors(options => { diff --git a/src/Services/Webhooks/Webhooks.API/Startup.cs b/src/Services/Webhooks/Webhooks.API/Startup.cs index 14781383d..4d3bd2c81 100644 --- a/src/Services/Webhooks/Webhooks.API/Startup.cs +++ b/src/Services/Webhooks/Webhooks.API/Startup.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.ServiceBus; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -47,7 +46,7 @@ namespace Webhooks.API { services .AddAppInsight(Configuration) - .AddCustomMVC(Configuration) + .AddCustomRouting(Configuration) .AddCustomDbContext(Configuration) .AddSwagger(Configuration) .AddCustomHealthCheck(Configuration) @@ -62,8 +61,6 @@ namespace Webhooks.API .AddTransient() .AddTransient(); - services.AddControllers(); - var container = new ContainerBuilder(); container.Populate(services); return new AutofacServiceProvider(container.Build()); @@ -85,10 +82,12 @@ namespace Webhooks.API ConfigureAuth(app); + app.UseAuthorization(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -142,14 +141,12 @@ namespace Webhooks.API return services; } - public static IServiceCollection AddCustomMVC(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddCustomRouting(this IServiceCollection services, IConfiguration configuration) { - services.AddMvc(options => + services.AddControllers(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - }) - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) - .AddControllersAsServices(); + }); services.AddCors(options => { @@ -209,7 +206,7 @@ namespace Webhooks.API TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), Scopes = new Dictionary() { - { "marketing", "Marketing API" } + { "webhooks", "Webhooks API" } } } } From e9811980f396e0e0e3c4e5c901bcbac999a0b4d7 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Fri, 26 Jul 2019 15:39:50 +0200 Subject: [PATCH 029/113] fix catalog --- src/Services/Catalog/Catalog.API/Startup.cs | 33 +++++---------------- 1 file changed, 8 insertions(+), 25 deletions(-) diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 732e7cddd..0e01e044e 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -26,10 +26,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Microsoft.OpenApi.Models; using RabbitMQ.Client; using System; -using System.Collections.Generic; using System.Data.Common; using System.IO; using System.Reflection; @@ -77,8 +75,15 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API app.UsePathBase(pathBase); } + app.UseSwagger() + .UseSwaggerUI(c => + { + c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Catalog.API V1"); + }); + app.UseCors("CorsPolicy"); app.UseAuthorization(); + app.UseAuthentication(); app.UseRouting(); app.UseEndpoints(endpoints => { @@ -110,12 +115,6 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API }); }); - app.UseSwagger() - .UseSwaggerUI(c => - { - c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Catalog.API V1"); - }); - ConfigureEventBus(app); } @@ -142,7 +141,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API services.AddControllers(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - }); + }).AddNewtonsoftJson(); services.AddCors(options => { @@ -269,22 +268,6 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API Version = "v1", Description = "The Catalog Microservice HTTP API. This is a Data-Driven/CRUD microservice sample" }); - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows() - { - Implicit = new OpenApiOAuthFlow() - { - AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), - TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), - Scopes = new Dictionary() - { - { "catalog", "Catalog API" } - } - } - } - }); }); return services; From 671d8b1e27215becb3d1baebe0034eff5994d634 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Mon, 29 Jul 2019 13:21:00 +0200 Subject: [PATCH 030/113] fix to startup identiy: remove old migrations and add initial migration. --- .../Mobile.Bff.Shopping/aggregator/Startup.cs | 2 +- .../Web.Bff.Shopping/aggregator/Startup.cs | 2 +- .../WebHostExtensions.cs | 7 +- src/Services/Basket/Basket.API/Startup.cs | 29 +- src/Services/Catalog/Catalog.API/Startup.cs | 5 +- ...190729091724_InitialMigration.Designer.cs} | 220 +++---- ....cs => 20190729091724_InitialMigration.cs} | 105 ++-- .../ApplicationDbContextModelSnapshot.cs | 216 ++++--- .../20170927170433_Config.Designer.cs | 591 ------------------ .../ConfigurationDb/20190725132846_core3.cs | 294 --------- ...InitialConfigurationMigration.Designer.cs} | 4 +- ...29092011_InitialConfigurationMigration.cs} | 286 +++++---- .../PersistedGrantDb/20170927170423_Grants.cs | 39 -- ...nitialPersistedGrantMigration.Designer.cs} | 44 +- ...29092100_InitialPersistedGrantMigration.cs | 65 ++ .../PersistedGrantDbContextModelSnapshot.cs | 41 +- .../Location/Locations.API/Startup.cs | 2 +- .../Marketing/Marketing.API/Startup.cs | 24 +- src/Services/Ordering/Ordering.API/Startup.cs | 6 +- .../Ordering/Ordering.SignalrHub/Startup.cs | 1 - src/Services/Webhooks/Webhooks.API/Startup.cs | 1 - 21 files changed, 634 insertions(+), 1350 deletions(-) rename src/Services/Identity/Identity.API/Migrations/{20170912114036_Initial.Designer.cs => 20190729091724_InitialMigration.Designer.cs} (80%) rename src/Services/Identity/Identity.API/Migrations/{20170912114036_Initial.cs => 20190729091724_InitialMigration.cs} (58%) delete mode 100644 src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20170927170433_Config.Designer.cs delete mode 100644 src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.cs rename src/Services/Identity/Identity.API/Migrations/ConfigurationDb/{20190725132846_core3.Designer.cs => 20190729092011_InitialConfigurationMigration.Designer.cs} (99%) rename src/Services/Identity/Identity.API/Migrations/ConfigurationDb/{20170927170433_Config.cs => 20190729092011_InitialConfigurationMigration.cs} (62%) delete mode 100644 src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20170927170423_Grants.cs rename src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/{20170927170423_Grants.Designer.cs => 20190729092100_InitialPersistedGrantMigration.Designer.cs} (54%) create mode 100644 src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20190729092100_InitialPersistedGrantMigration.cs diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index d63e82749..0c690bbcc 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -121,7 +121,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new OpenApiInfo { - Title = "Shopping Aggregator for Mobile Clients", + Title = "eShopOnContainers - Shopping Aggregator for Mobile Clients", Version = "v1", Description = "Shopping Aggregator for Mobile Clients" }); diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index 1c4655132..9edbf2815 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -147,7 +147,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new OpenApiInfo { - Title = "Shopping Aggregator for Web Clients", + Title = "eShopOnContainers - Shopping Aggregator for Web Clients", Version = "v1", Description = "Shopping Aggregator for Web Clients" }); diff --git a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs index fd17f4a0d..17f030e02 100644 --- a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs +++ b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs @@ -40,12 +40,7 @@ namespace Microsoft.AspNetCore.Hosting else { var retry = Policy.Handle() - .WaitAndRetry(new TimeSpan[] - { - TimeSpan.FromSeconds(3), - TimeSpan.FromSeconds(5), - TimeSpan.FromSeconds(8), - }); + .WaitAndRetry(10, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); //if the sql server container is not created on run docker compose this //migration can't fail for network related exception. The retry options for DbContext only diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index a85e7ddc0..3620b0b00 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -43,7 +43,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API public IConfiguration Configuration { get; } - // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { @@ -130,7 +129,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new OpenApiInfo { - Title = "Basket HTTP API", + Title = "eShopOnContainers - Basket HTTP API", Version = "v1", Description = "The Basket Service HTTP API" }); @@ -151,7 +150,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API } } }); - }); services.AddCors(options => @@ -175,7 +173,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API return new AutofacServiceProvider(container.Build()); } - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { @@ -188,12 +185,19 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UsePathBase(pathBase); } + ConfigureAuth(app); + app.UseStaticFiles(); - app.UseCors("CorsPolicy"); - ConfigureAuth(app); + app.UseSwagger() + .UseSwaggerUI(setup => + { + setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); + setup.OAuthClientId("basketswaggerui"); + setup.OAuthAppName("Basket Swagger UI"); + }); - app.UseAuthorization(); + app.UseCors("CorsPolicy"); app.UseRouting(); app.UseEndpoints(endpoints => { @@ -210,16 +214,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API }); }); - app.UseSwagger() - .UseSwaggerUI(c => - { - c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); - c.OAuthClientId("basketswaggerui"); - c.OAuthAppName("Basket Swagger UI"); - }); - ConfigureEventBus(app); - } private void RegisterAppInsights(IServiceCollection services) @@ -255,8 +250,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UseMiddleware(); } - app.UseAuthentication(); app.UseAuthorization(); + app.UseAuthentication(); } private void RegisterEventBus(IServiceCollection services) diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 0e01e044e..9dcf81f01 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -26,6 +26,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.OpenApi.Models; using RabbitMQ.Client; using System; using System.Data.Common; @@ -82,8 +83,6 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API }); app.UseCors("CorsPolicy"); - app.UseAuthorization(); - app.UseAuthentication(); app.UseRouting(); app.UseEndpoints(endpoints => { @@ -262,7 +261,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new OpenApi.Models.OpenApiInfo + options.SwaggerDoc("v1", new OpenApiInfo { Title = "eShopOnContainers - Catalog HTTP API", Version = "v1", diff --git a/src/Services/Identity/Identity.API/Migrations/20170912114036_Initial.Designer.cs b/src/Services/Identity/Identity.API/Migrations/20190729091724_InitialMigration.Designer.cs similarity index 80% rename from src/Services/Identity/Identity.API/Migrations/20170912114036_Initial.Designer.cs rename to src/Services/Identity/Identity.API/Migrations/20190729091724_InitialMigration.Designer.cs index 0850b37b9..5ad802992 100644 --- a/src/Services/Identity/Identity.API/Migrations/20170912114036_Initial.Designer.cs +++ b/src/Services/Identity/Identity.API/Migrations/20190729091724_InitialMigration.Designer.cs @@ -1,114 +1,29 @@ // +using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.eShopOnContainers.Services.Identity.API.Data; -using System; namespace Identity.API.Migrations { [DbContext(typeof(ApplicationDbContext))] - [Migration("20170912114036_Initial")] - partial class Initial + [Migration("20190729091724_InitialMigration")] + partial class InitialMigration { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "2.0.0-rtm-26452") + .HasAnnotation("ProductVersion", "3.0.0-preview7.19362.6") + .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - modelBuilder.Entity("Identity.API.Models.ApplicationUser", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("AccessFailedCount"); - - b.Property("CardHolderName") - .IsRequired(); - - b.Property("CardNumber") - .IsRequired(); - - b.Property("CardType"); - - b.Property("City") - .IsRequired(); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken(); - - b.Property("Country") - .IsRequired(); - - b.Property("Email") - .HasMaxLength(256); - - b.Property("EmailConfirmed"); - - b.Property("Expiration") - .IsRequired(); - - b.Property("LastName") - .IsRequired(); - - b.Property("LockoutEnabled"); - - b.Property("LockoutEnd"); - - b.Property("Name") - .IsRequired(); - - b.Property("NormalizedEmail") - .HasMaxLength(256); - - b.Property("NormalizedUserName") - .HasMaxLength(256); - - b.Property("PasswordHash"); - - b.Property("PhoneNumber"); - - b.Property("PhoneNumberConfirmed"); - - b.Property("SecurityNumber") - .IsRequired(); - - b.Property("SecurityStamp"); - - b.Property("State") - .IsRequired(); - - b.Property("Street") - .IsRequired(); - - b.Property("TwoFactorEnabled"); - - b.Property("UserName") - .HasMaxLength(256); - - b.Property("ZipCode") - .IsRequired(); - - b.HasKey("Id"); - - b.HasIndex("NormalizedEmail") - .HasName("EmailIndex"); - - b.HasIndex("NormalizedUserName") - .IsUnique() - .HasName("UserNameIndex") - .HasFilter("[NormalizedUserName] IS NOT NULL"); - - b.ToTable("AspNetUsers"); - }); - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { - b.Property("Id") - .ValueGeneratedOnAdd(); + b.Property("Id"); b.Property("ConcurrencyStamp") .IsConcurrencyToken(); @@ -132,7 +47,8 @@ namespace Identity.API.Migrations modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property("ClaimType"); @@ -151,7 +67,8 @@ namespace Identity.API.Migrations modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property("ClaimType"); @@ -213,49 +130,140 @@ namespace Identity.API.Migrations b.ToTable("AspNetUserTokens"); }); + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Identity.API.Models.ApplicationUser", b => + { + b.Property("Id"); + + b.Property("AccessFailedCount"); + + b.Property("CardHolderName") + .IsRequired(); + + b.Property("CardNumber") + .IsRequired(); + + b.Property("CardType"); + + b.Property("City") + .IsRequired(); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken(); + + b.Property("Country") + .IsRequired(); + + b.Property("Email") + .HasMaxLength(256); + + b.Property("EmailConfirmed"); + + b.Property("Expiration") + .IsRequired(); + + b.Property("LastName") + .IsRequired(); + + b.Property("LockoutEnabled"); + + b.Property("LockoutEnd"); + + b.Property("Name") + .IsRequired(); + + b.Property("NormalizedEmail") + .HasMaxLength(256); + + b.Property("NormalizedUserName") + .HasMaxLength(256); + + b.Property("PasswordHash"); + + b.Property("PhoneNumber"); + + b.Property("PhoneNumberConfirmed"); + + b.Property("SecurityNumber") + .IsRequired(); + + b.Property("SecurityStamp"); + + b.Property("State") + .IsRequired(); + + b.Property("Street") + .IsRequired(); + + b.Property("TwoFactorEnabled"); + + b.Property("UserName") + .HasMaxLength(256); + + b.Property("ZipCode") + .IsRequired(); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers"); + }); + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => { - b.HasOne("Identity.API.Models.ApplicationUser") + b.HasOne("Microsoft.eShopOnContainers.Services.Identity.API.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => { - b.HasOne("Identity.API.Models.ApplicationUser") + b.HasOne("Microsoft.eShopOnContainers.Services.Identity.API.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); - b.HasOne("Identity.API.Models.ApplicationUser") + b.HasOne("Microsoft.eShopOnContainers.Services.Identity.API.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => { - b.HasOne("Identity.API.Models.ApplicationUser") + b.HasOne("Microsoft.eShopOnContainers.Services.Identity.API.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); #pragma warning restore 612, 618 } diff --git a/src/Services/Identity/Identity.API/Migrations/20170912114036_Initial.cs b/src/Services/Identity/Identity.API/Migrations/20190729091724_InitialMigration.cs similarity index 58% rename from src/Services/Identity/Identity.API/Migrations/20170912114036_Initial.cs rename to src/Services/Identity/Identity.API/Migrations/20190729091724_InitialMigration.cs index cf771dac8..447369dd0 100644 --- a/src/Services/Identity/Identity.API/Migrations/20170912114036_Initial.cs +++ b/src/Services/Identity/Identity.API/Migrations/20190729091724_InitialMigration.cs @@ -1,11 +1,10 @@ -using Microsoft.EntityFrameworkCore.Metadata; +using System; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; -using System; -using System.Collections.Generic; namespace Identity.API.Migrations { - public partial class Initial : Migration + public partial class InitialMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { @@ -13,10 +12,10 @@ namespace Identity.API.Migrations name: "AspNetRoles", columns: table => new { - Id = table.Column(type: "nvarchar(450)", nullable: false), - ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true), - Name = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), - NormalizedName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true) + Id = table.Column(nullable: false), + Name = table.Column(maxLength: 256, nullable: true), + NormalizedName = table.Column(maxLength: 256, nullable: true), + ConcurrencyStamp = table.Column(nullable: true) }, constraints: table => { @@ -27,33 +26,33 @@ namespace Identity.API.Migrations name: "AspNetUsers", columns: table => new { - Id = table.Column(type: "nvarchar(450)", nullable: false), - AccessFailedCount = table.Column(type: "int", nullable: false), - CardHolderName = table.Column(type: "nvarchar(max)", nullable: false), - CardNumber = table.Column(type: "nvarchar(max)", nullable: false), - CardType = table.Column(type: "int", nullable: false), - City = table.Column(type: "nvarchar(max)", nullable: false), - ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true), - Country = table.Column(type: "nvarchar(max)", nullable: false), - Email = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), - EmailConfirmed = table.Column(type: "bit", nullable: false), - Expiration = table.Column(type: "nvarchar(max)", nullable: false), - LastName = table.Column(type: "nvarchar(max)", nullable: false), - LockoutEnabled = table.Column(type: "bit", nullable: false), - LockoutEnd = table.Column(type: "datetimeoffset", nullable: true), - Name = table.Column(type: "nvarchar(max)", nullable: false), - NormalizedEmail = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), - NormalizedUserName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), - PasswordHash = table.Column(type: "nvarchar(max)", nullable: true), - PhoneNumber = table.Column(type: "nvarchar(max)", nullable: true), - PhoneNumberConfirmed = table.Column(type: "bit", nullable: false), - SecurityNumber = table.Column(type: "nvarchar(max)", nullable: false), - SecurityStamp = table.Column(type: "nvarchar(max)", nullable: true), - State = table.Column(type: "nvarchar(max)", nullable: false), - Street = table.Column(type: "nvarchar(max)", nullable: false), - TwoFactorEnabled = table.Column(type: "bit", nullable: false), - UserName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), - ZipCode = table.Column(type: "nvarchar(max)", nullable: false) + Id = table.Column(nullable: false), + UserName = table.Column(maxLength: 256, nullable: true), + NormalizedUserName = table.Column(maxLength: 256, nullable: true), + Email = table.Column(maxLength: 256, nullable: true), + NormalizedEmail = table.Column(maxLength: 256, nullable: true), + EmailConfirmed = table.Column(nullable: false), + PasswordHash = table.Column(nullable: true), + SecurityStamp = table.Column(nullable: true), + ConcurrencyStamp = table.Column(nullable: true), + PhoneNumber = table.Column(nullable: true), + PhoneNumberConfirmed = table.Column(nullable: false), + TwoFactorEnabled = table.Column(nullable: false), + LockoutEnd = table.Column(nullable: true), + LockoutEnabled = table.Column(nullable: false), + AccessFailedCount = table.Column(nullable: false), + CardNumber = table.Column(nullable: false), + SecurityNumber = table.Column(nullable: false), + Expiration = table.Column(nullable: false), + CardHolderName = table.Column(nullable: false), + CardType = table.Column(nullable: false), + Street = table.Column(nullable: false), + City = table.Column(nullable: false), + State = table.Column(nullable: false), + Country = table.Column(nullable: false), + ZipCode = table.Column(nullable: false), + Name = table.Column(nullable: false), + LastName = table.Column(nullable: false) }, constraints: table => { @@ -64,11 +63,11 @@ namespace Identity.API.Migrations name: "AspNetRoleClaims", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClaimType = table.Column(type: "nvarchar(max)", nullable: true), - ClaimValue = table.Column(type: "nvarchar(max)", nullable: true), - RoleId = table.Column(type: "nvarchar(450)", nullable: false) + RoleId = table.Column(nullable: false), + ClaimType = table.Column(nullable: true), + ClaimValue = table.Column(nullable: true) }, constraints: table => { @@ -85,11 +84,11 @@ namespace Identity.API.Migrations name: "AspNetUserClaims", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClaimType = table.Column(type: "nvarchar(max)", nullable: true), - ClaimValue = table.Column(type: "nvarchar(max)", nullable: true), - UserId = table.Column(type: "nvarchar(450)", nullable: false) + UserId = table.Column(nullable: false), + ClaimType = table.Column(nullable: true), + ClaimValue = table.Column(nullable: true) }, constraints: table => { @@ -106,10 +105,10 @@ namespace Identity.API.Migrations name: "AspNetUserLogins", columns: table => new { - LoginProvider = table.Column(type: "nvarchar(450)", nullable: false), - ProviderKey = table.Column(type: "nvarchar(450)", nullable: false), - ProviderDisplayName = table.Column(type: "nvarchar(max)", nullable: true), - UserId = table.Column(type: "nvarchar(450)", nullable: false) + LoginProvider = table.Column(nullable: false), + ProviderKey = table.Column(nullable: false), + ProviderDisplayName = table.Column(nullable: true), + UserId = table.Column(nullable: false) }, constraints: table => { @@ -126,8 +125,8 @@ namespace Identity.API.Migrations name: "AspNetUserRoles", columns: table => new { - UserId = table.Column(type: "nvarchar(450)", nullable: false), - RoleId = table.Column(type: "nvarchar(450)", nullable: false) + UserId = table.Column(nullable: false), + RoleId = table.Column(nullable: false) }, constraints: table => { @@ -150,10 +149,10 @@ namespace Identity.API.Migrations name: "AspNetUserTokens", columns: table => new { - UserId = table.Column(type: "nvarchar(450)", nullable: false), - LoginProvider = table.Column(type: "nvarchar(450)", nullable: false), - Name = table.Column(type: "nvarchar(450)", nullable: false), - Value = table.Column(type: "nvarchar(max)", nullable: true) + UserId = table.Column(nullable: false), + LoginProvider = table.Column(nullable: false), + Name = table.Column(nullable: false), + Value = table.Column(nullable: true) }, constraints: table => { diff --git a/src/Services/Identity/Identity.API/Migrations/ApplicationDbContextModelSnapshot.cs b/src/Services/Identity/Identity.API/Migrations/ApplicationDbContextModelSnapshot.cs index dcc87bc73..2819cd6eb 100644 --- a/src/Services/Identity/Identity.API/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/src/Services/Identity/Identity.API/Migrations/ApplicationDbContextModelSnapshot.cs @@ -1,9 +1,10 @@ // +using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.eShopOnContainers.Services.Identity.API.Data; -using System; namespace Identity.API.Migrations { @@ -14,99 +15,13 @@ namespace Identity.API.Migrations { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "2.0.0-rtm-26452") + .HasAnnotation("ProductVersion", "3.0.0-preview7.19362.6") + .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - modelBuilder.Entity("Identity.API.Models.ApplicationUser", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("AccessFailedCount"); - - b.Property("CardHolderName") - .IsRequired(); - - b.Property("CardNumber") - .IsRequired(); - - b.Property("CardType"); - - b.Property("City") - .IsRequired(); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken(); - - b.Property("Country") - .IsRequired(); - - b.Property("Email") - .HasMaxLength(256); - - b.Property("EmailConfirmed"); - - b.Property("Expiration") - .IsRequired(); - - b.Property("LastName") - .IsRequired(); - - b.Property("LockoutEnabled"); - - b.Property("LockoutEnd"); - - b.Property("Name") - .IsRequired(); - - b.Property("NormalizedEmail") - .HasMaxLength(256); - - b.Property("NormalizedUserName") - .HasMaxLength(256); - - b.Property("PasswordHash"); - - b.Property("PhoneNumber"); - - b.Property("PhoneNumberConfirmed"); - - b.Property("SecurityNumber") - .IsRequired(); - - b.Property("SecurityStamp"); - - b.Property("State") - .IsRequired(); - - b.Property("Street") - .IsRequired(); - - b.Property("TwoFactorEnabled"); - - b.Property("UserName") - .HasMaxLength(256); - - b.Property("ZipCode") - .IsRequired(); - - b.HasKey("Id"); - - b.HasIndex("NormalizedEmail") - .HasName("EmailIndex"); - - b.HasIndex("NormalizedUserName") - .IsUnique() - .HasName("UserNameIndex") - .HasFilter("[NormalizedUserName] IS NOT NULL"); - - b.ToTable("AspNetUsers"); - }); - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { - b.Property("Id") - .ValueGeneratedOnAdd(); + b.Property("Id"); b.Property("ConcurrencyStamp") .IsConcurrencyToken(); @@ -130,7 +45,8 @@ namespace Identity.API.Migrations modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property("ClaimType"); @@ -149,7 +65,8 @@ namespace Identity.API.Migrations modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property("ClaimType"); @@ -211,49 +128,140 @@ namespace Identity.API.Migrations b.ToTable("AspNetUserTokens"); }); + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Identity.API.Models.ApplicationUser", b => + { + b.Property("Id"); + + b.Property("AccessFailedCount"); + + b.Property("CardHolderName") + .IsRequired(); + + b.Property("CardNumber") + .IsRequired(); + + b.Property("CardType"); + + b.Property("City") + .IsRequired(); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken(); + + b.Property("Country") + .IsRequired(); + + b.Property("Email") + .HasMaxLength(256); + + b.Property("EmailConfirmed"); + + b.Property("Expiration") + .IsRequired(); + + b.Property("LastName") + .IsRequired(); + + b.Property("LockoutEnabled"); + + b.Property("LockoutEnd"); + + b.Property("Name") + .IsRequired(); + + b.Property("NormalizedEmail") + .HasMaxLength(256); + + b.Property("NormalizedUserName") + .HasMaxLength(256); + + b.Property("PasswordHash"); + + b.Property("PhoneNumber"); + + b.Property("PhoneNumberConfirmed"); + + b.Property("SecurityNumber") + .IsRequired(); + + b.Property("SecurityStamp"); + + b.Property("State") + .IsRequired(); + + b.Property("Street") + .IsRequired(); + + b.Property("TwoFactorEnabled"); + + b.Property("UserName") + .HasMaxLength(256); + + b.Property("ZipCode") + .IsRequired(); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers"); + }); + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => { - b.HasOne("Identity.API.Models.ApplicationUser") + b.HasOne("Microsoft.eShopOnContainers.Services.Identity.API.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => { - b.HasOne("Identity.API.Models.ApplicationUser") + b.HasOne("Microsoft.eShopOnContainers.Services.Identity.API.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); - b.HasOne("Identity.API.Models.ApplicationUser") + b.HasOne("Microsoft.eShopOnContainers.Services.Identity.API.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => { - b.HasOne("Identity.API.Models.ApplicationUser") + b.HasOne("Microsoft.eShopOnContainers.Services.Identity.API.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); #pragma warning restore 612, 618 } diff --git a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20170927170433_Config.Designer.cs b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20170927170433_Config.Designer.cs deleted file mode 100644 index 327d2fee0..000000000 --- a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20170927170433_Config.Designer.cs +++ /dev/null @@ -1,591 +0,0 @@ -// -using IdentityServer4.EntityFramework.DbContexts; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage; -using Microsoft.EntityFrameworkCore.Storage.Internal; -using System; - -namespace Identity.API.Migrations.ConfigurationDb -{ - [DbContext(typeof(ConfigurationDbContext))] - [Migration("20170927170433_Config")] - partial class Config - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "2.0.0-rtm-26452") - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Enabled"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiResourceId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiResourceId") - .IsRequired(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Emphasize"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("Required"); - - b.Property("ShowInDiscoveryDocument"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiScopeId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ApiScopeId"); - - b.ToTable("ApiScopeClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiResourceId") - .IsRequired(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("Expiration"); - - b.Property("Type") - .HasMaxLength(250); - - b.Property("Value") - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("AbsoluteRefreshTokenLifetime"); - - b.Property("AccessTokenLifetime"); - - b.Property("AccessTokenType"); - - b.Property("AllowAccessTokensViaBrowser"); - - b.Property("AllowOfflineAccess"); - - b.Property("AllowPlainTextPkce"); - - b.Property("AllowRememberConsent"); - - b.Property("AlwaysIncludeUserClaimsInIdToken"); - - b.Property("AlwaysSendClientClaims"); - - b.Property("AuthorizationCodeLifetime"); - - b.Property("BackChannelLogoutSessionRequired"); - - b.Property("BackChannelLogoutUri") - .HasMaxLength(2000); - - b.Property("ClientClaimsPrefix") - .HasMaxLength(200); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200); - - b.Property("ClientName") - .HasMaxLength(200); - - b.Property("ClientUri") - .HasMaxLength(2000); - - b.Property("ConsentLifetime"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("EnableLocalLogin"); - - b.Property("Enabled"); - - b.Property("FrontChannelLogoutSessionRequired"); - - b.Property("FrontChannelLogoutUri") - .HasMaxLength(2000); - - b.Property("IdentityTokenLifetime"); - - b.Property("IncludeJwtId"); - - b.Property("LogoUri") - .HasMaxLength(2000); - - b.Property("PairWiseSubjectSalt") - .HasMaxLength(200); - - b.Property("ProtocolType") - .IsRequired() - .HasMaxLength(200); - - b.Property("RefreshTokenExpiration"); - - b.Property("RefreshTokenUsage"); - - b.Property("RequireClientSecret"); - - b.Property("RequireConsent"); - - b.Property("RequirePkce"); - - b.Property("SlidingRefreshTokenLifetime"); - - b.Property("UpdateAccessTokenClaimsOnRefresh"); - - b.HasKey("Id"); - - b.HasIndex("ClientId") - .IsUnique(); - - b.ToTable("Clients"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(250); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Origin") - .IsRequired() - .HasMaxLength(150); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientCorsOrigins"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("GrantType") - .IsRequired() - .HasMaxLength(250); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientGrantTypes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Provider") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientIdPRestrictions"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("PostLogoutRedirectUri") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientPostLogoutRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("RedirectUri") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Scope") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Description") - .HasMaxLength(2000); - - b.Property("Expiration"); - - b.Property("Type") - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("IdentityResourceId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Emphasize"); - - b.Property("Enabled"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("Required"); - - b.Property("ShowInDiscoveryDocument"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("IdentityResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("UserClaims") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Scopes") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "ApiScope") - .WithMany("UserClaims") - .HasForeignKey("ApiScopeId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Secrets") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Claims") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedCorsOrigins") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedGrantTypes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("IdentityProviderRestrictions") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("PostLogoutRedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Properties") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("RedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedScopes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("ClientSecrets") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("UserClaims") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.cs b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.cs deleted file mode 100644 index 7ecf04015..000000000 --- a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.cs +++ /dev/null @@ -1,294 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace Identity.API.Migrations.ConfigurationDb -{ - public partial class core3 : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.AddColumn( - name: "Created", - table: "IdentityResources", - nullable: false, - defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); - - migrationBuilder.AddColumn( - name: "NonEditable", - table: "IdentityResources", - nullable: false, - defaultValue: false); - - migrationBuilder.AddColumn( - name: "Updated", - table: "IdentityResources", - nullable: true); - - migrationBuilder.AlterColumn( - name: "Value", - table: "ClientSecrets", - maxLength: 4000, - nullable: false, - oldClrType: typeof(string), - oldMaxLength: 2000); - - migrationBuilder.AlterColumn( - name: "Type", - table: "ClientSecrets", - maxLength: 250, - nullable: false, - oldClrType: typeof(string), - oldMaxLength: 250, - oldNullable: true); - - migrationBuilder.AddColumn( - name: "Created", - table: "ClientSecrets", - nullable: false, - defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); - - migrationBuilder.AddColumn( - name: "Created", - table: "Clients", - nullable: false, - defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); - - migrationBuilder.AddColumn( - name: "DeviceCodeLifetime", - table: "Clients", - nullable: false, - defaultValue: 0); - - migrationBuilder.AddColumn( - name: "LastAccessed", - table: "Clients", - nullable: true); - - migrationBuilder.AddColumn( - name: "NonEditable", - table: "Clients", - nullable: false, - defaultValue: false); - - migrationBuilder.AddColumn( - name: "Updated", - table: "Clients", - nullable: true); - - migrationBuilder.AddColumn( - name: "UserCodeType", - table: "Clients", - maxLength: 100, - nullable: true); - - migrationBuilder.AddColumn( - name: "UserSsoLifetime", - table: "Clients", - nullable: true); - - migrationBuilder.AlterColumn( - name: "Value", - table: "ApiSecrets", - maxLength: 4000, - nullable: false, - oldClrType: typeof(string), - oldMaxLength: 2000, - oldNullable: true); - - migrationBuilder.AlterColumn( - name: "Type", - table: "ApiSecrets", - maxLength: 250, - nullable: false, - oldClrType: typeof(string), - oldMaxLength: 250, - oldNullable: true); - - migrationBuilder.AddColumn( - name: "Created", - table: "ApiSecrets", - nullable: false, - defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); - - migrationBuilder.AddColumn( - name: "Created", - table: "ApiResources", - nullable: false, - defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); - - migrationBuilder.AddColumn( - name: "LastAccessed", - table: "ApiResources", - nullable: true); - - migrationBuilder.AddColumn( - name: "NonEditable", - table: "ApiResources", - nullable: false, - defaultValue: false); - - migrationBuilder.AddColumn( - name: "Updated", - table: "ApiResources", - nullable: true); - - migrationBuilder.CreateTable( - name: "ApiProperties", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - Key = table.Column(maxLength: 250, nullable: false), - Value = table.Column(maxLength: 2000, nullable: false), - ApiResourceId = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiProperties", x => x.Id); - table.ForeignKey( - name: "FK_ApiProperties_ApiResources_ApiResourceId", - column: x => x.ApiResourceId, - principalTable: "ApiResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "IdentityProperties", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - Key = table.Column(maxLength: 250, nullable: false), - Value = table.Column(maxLength: 2000, nullable: false), - IdentityResourceId = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_IdentityProperties", x => x.Id); - table.ForeignKey( - name: "FK_IdentityProperties_IdentityResources_IdentityResourceId", - column: x => x.IdentityResourceId, - principalTable: "IdentityResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_ApiProperties_ApiResourceId", - table: "ApiProperties", - column: "ApiResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_IdentityProperties_IdentityResourceId", - table: "IdentityProperties", - column: "IdentityResourceId"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "ApiProperties"); - - migrationBuilder.DropTable( - name: "IdentityProperties"); - - migrationBuilder.DropColumn( - name: "Created", - table: "IdentityResources"); - - migrationBuilder.DropColumn( - name: "NonEditable", - table: "IdentityResources"); - - migrationBuilder.DropColumn( - name: "Updated", - table: "IdentityResources"); - - migrationBuilder.DropColumn( - name: "Created", - table: "ClientSecrets"); - - migrationBuilder.DropColumn( - name: "Created", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "DeviceCodeLifetime", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "LastAccessed", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "NonEditable", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "Updated", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "UserCodeType", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "UserSsoLifetime", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "Created", - table: "ApiSecrets"); - - migrationBuilder.DropColumn( - name: "Created", - table: "ApiResources"); - - migrationBuilder.DropColumn( - name: "LastAccessed", - table: "ApiResources"); - - migrationBuilder.DropColumn( - name: "NonEditable", - table: "ApiResources"); - - migrationBuilder.DropColumn( - name: "Updated", - table: "ApiResources"); - - migrationBuilder.AlterColumn( - name: "Value", - table: "ClientSecrets", - maxLength: 2000, - nullable: false, - oldClrType: typeof(string), - oldMaxLength: 4000); - - migrationBuilder.AlterColumn( - name: "Type", - table: "ClientSecrets", - maxLength: 250, - nullable: true, - oldClrType: typeof(string), - oldMaxLength: 250); - - migrationBuilder.AlterColumn( - name: "Value", - table: "ApiSecrets", - maxLength: 2000, - nullable: true, - oldClrType: typeof(string), - oldMaxLength: 4000); - - migrationBuilder.AlterColumn( - name: "Type", - table: "ApiSecrets", - maxLength: 250, - nullable: true, - oldClrType: typeof(string), - oldMaxLength: 250); - } - } -} diff --git a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.Designer.cs b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190729092011_InitialConfigurationMigration.Designer.cs similarity index 99% rename from src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.Designer.cs rename to src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190729092011_InitialConfigurationMigration.Designer.cs index ed87031d4..5e801b306 100644 --- a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190725132846_core3.Designer.cs +++ b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190729092011_InitialConfigurationMigration.Designer.cs @@ -10,8 +10,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Identity.API.Migrations.ConfigurationDb { [DbContext(typeof(ConfigurationDbContext))] - [Migration("20190725132846_core3")] - partial class core3 + [Migration("20190729092011_InitialConfigurationMigration")] + partial class InitialConfigurationMigration { protected override void BuildTargetModel(ModelBuilder modelBuilder) { diff --git a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20170927170433_Config.cs b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190729092011_InitialConfigurationMigration.cs similarity index 62% rename from src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20170927170433_Config.cs rename to src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190729092011_InitialConfigurationMigration.cs index 754c75486..05155a83c 100644 --- a/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20170927170433_Config.cs +++ b/src/Services/Identity/Identity.API/Migrations/ConfigurationDb/20190729092011_InitialConfigurationMigration.cs @@ -1,10 +1,10 @@ -using Microsoft.EntityFrameworkCore.Metadata; +using System; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; -using System; namespace Identity.API.Migrations.ConfigurationDb { - public partial class Config : Migration + public partial class InitialConfigurationMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { @@ -12,12 +12,16 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ApiResources", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - Description = table.Column(type: "nvarchar(1000)", maxLength: 1000, nullable: true), - DisplayName = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), - Enabled = table.Column(type: "bit", nullable: false), - Name = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false) + Enabled = table.Column(nullable: false), + Name = table.Column(maxLength: 200, nullable: false), + DisplayName = table.Column(maxLength: 200, nullable: true), + Description = table.Column(maxLength: 1000, nullable: true), + Created = table.Column(nullable: false), + Updated = table.Column(nullable: true), + LastAccessed = table.Column(nullable: true), + NonEditable = table.Column(nullable: false) }, constraints: table => { @@ -28,42 +32,49 @@ namespace Identity.API.Migrations.ConfigurationDb name: "Clients", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - AbsoluteRefreshTokenLifetime = table.Column(type: "int", nullable: false), - AccessTokenLifetime = table.Column(type: "int", nullable: false), - AccessTokenType = table.Column(type: "int", nullable: false), - AllowAccessTokensViaBrowser = table.Column(type: "bit", nullable: false), - AllowOfflineAccess = table.Column(type: "bit", nullable: false), - AllowPlainTextPkce = table.Column(type: "bit", nullable: false), - AllowRememberConsent = table.Column(type: "bit", nullable: false), - AlwaysIncludeUserClaimsInIdToken = table.Column(type: "bit", nullable: false), - AlwaysSendClientClaims = table.Column(type: "bit", nullable: false), - AuthorizationCodeLifetime = table.Column(type: "int", nullable: false), - BackChannelLogoutSessionRequired = table.Column(type: "bit", nullable: false), - BackChannelLogoutUri = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true), - ClientClaimsPrefix = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), - ClientId = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), - ClientName = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), - ClientUri = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true), - ConsentLifetime = table.Column(type: "int", nullable: true), - Description = table.Column(type: "nvarchar(1000)", maxLength: 1000, nullable: true), - EnableLocalLogin = table.Column(type: "bit", nullable: false), - Enabled = table.Column(type: "bit", nullable: false), - FrontChannelLogoutSessionRequired = table.Column(type: "bit", nullable: false), - FrontChannelLogoutUri = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true), - IdentityTokenLifetime = table.Column(type: "int", nullable: false), - IncludeJwtId = table.Column(type: "bit", nullable: false), - LogoUri = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true), - PairWiseSubjectSalt = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), - ProtocolType = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), - RefreshTokenExpiration = table.Column(type: "int", nullable: false), - RefreshTokenUsage = table.Column(type: "int", nullable: false), - RequireClientSecret = table.Column(type: "bit", nullable: false), - RequireConsent = table.Column(type: "bit", nullable: false), - RequirePkce = table.Column(type: "bit", nullable: false), - SlidingRefreshTokenLifetime = table.Column(type: "int", nullable: false), - UpdateAccessTokenClaimsOnRefresh = table.Column(type: "bit", nullable: false) + Enabled = table.Column(nullable: false), + ClientId = table.Column(maxLength: 200, nullable: false), + ProtocolType = table.Column(maxLength: 200, nullable: false), + RequireClientSecret = table.Column(nullable: false), + ClientName = table.Column(maxLength: 200, nullable: true), + Description = table.Column(maxLength: 1000, nullable: true), + ClientUri = table.Column(maxLength: 2000, nullable: true), + LogoUri = table.Column(maxLength: 2000, nullable: true), + RequireConsent = table.Column(nullable: false), + AllowRememberConsent = table.Column(nullable: false), + AlwaysIncludeUserClaimsInIdToken = table.Column(nullable: false), + RequirePkce = table.Column(nullable: false), + AllowPlainTextPkce = table.Column(nullable: false), + AllowAccessTokensViaBrowser = table.Column(nullable: false), + FrontChannelLogoutUri = table.Column(maxLength: 2000, nullable: true), + FrontChannelLogoutSessionRequired = table.Column(nullable: false), + BackChannelLogoutUri = table.Column(maxLength: 2000, nullable: true), + BackChannelLogoutSessionRequired = table.Column(nullable: false), + AllowOfflineAccess = table.Column(nullable: false), + IdentityTokenLifetime = table.Column(nullable: false), + AccessTokenLifetime = table.Column(nullable: false), + AuthorizationCodeLifetime = table.Column(nullable: false), + ConsentLifetime = table.Column(nullable: true), + AbsoluteRefreshTokenLifetime = table.Column(nullable: false), + SlidingRefreshTokenLifetime = table.Column(nullable: false), + RefreshTokenUsage = table.Column(nullable: false), + UpdateAccessTokenClaimsOnRefresh = table.Column(nullable: false), + RefreshTokenExpiration = table.Column(nullable: false), + AccessTokenType = table.Column(nullable: false), + EnableLocalLogin = table.Column(nullable: false), + IncludeJwtId = table.Column(nullable: false), + AlwaysSendClientClaims = table.Column(nullable: false), + ClientClaimsPrefix = table.Column(maxLength: 200, nullable: true), + PairWiseSubjectSalt = table.Column(maxLength: 200, nullable: true), + Created = table.Column(nullable: false), + Updated = table.Column(nullable: true), + LastAccessed = table.Column(nullable: true), + UserSsoLifetime = table.Column(nullable: true), + UserCodeType = table.Column(maxLength: 100, nullable: true), + DeviceCodeLifetime = table.Column(nullable: false), + NonEditable = table.Column(nullable: false) }, constraints: table => { @@ -74,15 +85,18 @@ namespace Identity.API.Migrations.ConfigurationDb name: "IdentityResources", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - Description = table.Column(type: "nvarchar(1000)", maxLength: 1000, nullable: true), - DisplayName = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), - Emphasize = table.Column(type: "bit", nullable: false), - Enabled = table.Column(type: "bit", nullable: false), - Name = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), - Required = table.Column(type: "bit", nullable: false), - ShowInDiscoveryDocument = table.Column(type: "bit", nullable: false) + Enabled = table.Column(nullable: false), + Name = table.Column(maxLength: 200, nullable: false), + DisplayName = table.Column(maxLength: 200, nullable: true), + Description = table.Column(maxLength: 1000, nullable: true), + Required = table.Column(nullable: false), + Emphasize = table.Column(nullable: false), + ShowInDiscoveryDocument = table.Column(nullable: false), + Created = table.Column(nullable: false), + Updated = table.Column(nullable: true), + NonEditable = table.Column(nullable: false) }, constraints: table => { @@ -93,10 +107,10 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ApiClaims", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ApiResourceId = table.Column(type: "int", nullable: false), - Type = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false) + Type = table.Column(maxLength: 200, nullable: false), + ApiResourceId = table.Column(nullable: false) }, constraints: table => { @@ -109,19 +123,40 @@ namespace Identity.API.Migrations.ConfigurationDb onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateTable( + name: "ApiProperties", + columns: table => new + { + Id = table.Column(nullable: false) + .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), + Key = table.Column(maxLength: 250, nullable: false), + Value = table.Column(maxLength: 2000, nullable: false), + ApiResourceId = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiProperties", x => x.Id); + table.ForeignKey( + name: "FK_ApiProperties_ApiResources_ApiResourceId", + column: x => x.ApiResourceId, + principalTable: "ApiResources", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + migrationBuilder.CreateTable( name: "ApiScopes", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ApiResourceId = table.Column(type: "int", nullable: false), - Description = table.Column(type: "nvarchar(1000)", maxLength: 1000, nullable: true), - DisplayName = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), - Emphasize = table.Column(type: "bit", nullable: false), - Name = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), - Required = table.Column(type: "bit", nullable: false), - ShowInDiscoveryDocument = table.Column(type: "bit", nullable: false) + Name = table.Column(maxLength: 200, nullable: false), + DisplayName = table.Column(maxLength: 200, nullable: true), + Description = table.Column(maxLength: 1000, nullable: true), + Required = table.Column(nullable: false), + Emphasize = table.Column(nullable: false), + ShowInDiscoveryDocument = table.Column(nullable: false), + ApiResourceId = table.Column(nullable: false) }, constraints: table => { @@ -138,13 +173,14 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ApiSecrets", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ApiResourceId = table.Column(type: "int", nullable: false), - Description = table.Column(type: "nvarchar(1000)", maxLength: 1000, nullable: true), - Expiration = table.Column(type: "datetime2", nullable: true), - Type = table.Column(type: "nvarchar(250)", maxLength: 250, nullable: true), - Value = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true) + Description = table.Column(maxLength: 1000, nullable: true), + Value = table.Column(maxLength: 4000, nullable: false), + Expiration = table.Column(nullable: true), + Type = table.Column(maxLength: 250, nullable: false), + Created = table.Column(nullable: false), + ApiResourceId = table.Column(nullable: false) }, constraints: table => { @@ -161,11 +197,11 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ClientClaims", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(type: "int", nullable: false), - Type = table.Column(type: "nvarchar(250)", maxLength: 250, nullable: false), - Value = table.Column(type: "nvarchar(250)", maxLength: 250, nullable: false) + Type = table.Column(maxLength: 250, nullable: false), + Value = table.Column(maxLength: 250, nullable: false), + ClientId = table.Column(nullable: false) }, constraints: table => { @@ -182,10 +218,10 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ClientCorsOrigins", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(type: "int", nullable: false), - Origin = table.Column(type: "nvarchar(150)", maxLength: 150, nullable: false) + Origin = table.Column(maxLength: 150, nullable: false), + ClientId = table.Column(nullable: false) }, constraints: table => { @@ -202,10 +238,10 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ClientGrantTypes", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(type: "int", nullable: false), - GrantType = table.Column(type: "nvarchar(250)", maxLength: 250, nullable: false) + GrantType = table.Column(maxLength: 250, nullable: false), + ClientId = table.Column(nullable: false) }, constraints: table => { @@ -222,10 +258,10 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ClientIdPRestrictions", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(type: "int", nullable: false), - Provider = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false) + Provider = table.Column(maxLength: 200, nullable: false), + ClientId = table.Column(nullable: false) }, constraints: table => { @@ -242,10 +278,10 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ClientPostLogoutRedirectUris", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(type: "int", nullable: false), - PostLogoutRedirectUri = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: false) + PostLogoutRedirectUri = table.Column(maxLength: 2000, nullable: false), + ClientId = table.Column(nullable: false) }, constraints: table => { @@ -262,11 +298,11 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ClientProperties", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(type: "int", nullable: false), - Key = table.Column(type: "nvarchar(250)", maxLength: 250, nullable: false), - Value = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: false) + Key = table.Column(maxLength: 250, nullable: false), + Value = table.Column(maxLength: 2000, nullable: false), + ClientId = table.Column(nullable: false) }, constraints: table => { @@ -283,10 +319,10 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ClientRedirectUris", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(type: "int", nullable: false), - RedirectUri = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: false) + RedirectUri = table.Column(maxLength: 2000, nullable: false), + ClientId = table.Column(nullable: false) }, constraints: table => { @@ -303,10 +339,10 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ClientScopes", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(type: "int", nullable: false), - Scope = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false) + Scope = table.Column(maxLength: 200, nullable: false), + ClientId = table.Column(nullable: false) }, constraints: table => { @@ -323,13 +359,14 @@ namespace Identity.API.Migrations.ConfigurationDb name: "ClientSecrets", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(type: "int", nullable: false), - Description = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true), - Expiration = table.Column(type: "datetime2", nullable: true), - Type = table.Column(type: "nvarchar(250)", maxLength: 250, nullable: true), - Value = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: false) + Description = table.Column(maxLength: 2000, nullable: true), + Value = table.Column(maxLength: 4000, nullable: false), + Expiration = table.Column(nullable: true), + Type = table.Column(maxLength: 250, nullable: false), + Created = table.Column(nullable: false), + ClientId = table.Column(nullable: false) }, constraints: table => { @@ -346,10 +383,10 @@ namespace Identity.API.Migrations.ConfigurationDb name: "IdentityClaims", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - IdentityResourceId = table.Column(type: "int", nullable: false), - Type = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false) + Type = table.Column(maxLength: 200, nullable: false), + IdentityResourceId = table.Column(nullable: false) }, constraints: table => { @@ -362,14 +399,35 @@ namespace Identity.API.Migrations.ConfigurationDb onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateTable( + name: "IdentityProperties", + columns: table => new + { + Id = table.Column(nullable: false) + .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), + Key = table.Column(maxLength: 250, nullable: false), + Value = table.Column(maxLength: 2000, nullable: false), + IdentityResourceId = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_IdentityProperties", x => x.Id); + table.ForeignKey( + name: "FK_IdentityProperties_IdentityResources_IdentityResourceId", + column: x => x.IdentityResourceId, + principalTable: "IdentityResources", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + migrationBuilder.CreateTable( name: "ApiScopeClaims", columns: table => new { - Id = table.Column(type: "int", nullable: false) + Id = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ApiScopeId = table.Column(type: "int", nullable: false), - Type = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false) + Type = table.Column(maxLength: 200, nullable: false), + ApiScopeId = table.Column(nullable: false) }, constraints: table => { @@ -387,6 +445,11 @@ namespace Identity.API.Migrations.ConfigurationDb table: "ApiClaims", column: "ApiResourceId"); + migrationBuilder.CreateIndex( + name: "IX_ApiProperties_ApiResourceId", + table: "ApiProperties", + column: "ApiResourceId"); + migrationBuilder.CreateIndex( name: "IX_ApiResources_Name", table: "ApiResources", @@ -470,6 +533,11 @@ namespace Identity.API.Migrations.ConfigurationDb table: "IdentityClaims", column: "IdentityResourceId"); + migrationBuilder.CreateIndex( + name: "IX_IdentityProperties_IdentityResourceId", + table: "IdentityProperties", + column: "IdentityResourceId"); + migrationBuilder.CreateIndex( name: "IX_IdentityResources_Name", table: "IdentityResources", @@ -482,6 +550,9 @@ namespace Identity.API.Migrations.ConfigurationDb migrationBuilder.DropTable( name: "ApiClaims"); + migrationBuilder.DropTable( + name: "ApiProperties"); + migrationBuilder.DropTable( name: "ApiScopeClaims"); @@ -518,6 +589,9 @@ namespace Identity.API.Migrations.ConfigurationDb migrationBuilder.DropTable( name: "IdentityClaims"); + migrationBuilder.DropTable( + name: "IdentityProperties"); + migrationBuilder.DropTable( name: "ApiScopes"); diff --git a/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20170927170423_Grants.cs b/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20170927170423_Grants.cs deleted file mode 100644 index 4017f8bf0..000000000 --- a/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20170927170423_Grants.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Microsoft.EntityFrameworkCore.Migrations; -using System; - -namespace Identity.API.Migrations.PersistedGrantDb -{ - public partial class Grants : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "PersistedGrants", - columns: table => new - { - Key = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), - ClientId = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), - CreationTime = table.Column(type: "datetime2", nullable: false), - Data = table.Column(type: "nvarchar(max)", maxLength: 50000, nullable: false), - Expiration = table.Column(type: "datetime2", nullable: true), - SubjectId = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), - Type = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_PersistedGrants", x => x.Key); - }); - - migrationBuilder.CreateIndex( - name: "IX_PersistedGrants_SubjectId_ClientId_Type", - table: "PersistedGrants", - columns: new[] { "SubjectId", "ClientId", "Type" }); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "PersistedGrants"); - } - } -} diff --git a/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20170927170423_Grants.Designer.cs b/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20190729092100_InitialPersistedGrantMigration.Designer.cs similarity index 54% rename from src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20170927170423_Grants.Designer.cs rename to src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20190729092100_InitialPersistedGrantMigration.Designer.cs index aaf24d10c..0518894dc 100644 --- a/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20170927170423_Grants.Designer.cs +++ b/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20190729092100_InitialPersistedGrantMigration.Designer.cs @@ -1,25 +1,59 @@ // +using System; using IdentityServer4.EntityFramework.DbContexts; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.Internal; -using System; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Identity.API.Migrations.PersistedGrantDb { [DbContext(typeof(PersistedGrantDbContext))] - [Migration("20170927170423_Grants")] - partial class Grants + [Migration("20190729092100_InitialPersistedGrantMigration")] + partial class InitialPersistedGrantMigration { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "2.0.0-rtm-26452") + .HasAnnotation("ProductVersion", "3.0.0-preview7.19362.6") + .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => + { + b.Property("UserCode") + .HasMaxLength(200); + + b.Property("ClientId") + .IsRequired() + .HasMaxLength(200); + + b.Property("CreationTime"); + + b.Property("Data") + .IsRequired() + .HasMaxLength(50000); + + b.Property("DeviceCode") + .IsRequired() + .HasMaxLength(200); + + b.Property("Expiration") + .IsRequired(); + + b.Property("SubjectId") + .HasMaxLength(200); + + b.HasKey("UserCode"); + + b.HasIndex("DeviceCode") + .IsUnique(); + + b.ToTable("DeviceCodes"); + }); + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => { b.Property("Key") diff --git a/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20190729092100_InitialPersistedGrantMigration.cs b/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20190729092100_InitialPersistedGrantMigration.cs new file mode 100644 index 000000000..076f12323 --- /dev/null +++ b/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/20190729092100_InitialPersistedGrantMigration.cs @@ -0,0 +1,65 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Identity.API.Migrations.PersistedGrantDb +{ + public partial class InitialPersistedGrantMigration : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "DeviceCodes", + columns: table => new + { + UserCode = table.Column(maxLength: 200, nullable: false), + DeviceCode = table.Column(maxLength: 200, nullable: false), + SubjectId = table.Column(maxLength: 200, nullable: true), + ClientId = table.Column(maxLength: 200, nullable: false), + CreationTime = table.Column(nullable: false), + Expiration = table.Column(nullable: false), + Data = table.Column(maxLength: 50000, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceCodes", x => x.UserCode); + }); + + migrationBuilder.CreateTable( + name: "PersistedGrants", + columns: table => new + { + Key = table.Column(maxLength: 200, nullable: false), + Type = table.Column(maxLength: 50, nullable: false), + SubjectId = table.Column(maxLength: 200, nullable: true), + ClientId = table.Column(maxLength: 200, nullable: false), + CreationTime = table.Column(nullable: false), + Expiration = table.Column(nullable: true), + Data = table.Column(maxLength: 50000, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PersistedGrants", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_DeviceCodes_DeviceCode", + table: "DeviceCodes", + column: "DeviceCode", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PersistedGrants_SubjectId_ClientId_Type", + table: "PersistedGrants", + columns: new[] { "SubjectId", "ClientId", "Type" }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "DeviceCodes"); + + migrationBuilder.DropTable( + name: "PersistedGrants"); + } + } +} diff --git a/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/PersistedGrantDbContextModelSnapshot.cs b/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/PersistedGrantDbContextModelSnapshot.cs index 7989f0586..3188904ef 100644 --- a/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/PersistedGrantDbContextModelSnapshot.cs +++ b/src/Services/Identity/Identity.API/Migrations/PersistedGrantDb/PersistedGrantDbContextModelSnapshot.cs @@ -1,11 +1,10 @@ // +using System; using IdentityServer4.EntityFramework.DbContexts; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.Internal; -using System; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Identity.API.Migrations.PersistedGrantDb { @@ -16,9 +15,43 @@ namespace Identity.API.Migrations.PersistedGrantDb { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "2.0.0-rtm-26452") + .HasAnnotation("ProductVersion", "3.0.0-preview7.19362.6") + .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => + { + b.Property("UserCode") + .HasMaxLength(200); + + b.Property("ClientId") + .IsRequired() + .HasMaxLength(200); + + b.Property("CreationTime"); + + b.Property("Data") + .IsRequired() + .HasMaxLength(50000); + + b.Property("DeviceCode") + .IsRequired() + .HasMaxLength(200); + + b.Property("Expiration") + .IsRequired(); + + b.Property("SubjectId") + .HasMaxLength(200); + + b.HasKey("UserCode"); + + b.HasIndex("DeviceCode") + .IsUnique(); + + b.ToTable("DeviceCodes"); + }); + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => { b.Property("Key") diff --git a/src/Services/Location/Locations.API/Startup.cs b/src/Services/Location/Locations.API/Startup.cs index ff7c79416..0a4e09b4e 100644 --- a/src/Services/Location/Locations.API/Startup.cs +++ b/src/Services/Location/Locations.API/Startup.cs @@ -169,7 +169,6 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API ConfigureAuth(app); - app.UseAuthorization(); app.UseRouting(); app.UseEndpoints(endpoints => { @@ -230,6 +229,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API } app.UseAuthentication(); + app.UseAuthorization(); } private void RegisterEventBus(IServiceCollection services) diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index 5fc3c60d3..c3ae02e23 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -50,7 +50,7 @@ // Add framework services. services.AddCustomHealthCheck(Configuration); - services.AddControllers(); + services.AddControllers().AddNewtonsoftJson(); services.Configure(Configuration); ConfigureAuthService(services); @@ -122,7 +122,7 @@ options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new OpenApiInfo { - Title = "Marketing HTTP API", + Title = "eShopOnContainers - Marketing HTTP API", Version = "v1", Description = "The Marketing Service HTTP API" }); @@ -189,7 +189,6 @@ ConfigureAuth(app); - app.UseAuthorization(); app.UseRouting(); app.UseEndpoints(endpoints => { @@ -207,11 +206,11 @@ }); app.UseSwagger() - .UseSwaggerUI(c => + .UseSwaggerUI(setup => { - c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Marketing.API V1"); - c.OAuthClientId("marketingswaggerui"); - c.OAuthAppName("Marketing Swagger UI"); + setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Marketing.API V1"); + setup.OAuthClientId("marketingswaggerui"); + setup.OAuthAppName("Marketing Swagger UI"); }); ConfigureEventBus(app); @@ -234,11 +233,11 @@ options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => - { - options.Authority = Configuration.GetValue("IdentityUrl"); - options.Audience = "marketing"; - options.RequireHttpsMetadata = false; - }); + { + options.Authority = Configuration.GetValue("IdentityUrl"); + options.Audience = "marketing"; + options.RequireHttpsMetadata = false; + }); } private void RegisterEventBus(IServiceCollection services) @@ -295,6 +294,7 @@ } app.UseAuthentication(); + app.UseAuthorization(); } } diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index 7dfbcc45c..e8640489c 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -83,7 +83,6 @@ ConfigureAuth(app); - app.UseAuthorization(); app.UseRouting(); app.UseEndpoints(endpoints => { @@ -132,6 +131,7 @@ } app.UseAuthentication(); + app.UseAuthorization(); } } @@ -242,14 +242,14 @@ options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new OpenApiInfo { - Title = "Ordering HTTP API", + Title = "eShopOnContainers - Ordering HTTP API", Version = "v1", Description = "The Ordering Service HTTP API" }); options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, - Flows = new OpenApi.Models.OpenApiOAuthFlows() + Flows = new OpenApiOAuthFlows() { Implicit = new OpenApiOAuthFlow() { diff --git a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs index 78f10adb3..456e73397 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs @@ -135,7 +135,6 @@ namespace Ordering.SignalrHub } app.UseCors("CorsPolicy"); - app.UseAuthentication(); app.UseRouting(); app.UseEndpoints(endpoints => { diff --git a/src/Services/Webhooks/Webhooks.API/Startup.cs b/src/Services/Webhooks/Webhooks.API/Startup.cs index 4d3bd2c81..5859e9e12 100644 --- a/src/Services/Webhooks/Webhooks.API/Startup.cs +++ b/src/Services/Webhooks/Webhooks.API/Startup.cs @@ -82,7 +82,6 @@ namespace Webhooks.API ConfigureAuth(app); - app.UseAuthorization(); app.UseRouting(); app.UseEndpoints(endpoints => { From 4d8f3cba65886beb24370e25a5e98cdcef2faf90 Mon Sep 17 00:00:00 2001 From: ericuss Date: Mon, 29 Jul 2019 14:05:17 +0200 Subject: [PATCH 031/113] partial checkin --- .../Locations.API/Model/Core/LocationPoint.cs | 24 +++ .../Model/Core/LocationPolygon.cs | 25 +++ .../Location/Locations.API/Model/Locations.cs | 13 +- .../Location/Locations.API/Startup.cs | 6 +- .../Locations.FunctionalTests.csproj | 5 +- .../LocationsScenarios.cs | 155 +++++++++--------- src/_build/dependencies.props | 10 +- 7 files changed, 145 insertions(+), 93 deletions(-) create mode 100644 src/Services/Location/Locations.API/Model/Core/LocationPoint.cs create mode 100644 src/Services/Location/Locations.API/Model/Core/LocationPolygon.cs diff --git a/src/Services/Location/Locations.API/Model/Core/LocationPoint.cs b/src/Services/Location/Locations.API/Model/Core/LocationPoint.cs new file mode 100644 index 000000000..48b6e32a7 --- /dev/null +++ b/src/Services/Location/Locations.API/Model/Core/LocationPoint.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Locations.API.Model.Core +{ + public class LocationPoint + { + public LocationPoint() + { + } + + public LocationPoint(double longitude, double latitude) + { + this.coordinates.Add(longitude); + this.coordinates.Add(latitude); + } + + public string type { get; private set; } = "Point"; + + public List coordinates { get; private set; } = new List(); + } +} diff --git a/src/Services/Location/Locations.API/Model/Core/LocationPolygon.cs b/src/Services/Location/Locations.API/Model/Core/LocationPolygon.cs new file mode 100644 index 000000000..18380cc79 --- /dev/null +++ b/src/Services/Location/Locations.API/Model/Core/LocationPolygon.cs @@ -0,0 +1,25 @@ +using MongoDB.Driver.GeoJsonObjectModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Locations.API.Model.Core +{ + public class LocationPolygon + { + public LocationPolygon() + { + } + + public LocationPolygon(List coordinatesList) + { + var coordinatesMapped = coordinatesList.Select(x => new List() { x.Longitude, x.Latitude }).ToList(); + this.coordinates.Add(coordinatesMapped); + } + + public string type { get; private set; } = "Polygon"; + + public List>> coordinates { get; private set; } = new List>>(); + } +} diff --git a/src/Services/Location/Locations.API/Model/Locations.cs b/src/Services/Location/Locations.API/Model/Locations.cs index 7c0580fc6..ae6672345 100644 --- a/src/Services/Location/Locations.API/Model/Locations.cs +++ b/src/Services/Location/Locations.API/Model/Locations.cs @@ -1,5 +1,6 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API.Model { + using global::Locations.API.Model.Core; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver.GeoJsonObjectModel; @@ -17,8 +18,10 @@ public string Description { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } - public GeoJsonPoint Location { get; private set; } - public GeoJsonPolygon Polygon { get; private set; } + //public GeoJsonPoint Location { get; private set; } + public LocationPoint Location { get; private set; } + public LocationPolygon Polygon { get; private set; } + //public GeoJsonPolygon Polygon { get; private set; } public void SetLocation(double lon, double lat) => SetPosition(lon, lat); public void SetArea(List coordinatesList) => SetPolygon(coordinatesList); @@ -26,14 +29,12 @@ { Latitude = lat; Longitude = lon; - Location = new GeoJsonPoint( - new GeoJson2DGeographicCoordinates(lon, lat)); + Location = new LocationPoint(lon, lat); } private void SetPolygon(List coordinatesList) { - Polygon = new GeoJsonPolygon(new GeoJsonPolygonCoordinates( - new GeoJsonLinearRingCoordinates(coordinatesList))); + Polygon = new LocationPolygon(coordinatesList); } } } diff --git a/src/Services/Location/Locations.API/Startup.cs b/src/Services/Location/Locations.API/Startup.cs index ff7c79416..3620da209 100644 --- a/src/Services/Location/Locations.API/Startup.cs +++ b/src/Services/Location/Locations.API/Startup.cs @@ -154,7 +154,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { //loggerFactory.AddAzureWebAppDiagnostics(); //loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); @@ -167,10 +167,9 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API app.UseCors("CorsPolicy"); + app.UseRouting(); ConfigureAuth(app); - app.UseAuthorization(); - app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); @@ -230,6 +229,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API } app.UseAuthentication(); + app.UseAuthorization(); } private void RegisterEventBus(IServiceCollection services) diff --git a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj index dd1432b48..788f44ede 100644 --- a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj +++ b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj @@ -17,8 +17,7 @@ - - + @@ -26,7 +25,7 @@ all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Location/Locations.FunctionalTests/LocationsScenarios.cs b/src/Services/Location/Locations.FunctionalTests/LocationsScenarios.cs index d08f777fd..6e625a257 100644 --- a/src/Services/Location/Locations.FunctionalTests/LocationsScenarios.cs +++ b/src/Services/Location/Locations.FunctionalTests/LocationsScenarios.cs @@ -12,37 +12,37 @@ namespace Locations.FunctionalTests public class LocationsScenarios : LocationsScenarioBase { - [Fact] - public async Task Set_new_user_seattle_location_response_ok_status_code() - { - using (var server = CreateServer()) - { - var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed"; - var content = new StringContent(BuildLocationsRequest(-122.315752, 47.604610), UTF8Encoding.UTF8, "application/json"); + //[Fact] + //public async Task Set_new_user_seattle_location_response_ok_status_code() + //{ + // using (var server = CreateServer()) + // { + // var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed"; + // var content = new StringContent(BuildLocationsRequest(-122.315752, 47.604610), UTF8Encoding.UTF8, "application/json"); - // Expected result - var expectedLocation = "SEAT"; + // // Expected result + // var expectedLocation = "SEAT"; - // Act - var response = await server.CreateClient() - .PostAsync(Post.AddNewLocation, content); + // // Act + // var response = await server.CreateClient() + // .PostAsync(Post.AddNewLocation, content); - var userLocationResponse = await server.CreateClient() - .GetAsync(Get.UserLocationBy(userId)); + // var userLocationResponse = await server.CreateClient() + // .GetAsync(Get.UserLocationBy(userId)); - var responseBody = await userLocationResponse.Content.ReadAsStringAsync(); - var userLocation = JsonConvert.DeserializeObject(responseBody); + // var responseBody = await userLocationResponse.Content.ReadAsStringAsync(); + // var userLocation = JsonConvert.DeserializeObject(responseBody); - var locationResponse = await server.CreateClient() - .GetAsync(Get.LocationBy(userLocation.LocationId)); + // var locationResponse = await server.CreateClient() + // .GetAsync(Get.LocationBy(userLocation.LocationId)); - responseBody = await locationResponse.Content.ReadAsStringAsync(); - var location = JsonConvert.DeserializeObject(responseBody); + // responseBody = await locationResponse.Content.ReadAsStringAsync(); + // var location = JsonConvert.DeserializeObject(responseBody); - // Assert - Assert.Equal(expectedLocation, location.Code); - } - } + // // Assert + // Assert.Equal(expectedLocation, location.Code); + // } + //} [Fact] public async Task Set_new_user_readmond_location_response_ok_status_code() @@ -52,53 +52,24 @@ namespace Locations.FunctionalTests var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed"; var content = new StringContent(BuildLocationsRequest(-122.119998, 47.690876), UTF8Encoding.UTF8, "application/json"); + var client = server.CreateClient(); + // Expected result var expectedLocation = "REDM"; // Act - var response = await server.CreateClient() - .PostAsync(Post.AddNewLocation, content); - - var userLocationResponse = await server.CreateClient() - .GetAsync(Get.UserLocationBy(userId)); - - var responseBody = await userLocationResponse.Content.ReadAsStringAsync(); - var userLocation = JsonConvert.DeserializeObject(responseBody); - - var locationResponse = await server.CreateClient() - .GetAsync(Get.LocationBy(userLocation.LocationId)); - - responseBody = await locationResponse.Content.ReadAsStringAsync(); - var location = JsonConvert.DeserializeObject(responseBody); - // Assert - Assert.Equal(expectedLocation, location.Code); - } - } - - [Fact] - public async Task Set_new_user_Washington_location_response_ok_status_code() - { - using (var server = CreateServer()) - { - var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed"; - var content = new StringContent(BuildLocationsRequest(-121.040360, 48.091631), UTF8Encoding.UTF8, "application/json"); - - // Expected result - var expectedLocation = "WHT"; + var response = await client.PostAsync(Post.AddNewLocation, content); - // Act - var response = await server.CreateClient() - .PostAsync(Post.AddNewLocation, content); - - var userLocationResponse = await server.CreateClient() - .GetAsync(Get.UserLocationBy(userId)); + var userLocationResponse = await client.GetAsync(Get.UserLocationBy(userId)); + userLocationResponse.EnsureSuccessStatusCode(); var responseBody = await userLocationResponse.Content.ReadAsStringAsync(); var userLocation = JsonConvert.DeserializeObject(responseBody); - var locationResponse = await server.CreateClient() - .GetAsync(Get.LocationBy(userLocation.LocationId)); + Assert.NotNull(userLocation); + + var locationResponse = await client.GetAsync(Get.LocationBy(userLocation.LocationId)); responseBody = await locationResponse.Content.ReadAsStringAsync(); var location = JsonConvert.DeserializeObject(responseBody); @@ -108,21 +79,53 @@ namespace Locations.FunctionalTests } } - [Fact] - public async Task Get_all_locations_response_ok_status_code() - { - using (var server = CreateServer()) - { - var response = await server.CreateClient() - .GetAsync(Get.Locations); - - var responseBody = await response.Content.ReadAsStringAsync(); - var locations = JsonConvert.DeserializeObject>(responseBody); - - // Assert - Assert.NotEmpty(locations); - } - } + //[Fact] + //public async Task Set_new_user_Washington_location_response_ok_status_code() + //{ + // using (var server = CreateServer()) + // { + // var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed"; + // var content = new StringContent(BuildLocationsRequest(-121.040360, 48.091631), UTF8Encoding.UTF8, "application/json"); + + // // Expected result + // var expectedLocation = "WHT"; + + // // Act + // var response = await server.CreateClient() + // .PostAsync(Post.AddNewLocation, content); + + // var userLocationResponse = await server.CreateClient() + // .GetAsync(Get.UserLocationBy(userId)); + + // var responseBody = await userLocationResponse.Content.ReadAsStringAsync(); + // var userLocation = JsonConvert.DeserializeObject(responseBody); + + // var locationResponse = await server.CreateClient() + // .GetAsync(Get.LocationBy(userLocation.LocationId)); + + // responseBody = await locationResponse.Content.ReadAsStringAsync(); + // var location = JsonConvert.DeserializeObject(responseBody); + + // // Assert + // Assert.Equal(expectedLocation, location.Code); + // } + //} + + //[Fact] + //public async Task Get_all_locations_response_ok_status_code() + //{ + // using (var server = CreateServer()) + // { + // var response = await server.CreateClient() + // .GetAsync(Get.Locations); + + // var responseBody = await response.Content.ReadAsStringAsync(); + // var locations = JsonConvert.DeserializeObject>(responseBody); + + // // Assert + // Assert.NotEmpty(locations); + // } + //} string BuildLocationsRequest(double lon, double lat) { diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 18f81d6b3..7f81abf62 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -56,7 +56,7 @@ 1.0.0 2.2.0 3.0.0-preview6.19307.2 - 3.0.0-preview6.19307.2 + 3.0.0-preview7.19365.7 3.0.0-preview7.19365.7 3.0.0-preview7.19365.7 3.0.0-preview4-19123-01 @@ -80,10 +80,10 @@ 2.2.0 3.0.0-preview7.19362.4 16.0.1 - 2.5.0 - 2.5.0 - 2.5.0 - 2.5.0 + 2.9.0-beta2 + 2.9.0-beta2 + 2.9.0-beta2 + 2.9.0-beta2 4.10.1 12.0.2 12.0.1 From c94304f26eafe74efc42152b74fd380967f5a54a Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Mon, 29 Jul 2019 14:44:32 +0200 Subject: [PATCH 032/113] #74197 Order Background Service to Service Worker --- eShopOnContainers-ServicesAndWebApps.sln | 51 ----------- .../Tasks/GracePeriodManagerTask.cs | 90 +++++++++++++++++++ .../Ordering/Ordering.API/OrderingSettings.cs | 3 + src/Services/Ordering/Ordering.API/Program.cs | 4 +- .../Ordering/Ordering.API/appsettings.json | 1 + 5 files changed, 97 insertions(+), 52 deletions(-) create mode 100644 src/Services/Ordering/Ordering.API/Infrastructure/Tasks/GracePeriodManagerTask.cs diff --git a/eShopOnContainers-ServicesAndWebApps.sln b/eShopOnContainers-ServicesAndWebApps.sln index 4bf2fa51d..75cf60bae 100644 --- a/eShopOnContainers-ServicesAndWebApps.sln +++ b/eShopOnContainers-ServicesAndWebApps.sln @@ -102,8 +102,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mobile.Shopping.HttpAggrega EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Web.Shopping.HttpAggregator", "src\ApiGateways\Web.Bff.Shopping\aggregator\Web.Shopping.HttpAggregator.csproj", "{AF0828DB-8BDD-411A-AEEF-B780FBB8D8C1}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.BackgroundTasks", "src\Services\Ordering\Ordering.BackgroundTasks\Ordering.BackgroundTasks.csproj", "{7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.SignalrHub", "src\Services\Ordering\Ordering.SignalrHub\Ordering.SignalrHub.csproj", "{E1D2B260-4E7F-4A88-BC13-9910F7C44623}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basket.UnitTests", "src\Services\Basket\Basket.UnitTests\Basket.UnitTests.csproj", "{9D9CE4E4-1DD0-4961-861F-219731DE06CE}" @@ -1041,54 +1039,6 @@ Global {AF0828DB-8BDD-411A-AEEF-B780FBB8D8C1}.Release|x64.Build.0 = Release|Any CPU {AF0828DB-8BDD-411A-AEEF-B780FBB8D8C1}.Release|x86.ActiveCfg = Release|Any CPU {AF0828DB-8BDD-411A-AEEF-B780FBB8D8C1}.Release|x86.Build.0 = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|ARM.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|ARM.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|iPhone.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|iPhoneSimulator.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|x64.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|x64.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|x86.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Ad-Hoc|x86.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|Any CPU.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|Any CPU.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|ARM.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|ARM.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|iPhone.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|iPhone.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|iPhoneSimulator.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|iPhoneSimulator.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|x64.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|x64.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|x86.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.AppStore|x86.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|ARM.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|ARM.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|iPhone.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|iPhone.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|x64.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|x64.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|x86.ActiveCfg = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Debug|x86.Build.0 = Debug|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|Any CPU.Build.0 = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|ARM.ActiveCfg = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|ARM.Build.0 = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|iPhone.ActiveCfg = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|iPhone.Build.0 = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|iPhoneSimulator.Build.0 = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|x64.ActiveCfg = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|x64.Build.0 = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|x86.ActiveCfg = Release|Any CPU - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931}.Release|x86.Build.0 = Release|Any CPU {E1D2B260-4E7F-4A88-BC13-9910F7C44623}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU {E1D2B260-4E7F-4A88-BC13-9910F7C44623}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU {E1D2B260-4E7F-4A88-BC13-9910F7C44623}.Ad-Hoc|ARM.ActiveCfg = Debug|Any CPU @@ -1851,7 +1801,6 @@ Global {3F79558C-485D-49E1-BD3E-E12538D3D308} = {EC91ADE9-3D66-4AB2-9FB4-2B585E1F3531} {BEA37D6D-4CF2-4AE8-9575-72388E54FBD0} = {0189E4FB-6E2B-4F2E-9B1D-5473D23FC6DB} {AF0828DB-8BDD-411A-AEEF-B780FBB8D8C1} = {28C0F5C8-4849-4035-80AB-45639424E73F} - {7D63ED4A-3EDA-4BBA-8BBA-F46BD6430931} = {0BD0DB92-2D98-44D9-9AC0-C59186D59B0B} {E1D2B260-4E7F-4A88-BC13-9910F7C44623} = {0BD0DB92-2D98-44D9-9AC0-C59186D59B0B} {9D9CE4E4-1DD0-4961-861F-219731DE06CE} = {2751AC5C-D148-4D7A-AE8F-149B47C9A82D} {791961C7-3F3E-434E-B2BA-B4D6B5E222B0} = {5FB21302-3973-4992-962A-6F87F5EC99FD} diff --git a/src/Services/Ordering/Ordering.API/Infrastructure/Tasks/GracePeriodManagerTask.cs b/src/Services/Ordering/Ordering.API/Infrastructure/Tasks/GracePeriodManagerTask.cs new file mode 100644 index 000000000..740d1aa30 --- /dev/null +++ b/src/Services/Ordering/Ordering.API/Infrastructure/Tasks/GracePeriodManagerTask.cs @@ -0,0 +1,90 @@ +using Dapper; +using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; +using Microsoft.eShopOnContainers.Services.Ordering.API; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Ordering.API.Application.IntegrationEvents.Events; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Threading; +using System.Threading.Tasks; + +namespace Ordering.API.Infrastructure.Tasks +{ + public class GracePeriodManagerService : BackgroundService + { + private readonly ILogger _logger; + private readonly OrderingSettings _settings; + private readonly IEventBus _eventBus; + + public GracePeriodManagerService(IOptions settings, IEventBus eventBus, ILogger logger) + { + _settings = settings?.Value ?? throw new ArgumentNullException(nameof(settings)); + _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + _logger.LogDebug("GracePeriodManagerService is starting."); + + stoppingToken.Register(() => _logger.LogDebug("#1 GracePeriodManagerService background task is stopping.")); + + while (!stoppingToken.IsCancellationRequested) + { + _logger.LogDebug("GracePeriodManagerService background task is doing background work."); + + CheckConfirmedGracePeriodOrders(); + + await Task.Delay(_settings.CheckUpdateTime, stoppingToken); + } + + _logger.LogDebug("GracePeriodManagerService background task is stopping."); + + await Task.CompletedTask; + } + + private void CheckConfirmedGracePeriodOrders() + { + _logger.LogDebug("Checking confirmed grace period orders"); + + var orderIds = GetConfirmedGracePeriodOrders(); + + foreach (var orderId in orderIds) + { + var confirmGracePeriodEvent = new GracePeriodConfirmedIntegrationEvent(orderId); + + _logger.LogInformation("----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", confirmGracePeriodEvent.Id, Program.AppName, confirmGracePeriodEvent); + + _eventBus.Publish(confirmGracePeriodEvent); + } + } + + private IEnumerable GetConfirmedGracePeriodOrders() + { + IEnumerable orderIds = new List(); + + using (var conn = new SqlConnection(_settings.ConnectionString)) + { + try + { + conn.Open(); + orderIds = conn.Query( + @"SELECT Id FROM [ordering].[orders] + WHERE DATEDIFF(minute, [OrderDate], GETDATE()) >= @GracePeriodTime + AND [OrderStatusId] = 1", + new { _settings.GracePeriodTime }); + } + catch (SqlException exception) + { + _logger.LogCritical(exception, "FATAL ERROR: Database connections could not be opened: {Message}", exception.Message); + } + + } + + return orderIds; + } + } +} diff --git a/src/Services/Ordering/Ordering.API/OrderingSettings.cs b/src/Services/Ordering/Ordering.API/OrderingSettings.cs index af38823ae..7459bfd1c 100644 --- a/src/Services/Ordering/Ordering.API/OrderingSettings.cs +++ b/src/Services/Ordering/Ordering.API/OrderingSettings.cs @@ -3,10 +3,13 @@ public class OrderingSettings { public bool UseCustomizationData { get; set; } + public string ConnectionString { get; set; } public string EventBusConnection { get; set; } + public int GracePeriodTime { get; set; } + public int CheckUpdateTime { get; set; } } } diff --git a/src/Services/Ordering/Ordering.API/Program.cs b/src/Services/Ordering/Ordering.API/Program.cs index a0b7dc40e..251a9cbf5 100644 --- a/src/Services/Ordering/Ordering.API/Program.cs +++ b/src/Services/Ordering/Ordering.API/Program.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Ordering.API.Infrastructure.Tasks; using Serilog; using System; using System.IO; @@ -62,13 +63,14 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API WebHost.CreateDefaultBuilder(args) .CaptureStartupErrors(false) .UseStartup() + .ConfigureServices(service => service.AddHostedService()) .UseApplicationInsights() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(configuration) .UseSerilog() .Build(); - private static Serilog.ILogger CreateSerilogLogger(IConfiguration configuration) + private static Serilog.ILogger CreateSerilogLogger(IConfiguration configuration) { var seqServerUrl = configuration["Serilog:SeqServerUrl"]; var logstashUrl = configuration["Serilog:LogstashgUrl"]; diff --git a/src/Services/Ordering/Ordering.API/appsettings.json b/src/Services/Ordering/Ordering.API/appsettings.json index f74c312b1..4ef8f6ac4 100644 --- a/src/Services/Ordering/Ordering.API/appsettings.json +++ b/src/Services/Ordering/Ordering.API/appsettings.json @@ -16,6 +16,7 @@ }, "AzureServiceBusEnabled": false, "SubscriptionClientName": "Ordering", + "GracePeriodTime": "1", "CheckUpdateTime": "30000", "ApplicationInsights": { "InstrumentationKey": "" From de36e8c09e0f7d9d90a3d56f4d1fb0d81aeefe41 Mon Sep 17 00:00:00 2001 From: ericuss Date: Tue, 30 Jul 2019 10:56:14 +0200 Subject: [PATCH 033/113] Migrate locations.functionaltest to 3.0 --- .../Location/Locations.API/Model/Locations.cs | 6 +- .../Location/Locations.API/Startup.cs | 12 +- .../LocationTestsStartup.cs | 13 +- .../Locations.FunctionalTests.csproj | 2 +- .../LocationsScenarios.cs | 142 +++++++++--------- .../appsettings.json | 3 +- 6 files changed, 97 insertions(+), 81 deletions(-) diff --git a/src/Services/Location/Locations.API/Model/Locations.cs b/src/Services/Location/Locations.API/Model/Locations.cs index ae6672345..ba3dbe62c 100644 --- a/src/Services/Location/Locations.API/Model/Locations.cs +++ b/src/Services/Location/Locations.API/Model/Locations.cs @@ -18,10 +18,12 @@ public string Description { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } - //public GeoJsonPoint Location { get; private set; } public LocationPoint Location { get; private set; } public LocationPolygon Polygon { get; private set; } - //public GeoJsonPolygon Polygon { get; private set; } + + // Temporal commented in previewVersion7 of netcore and 2.9.0-beta2 of Mongo packages, review in next versions + // public GeoJsonPoint Location { get; private set; } + // public GeoJsonPolygon Polygon { get; private set; } public void SetLocation(double lon, double lat) => SetPosition(lon, lat); public void SetArea(List coordinatesList) => SetPolygon(coordinatesList); diff --git a/src/Services/Location/Locations.API/Startup.cs b/src/Services/Location/Locations.API/Startup.cs index 3620da209..5deaae52d 100644 --- a/src/Services/Location/Locations.API/Startup.cs +++ b/src/Services/Location/Locations.API/Startup.cs @@ -1,6 +1,7 @@ using Autofac; using Autofac.Extensions.DependencyInjection; using HealthChecks.UI.Client; +using Locations.API.Controllers; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; @@ -37,17 +38,18 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API public IConfiguration Configuration { get; } - public IServiceProvider ConfigureServices(IServiceCollection services) + public virtual IServiceProvider ConfigureServices(IServiceCollection services) { RegisterAppInsights(services); services.AddCustomHealthCheck(Configuration); services.AddControllers(options => - { - options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - - }).AddNewtonsoftJson(); + { + options.Filters.Add(typeof(HttpGlobalExceptionFilter)); + }) + .AddApplicationPart(typeof(LocationsController).Assembly) + .AddNewtonsoftJson(); ConfigureAuthService(services); diff --git a/src/Services/Location/Locations.FunctionalTests/LocationTestsStartup.cs b/src/Services/Location/Locations.FunctionalTests/LocationTestsStartup.cs index 21d0814a0..08bf2ffa5 100644 --- a/src/Services/Location/Locations.FunctionalTests/LocationTestsStartup.cs +++ b/src/Services/Location/Locations.FunctionalTests/LocationTestsStartup.cs @@ -1,7 +1,11 @@ -using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; using Microsoft.eShopOnContainers.Services.Locations.API; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; using System.Security.Claims; using System.Threading.Tasks; @@ -13,6 +17,13 @@ namespace Locations.FunctionalTests { } + public override IServiceProvider ConfigureServices(IServiceCollection services) + { + // Added to avoid the Authorize data annotation in test environment. + // Property "SuppressCheckForUnhandledSecurityMetadata" in appsettings.json + services.Configure(Configuration); + return base.ConfigureServices(services); + } protected override void ConfigureAuth(IApplicationBuilder app) { if (Configuration["isTest"] == bool.TrueString.ToLowerInvariant()) diff --git a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj index 788f44ede..8b60d0001 100644 --- a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj +++ b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj @@ -2,7 +2,7 @@ $(NetCoreTargetVersion) - + false false diff --git a/src/Services/Location/Locations.FunctionalTests/LocationsScenarios.cs b/src/Services/Location/Locations.FunctionalTests/LocationsScenarios.cs index 6e625a257..5f8c90dfd 100644 --- a/src/Services/Location/Locations.FunctionalTests/LocationsScenarios.cs +++ b/src/Services/Location/Locations.FunctionalTests/LocationsScenarios.cs @@ -12,37 +12,37 @@ namespace Locations.FunctionalTests public class LocationsScenarios : LocationsScenarioBase { - //[Fact] - //public async Task Set_new_user_seattle_location_response_ok_status_code() - //{ - // using (var server = CreateServer()) - // { - // var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed"; - // var content = new StringContent(BuildLocationsRequest(-122.315752, 47.604610), UTF8Encoding.UTF8, "application/json"); + [Fact] + public async Task Set_new_user_seattle_location_response_ok_status_code() + { + using (var server = CreateServer()) + { + var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed"; + var content = new StringContent(BuildLocationsRequest(-122.315752, 47.604610), UTF8Encoding.UTF8, "application/json"); - // // Expected result - // var expectedLocation = "SEAT"; + // Expected result + var expectedLocation = "SEAT"; - // // Act - // var response = await server.CreateClient() - // .PostAsync(Post.AddNewLocation, content); + // Act + var response = await server.CreateClient() + .PostAsync(Post.AddNewLocation, content); - // var userLocationResponse = await server.CreateClient() - // .GetAsync(Get.UserLocationBy(userId)); + var userLocationResponse = await server.CreateClient() + .GetAsync(Get.UserLocationBy(userId)); - // var responseBody = await userLocationResponse.Content.ReadAsStringAsync(); - // var userLocation = JsonConvert.DeserializeObject(responseBody); + var responseBody = await userLocationResponse.Content.ReadAsStringAsync(); + var userLocation = JsonConvert.DeserializeObject(responseBody); - // var locationResponse = await server.CreateClient() - // .GetAsync(Get.LocationBy(userLocation.LocationId)); + var locationResponse = await server.CreateClient() + .GetAsync(Get.LocationBy(userLocation.LocationId)); - // responseBody = await locationResponse.Content.ReadAsStringAsync(); - // var location = JsonConvert.DeserializeObject(responseBody); + responseBody = await locationResponse.Content.ReadAsStringAsync(); + var location = JsonConvert.DeserializeObject(responseBody); - // // Assert - // Assert.Equal(expectedLocation, location.Code); - // } - //} + // Assert + Assert.Equal(expectedLocation, location.Code); + } + } [Fact] public async Task Set_new_user_readmond_location_response_ok_status_code() @@ -79,53 +79,53 @@ namespace Locations.FunctionalTests } } - //[Fact] - //public async Task Set_new_user_Washington_location_response_ok_status_code() - //{ - // using (var server = CreateServer()) - // { - // var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed"; - // var content = new StringContent(BuildLocationsRequest(-121.040360, 48.091631), UTF8Encoding.UTF8, "application/json"); - - // // Expected result - // var expectedLocation = "WHT"; - - // // Act - // var response = await server.CreateClient() - // .PostAsync(Post.AddNewLocation, content); - - // var userLocationResponse = await server.CreateClient() - // .GetAsync(Get.UserLocationBy(userId)); - - // var responseBody = await userLocationResponse.Content.ReadAsStringAsync(); - // var userLocation = JsonConvert.DeserializeObject(responseBody); - - // var locationResponse = await server.CreateClient() - // .GetAsync(Get.LocationBy(userLocation.LocationId)); - - // responseBody = await locationResponse.Content.ReadAsStringAsync(); - // var location = JsonConvert.DeserializeObject(responseBody); - - // // Assert - // Assert.Equal(expectedLocation, location.Code); - // } - //} - - //[Fact] - //public async Task Get_all_locations_response_ok_status_code() - //{ - // using (var server = CreateServer()) - // { - // var response = await server.CreateClient() - // .GetAsync(Get.Locations); - - // var responseBody = await response.Content.ReadAsStringAsync(); - // var locations = JsonConvert.DeserializeObject>(responseBody); - - // // Assert - // Assert.NotEmpty(locations); - // } - //} + [Fact] + public async Task Set_new_user_Washington_location_response_ok_status_code() + { + using (var server = CreateServer()) + { + var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed"; + var content = new StringContent(BuildLocationsRequest(-121.040360, 48.091631), UTF8Encoding.UTF8, "application/json"); + + // Expected result + var expectedLocation = "WHT"; + + // Act + var response = await server.CreateClient() + .PostAsync(Post.AddNewLocation, content); + + var userLocationResponse = await server.CreateClient() + .GetAsync(Get.UserLocationBy(userId)); + + var responseBody = await userLocationResponse.Content.ReadAsStringAsync(); + var userLocation = JsonConvert.DeserializeObject(responseBody); + + var locationResponse = await server.CreateClient() + .GetAsync(Get.LocationBy(userLocation.LocationId)); + + responseBody = await locationResponse.Content.ReadAsStringAsync(); + var location = JsonConvert.DeserializeObject(responseBody); + + // Assert + Assert.Equal(expectedLocation, location.Code); + } + } + + [Fact] + public async Task Get_all_locations_response_ok_status_code() + { + using (var server = CreateServer()) + { + var response = await server.CreateClient() + .GetAsync(Get.Locations); + + var responseBody = await response.Content.ReadAsStringAsync(); + var locations = JsonConvert.DeserializeObject>(responseBody); + + // Assert + Assert.NotEmpty(locations); + } + } string BuildLocationsRequest(double lon, double lat) { diff --git a/src/Services/Location/Locations.FunctionalTests/appsettings.json b/src/Services/Location/Locations.FunctionalTests/appsettings.json index 398cd54c0..6880b2ee1 100644 --- a/src/Services/Location/Locations.FunctionalTests/appsettings.json +++ b/src/Services/Location/Locations.FunctionalTests/appsettings.json @@ -5,5 +5,6 @@ "IdentityUrl": "http://localhost:5105", "isTest": "true", "EventBusConnection": "localhost", - "SubscriptionClientName": "Locations" + "SubscriptionClientName": "Locations", + "SuppressCheckForUnhandledSecurityMetadata":true } From e1b21abe94d77c1ed91552f7674b57b044996f3c Mon Sep 17 00:00:00 2001 From: ericuss Date: Tue, 30 Jul 2019 11:14:16 +0200 Subject: [PATCH 034/113] Remove unused project --- .../Configuration/BackgroundTaskSettings.cs | 13 -- .../Ordering.BackgroundTasks/Dockerfile | 25 --- .../Dockerfile.develop | 18 -- .../GracePeriodConfirmedIntegrationEvent.cs | 12 -- .../Ordering.BackgroundTasks.csproj | 42 ---- .../Ordering.BackgroundTasks/Program.cs | 76 ------- .../Properties/launchSettings.json | 29 --- .../Ordering.BackgroundTasks/Startup.cs | 199 ------------------ .../Tasks/GracePeriodManagerTask.cs | 95 --------- .../appsettings.Development.json | 10 - .../Ordering.BackgroundTasks/appsettings.json | 26 --- .../Ordering.BackgroundTasks/azds.yaml | 56 ----- 12 files changed, 601 deletions(-) delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Configuration/BackgroundTaskSettings.cs delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile.develop delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/IntegrationEvents/GracePeriodConfirmedIntegrationEvent.cs delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Program.cs delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Properties/launchSettings.json delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/appsettings.Development.json delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/appsettings.json delete mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/azds.yaml diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Configuration/BackgroundTaskSettings.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Configuration/BackgroundTaskSettings.cs deleted file mode 100644 index 2b42f6084..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Configuration/BackgroundTaskSettings.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Ordering.BackgroundTasks.Configuration -{ - public class BackgroundTaskSettings - { - public string ConnectionString { get; set; } - - public string EventBusConnection { get; set; } - - public int GracePeriodTime { get; set; } - - public int CheckUpdateTime { get; set; } - } -} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile deleted file mode 100644 index 820f8d4b1..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile +++ /dev/null @@ -1,25 +0,0 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base -WORKDIR /app -EXPOSE 80 - -FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build -WORKDIR /src - -COPY scripts scripts/ - -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ - -COPY . . -WORKDIR /src/src/Services/Ordering/Ordering.BackgroundTasks -RUN dotnet publish -c Release -o /app - -FROM build AS publish - -FROM base AS final -WORKDIR /app -COPY --from=publish /app . -ENTRYPOINT ["dotnet", "Ordering.BackgroundTasks.dll"] \ No newline at end of file diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile.develop b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile.develop deleted file mode 100644 index 5f5d002db..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile.develop +++ /dev/null @@ -1,18 +0,0 @@ -FROM microsoft/dotnet:2.2-sdk -ARG BUILD_CONFIGURATION=Debug -ENV ASPNETCORE_ENVIRONMENT=Development -ENV DOTNET_USE_POLLING_FILE_WATCHER=true -EXPOSE 80 - -WORKDIR /src -COPY ["src/BuildingBlocks/EventBus/EventBus/EventBus.csproj", "src/BuildingBlocks/EventBus/EventBus/"] -COPY ["src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "src/BuildingBlocks/EventBus/EventBusRabbitMQ/"] -COPY ["src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "src/BuildingBlocks/EventBus/EventBusServiceBus/"] -COPY ["src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj", "src/Services/Ordering/Ordering.BackgroundTasks/"] - -RUN dotnet restore src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj -COPY . . -WORKDIR /src/src/Services/Ordering/Ordering.BackgroundTasks -RUN dotnet build --no-restore -c $BUILD_CONFIGURATION - -ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] \ No newline at end of file diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/IntegrationEvents/GracePeriodConfirmedIntegrationEvent.cs b/src/Services/Ordering/Ordering.BackgroundTasks/IntegrationEvents/GracePeriodConfirmedIntegrationEvent.cs deleted file mode 100644 index df008ad90..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/IntegrationEvents/GracePeriodConfirmedIntegrationEvent.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; - -namespace Ordering.BackgroundTasks.IntegrationEvents -{ - public class GracePeriodConfirmedIntegrationEvent : IntegrationEvent - { - public int OrderId { get; } - - public GracePeriodConfirmedIntegrationEvent(int orderId) => - OrderId = orderId; - } -} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj deleted file mode 100644 index 3cca3adb7..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj +++ /dev/null @@ -1,42 +0,0 @@ - - - - $(NetCoreTargetVersion) - $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; - ..\..\..\..\docker-compose.dcproj - false - true - $(LangVersion) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs deleted file mode 100644 index 7a429742e..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs +++ /dev/null @@ -1,76 +0,0 @@ -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Serilog; -using System; -using System.IO; - -namespace Ordering.BackgroundTasks -{ - public class Program - { - public static readonly string Namespace = typeof(Program).Namespace; - public static readonly string AppName = Namespace; - - public static int Main(string[] args) - { - var configuration = GetConfiguration(); - - Log.Logger = CreateSerilogLogger(configuration); - - try - { - Log.Information("Configuring web host ({ApplicationContext})...", AppName); - var host = BuildWebHost(configuration, args); - - Log.Information("Starting web host ({ApplicationContext})...", AppName); - host.Run(); - - return 0; - } - catch (Exception ex) - { - Log.Fatal(ex, "Program terminated unexpectedly ({ApplicationContext})!", AppName); - return 1; - } - finally - { - Log.CloseAndFlush(); - } - } - - private static IWebHost BuildWebHost(IConfiguration configuration, string[] args) => - WebHost.CreateDefaultBuilder(args) - .CaptureStartupErrors(false) - .UseStartup() - .UseConfiguration(configuration) - .UseSerilog() - .Build(); - - private static Serilog.ILogger CreateSerilogLogger(IConfiguration configuration) - { - var seqServerUrl = configuration["Serilog:SeqServerUrl"]; - var logstashUrl = configuration["Serilog:LogstashgUrl"]; - return new LoggerConfiguration() - .MinimumLevel.Verbose() - .Enrich.WithProperty("ApplicationContext", AppName) - .Enrich.FromLogContext() - .WriteTo.Console() - .WriteTo.Seq(string.IsNullOrWhiteSpace(seqServerUrl) ? "http://seq" : seqServerUrl) - .WriteTo.Http(string.IsNullOrWhiteSpace(logstashUrl) ? "http://logstash:8080" : logstashUrl) - .ReadFrom.Configuration(configuration) - .CreateLogger(); - } - - private static IConfiguration GetConfiguration() - { - var builder = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) - .AddEnvironmentVariables(); - - return builder.Build(); - } - } -} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Properties/launchSettings.json b/src/Services/Ordering/Ordering.BackgroundTasks/Properties/launchSettings.json deleted file mode 100644 index 6d60a7d28..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Properties/launchSettings.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:5161/", - "sslPort": 0 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "api/values", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "Ordering.BackgroundTasks": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "api/values", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "http://localhost:5162/" - } - } -} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs deleted file mode 100644 index 6035beaeb..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs +++ /dev/null @@ -1,199 +0,0 @@ -using Autofac; -using Autofac.Extensions.DependencyInjection; -using HealthChecks.UI.Client; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.Azure.ServiceBus; -using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; -using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; -using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ; -using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Diagnostics.HealthChecks; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Ordering.BackgroundTasks.Configuration; -using Ordering.BackgroundTasks.Tasks; -using RabbitMQ.Client; -using System; - -namespace Ordering.BackgroundTasks -{ - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - public IServiceProvider ConfigureServices(IServiceCollection services) - { - //add health check for this service - services.AddCustomHealthCheck(Configuration); - - //configure settings - - services.Configure(Configuration); - services.AddOptions(); - - //configure background task - - services.AddSingleton(); - - //configure event bus related services - - if (Configuration.GetValue("AzureServiceBusEnabled")) - { - services.AddSingleton(sp => - { - var logger = sp.GetRequiredService>(); - - var serviceBusConnectionString = Configuration["EventBusConnection"]; - var serviceBusConnection = new ServiceBusConnectionStringBuilder(serviceBusConnectionString); - - return new DefaultServiceBusPersisterConnection(serviceBusConnection, logger); - }); - } - else - { - services.AddSingleton(sp => - { - var logger = sp.GetRequiredService>(); - - - var factory = new ConnectionFactory() - { - HostName = Configuration["EventBusConnection"], - DispatchConsumersAsync = true - }; - - if (!string.IsNullOrEmpty(Configuration["EventBusUserName"])) - { - factory.UserName = Configuration["EventBusUserName"]; - } - - if (!string.IsNullOrEmpty(Configuration["EventBusPassword"])) - { - factory.Password = Configuration["EventBusPassword"]; - } - - var retryCount = 5; - if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"])) - { - retryCount = int.Parse(Configuration["EventBusRetryCount"]); - } - - return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount); - }); - } - - RegisterEventBus(services); - - //create autofac based service provider - var container = new ContainerBuilder(); - container.Populate(services); - - - return new AutofacServiceProvider(container.Build()); - } - - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app) - { - app.UseRouting(); - app.UseEndpoints(endpoints => - { - endpoints.MapHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - endpoints.MapHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - }); - } - - - private void RegisterEventBus(IServiceCollection services) - { - var subscriptionClientName = Configuration["SubscriptionClientName"]; - - if (Configuration.GetValue("AzureServiceBusEnabled")) - { - services.AddSingleton(sp => - { - var serviceBusPersisterConnection = sp.GetRequiredService(); - var iLifetimeScope = sp.GetRequiredService(); - var logger = sp.GetRequiredService>(); - var eventBusSubcriptionsManager = sp.GetRequiredService(); - - return new EventBusServiceBus(serviceBusPersisterConnection, logger, - eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope); - }); - } - else - { - services.AddSingleton(sp => - { - var rabbitMQPersistentConnection = sp.GetRequiredService(); - var iLifetimeScope = sp.GetRequiredService(); - var logger = sp.GetRequiredService>(); - var eventBusSubcriptionsManager = sp.GetRequiredService(); - - var retryCount = 5; - if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"])) - { - retryCount = int.Parse(Configuration["EventBusRetryCount"]); - } - - return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount); - }); - } - - services.AddSingleton(); - } - } - - public static class CustomExtensionMethods - { - public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration) - { - var hcBuilder = services.AddHealthChecks(); - - hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy()); - - hcBuilder - .AddSqlServer( - configuration["ConnectionString"], - name: "OrderingTaskDB-check", - tags: new string[] { "orderingtaskdb" }); - - if (configuration.GetValue("AzureServiceBusEnabled")) - { - hcBuilder - .AddAzureServiceBusTopic( - configuration["EventBusConnection"], - topicName: "eshop_event_bus", - name: "orderingtask-servicebus-check", - tags: new string[] { "servicebus" }); - } - else - { - hcBuilder - .AddRabbitMQ( - $"amqp://{configuration["EventBusConnection"]}", - name: "orderingtask-rabbitmqbus-check", - tags: new string[] { "rabbitmqbus" }); - } - - return services; - } - } -} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs deleted file mode 100644 index 328fb95c4..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs +++ /dev/null @@ -1,95 +0,0 @@ -using Dapper; -using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Ordering.BackgroundTasks.Configuration; -using Ordering.BackgroundTasks.IntegrationEvents; -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Threading; -using System.Threading.Tasks; - -namespace Ordering.BackgroundTasks.Tasks -{ - public class GracePeriodManagerService - : BackgroundService - { - private readonly ILogger _logger; - private readonly BackgroundTaskSettings _settings; - private readonly IEventBus _eventBus; - - public GracePeriodManagerService( - IOptions settings, - IEventBus eventBus, - ILogger logger) - { - _settings = settings?.Value ?? throw new ArgumentNullException(nameof(settings)); - _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - - } - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - _logger.LogDebug("GracePeriodManagerService is starting."); - - stoppingToken.Register(() => _logger.LogDebug("#1 GracePeriodManagerService background task is stopping.")); - - while (!stoppingToken.IsCancellationRequested) - { - _logger.LogDebug("GracePeriodManagerService background task is doing background work."); - - CheckConfirmedGracePeriodOrders(); - - await Task.Delay(_settings.CheckUpdateTime, stoppingToken); - } - - _logger.LogDebug("GracePeriodManagerService background task is stopping."); - - await Task.CompletedTask; - } - - private void CheckConfirmedGracePeriodOrders() - { - _logger.LogDebug("Checking confirmed grace period orders"); - - var orderIds = GetConfirmedGracePeriodOrders(); - - foreach (var orderId in orderIds) - { - var confirmGracePeriodEvent = new GracePeriodConfirmedIntegrationEvent(orderId); - - _logger.LogInformation("----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", confirmGracePeriodEvent.Id, Program.AppName, confirmGracePeriodEvent); - - _eventBus.Publish(confirmGracePeriodEvent); - } - } - - private IEnumerable GetConfirmedGracePeriodOrders() - { - IEnumerable orderIds = new List(); - - using (var conn = new SqlConnection(_settings.ConnectionString)) - { - try - { - conn.Open(); - orderIds = conn.Query( - @"SELECT Id FROM [ordering].[orders] - WHERE DATEDIFF(minute, [OrderDate], GETDATE()) >= @GracePeriodTime - AND [OrderStatusId] = 1", - new { GracePeriodTime = _settings.GracePeriodTime }); - } - catch (SqlException exception) - { - _logger.LogCritical(exception, "FATAL ERROR: Database connections could not be opened: {Message}", exception.Message); - } - - } - - return orderIds; - } - } -} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.Development.json b/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.Development.json deleted file mode 100644 index fa8ce71a9..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.Development.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Logging": { - "IncludeScopes": false, - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } - } -} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.json b/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.json deleted file mode 100644 index 51250be9d..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "ConnectionString": "Server=tcp:127.0.0.1,5433;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word;", - "Serilog": { - "SeqServerUrl": null, - "LogstashgUrl": null, - "MinimumLevel": { - "Default": "Information", - "Override": { - "Microsoft": "Warning", - "Microsoft.eShopOnContainers": "Information", - "System": "Warning" - } - } - }, - "SubscriptionClientName": "BackgroundTasks", - "GracePeriodTime": "1", - "CheckUpdateTime": "1000", - "ApplicationInsights": { - "InstrumentationKey": "" - }, - "AzureServiceBusEnabled": false, - "EventBusRetryCount": 5, - "EventBusConnection": "", - "EventBusUserName": "", - "EventBusPassword": "" -} \ No newline at end of file diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/azds.yaml b/src/Services/Ordering/Ordering.BackgroundTasks/azds.yaml deleted file mode 100644 index e92eca09f..000000000 --- a/src/Services/Ordering/Ordering.BackgroundTasks/azds.yaml +++ /dev/null @@ -1,56 +0,0 @@ -kind: helm-release -apiVersion: 1.1 -build: - context: ..\..\..\.. - dockerfile: Dockerfile -install: - chart: ../../../../k8s/helm/ordering-backgroundtasks - set: - replicaCount: 1 - image: - tag: $(tag) - pullPolicy: Never - ingress: - annotations: - kubernetes.io/ingress.class: traefik-azds - hosts: - - $(spacePrefix)eshop$(hostSuffix) - inf: - k8s: - dns: $(spacePrefix)eshop$(hostSuffix) - values: - - values.dev.yaml? - - secrets.dev.yaml? - - inf.yaml - - app.yaml -configurations: - develop: - build: - useGitIgnore: true - dockerfile: Dockerfile.develop - args: - BUILD_CONFIGURATION: ${BUILD_CONFIGURATION:-Debug} - container: - sync: - - '**/Pages/**' - - '**/Views/**' - - '**/wwwroot/**' - - '!**/*.{sln,csproj}' - command: - - dotnet - - run - - --no-restore - - --no-build - - --no-launch-profile - - -c - - ${BUILD_CONFIGURATION:-Debug} - iterate: - processesToKill: - - dotnet - - vsdbg - buildCommands: - - - dotnet - - build - - --no-restore - - -c - - ${BUILD_CONFIGURATION:-Debug} From 17dd9cebb1fce9930c6a63aee50b3be4b474c763 Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 31 Jul 2019 09:12:12 +0200 Subject: [PATCH 035/113] remove all references of basket background --- build/acr-build/queue-all.ps1 | 1 - .../multiarch-manifests/create-manifests.ps1 | 2 +- docker-compose-windows.prod.yml | 11 --- docker-compose.override.windows.yml | 5 - docker-compose.override.yml | 23 ----- docker-compose.prod.yml | 20 ---- docker-compose.yml | 10 +- eShopOnContainers.sln | 2 - k8s/build-push-images.ps1 | 2 +- k8s/deploy.ps1 | 2 +- k8s/deployments.yaml | 64 ------------- k8s/helm/app.yaml | 1 - k8s/helm/deploy-all-istio.ps1 | 2 +- k8s/helm/deploy-all.ps1 | 2 +- k8s/helm/deploy-all.sh | 2 +- k8s/helm/istio/doc.md | 1 - k8s/helm/ordering-backgroundtasks/.helmignore | 21 ----- k8s/helm/ordering-backgroundtasks/Chart.yaml | 5 - .../templates/NOTES.txt | 3 - .../templates/_helpers.tpl | 32 ------- .../templates/_names.tpl | 51 ---------- .../templates/configmap.yaml | 21 ----- .../templates/deployment.yaml | 92 ------------------- .../templates/service.yaml | 19 ---- k8s/helm/ordering-backgroundtasks/values.yaml | 70 -------------- src/csproj-files.txt | 1 - src/prepare-devspaces.ps1 | 3 - 27 files changed, 7 insertions(+), 461 deletions(-) delete mode 100644 k8s/helm/ordering-backgroundtasks/.helmignore delete mode 100644 k8s/helm/ordering-backgroundtasks/Chart.yaml delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/NOTES.txt delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/_names.tpl delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/configmap.yaml delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/deployment.yaml delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/service.yaml delete mode 100644 k8s/helm/ordering-backgroundtasks/values.yaml diff --git a/build/acr-build/queue-all.ps1 b/build/acr-build/queue-all.ps1 index aacffea95..60a39d92c 100644 --- a/build/acr-build/queue-all.ps1 +++ b/build/acr-build/queue-all.ps1 @@ -13,7 +13,6 @@ $services = @( @{ Name="eshopcatalog"; Image="eshop/catalog.api"; File="src/Services/Catalog/Catalog.API/Dockerfile" }, @{ Name="eshopidentity"; Image="eshop/identity.api"; File="src/Services/Identity/Identity.API/Dockerfile" }, @{ Name="eshopordering"; Image="eshop/ordering.api"; File="src/Services/Ordering/Ordering.API/Dockerfile" }, - @{ Name="eshoporderingbg"; Image="eshop/ordering.backgroundtasks"; File="src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile" }, @{ Name="eshopmarketing"; Image="eshop/marketing.api"; File="src/Services/Marketing/Marketing.API/Dockerfile" }, @{ Name="eshopwebspa"; Image="eshop/webspa"; File="src/Web/WebSPA/Dockerfile" }, @{ Name="eshopwebmvc"; Image="eshop/webmvc"; File="src/Web/WebMVC/Dockerfile" }, diff --git a/build/multiarch-manifests/create-manifests.ps1 b/build/multiarch-manifests/create-manifests.ps1 index cc7f05194..0bc6a4c7c 100644 --- a/build/multiarch-manifests/create-manifests.ps1 +++ b/build/multiarch-manifests/create-manifests.ps1 @@ -12,7 +12,7 @@ Write-Host "Tags used are linux-master, win-master, linux-dev, win-dev, linux-la Write-Host "Multiarch images tags will be master, dev, latest" -ForegroundColor Yellow -$services = "identity.api", "basket.api", "catalog.api", "ordering.api", "ordering.backgroundtasks", "marketing.api", "payment.api", "locations.api", "webhooks.api", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub", "webstatus", "webspa", "webmvc", "webhooks.client" +$services = "identity.api", "basket.api", "catalog.api", "ordering.api", "marketing.api", "payment.api", "locations.api", "webhooks.api", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub", "webstatus", "webspa", "webmvc", "webhooks.client" foreach ($svc in $services) { Write-Host "Creating manifest for $svc and tags :latest, :master, and :dev" diff --git a/docker-compose-windows.prod.yml b/docker-compose-windows.prod.yml index ead977f29..638c98d69 100644 --- a/docker-compose-windows.prod.yml +++ b/docker-compose-windows.prod.yml @@ -69,17 +69,6 @@ services: ports: - "5102:80" - ordering.backgroundtasks: - environment: - - ASPNETCORE_ENVIRONMENT=Production - - ASPNETCORE_URLS=http://0.0.0.0:80 - - ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word} - - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} - - UseCustomizationData=True - - AzureServiceBusEnabled=False - ports: - - "5111:80" - webspa: environment: - ASPNETCORE_ENVIRONMENT=Production diff --git a/docker-compose.override.windows.yml b/docker-compose.override.windows.yml index dcaac7c45..0f1e66efe 100644 --- a/docker-compose.override.windows.yml +++ b/docker-compose.override.windows.yml @@ -37,11 +37,6 @@ services: - EventBusUserName=admin - EventBusPassword=password - ordering.backgroundtasks: - environment: - - EventBusUserName=admin - - EventBusPassword=password - payment.api: environment: - EventBusUserName=admin diff --git a/docker-compose.override.yml b/docker-compose.override.yml index e4ee76650..bd04fa997 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -115,26 +115,6 @@ services: ports: - "5102:80" - - ordering.backgroundtasks: - environment: - - ASPNETCORE_ENVIRONMENT=Development - - ASPNETCORE_URLS=http://0.0.0.0:80 - - ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word} - - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} - - EventBusUserName=${ESHOP_SERVICE_BUS_USERNAME} - - EventBusPassword=${ESHOP_SERVICE_BUS_PASSWORD} - - UseCustomizationData=True - - AzureServiceBusEnabled=False - - CheckUpdateTime=30000 - - GracePeriodTime=1 - - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - - OrchestratorType=${ORCHESTRATOR_TYPE} - - UseLoadTest=${USE_LOADTEST:-False} - - Serilog__MinimumLevel__Override__Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ=Verbose - ports: - - "5111:80" - marketing.api: environment: - ASPNETCORE_ENVIRONMENT=Development @@ -343,8 +323,6 @@ services: - HealthChecks-UI__HealthChecks__7__Uri=http://webmarketingapigw/hc - HealthChecks-UI__HealthChecks__8__Name=Ordering HTTP Check - HealthChecks-UI__HealthChecks__8__Uri=http://ordering.api/hc - - HealthChecks-UI__HealthChecks__9__Name=Ordering HTTP Background Check - - HealthChecks-UI__HealthChecks__9__Uri=http://ordering.backgroundtasks/hc - HealthChecks-UI__HealthChecks__10__Name=Basket HTTP Check - HealthChecks-UI__HealthChecks__10__Uri=http://basket.api/hc - HealthChecks-UI__HealthChecks__11__Name=Catalog HTTP Check @@ -359,7 +337,6 @@ services: - HealthChecks-UI__HealthChecks__15__Uri=http://payment.api/hc - HealthChecks-UI__HealthChecks__16__Name=Ordering SignalRHub HTTP Check - HealthChecks-UI__HealthChecks__16__Uri=http://ordering.signalrhub/hc - - OrderingBackgroundTasksUrl=http://ordering.backgroundtasks/hc - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - OrchestratorType=${ORCHESTRATOR_TYPE} ports: diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 4bf465565..e1825a8c4 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -91,25 +91,6 @@ services: ports: - "80" # The API Gateway redirects and access through the internal port (80). - - ordering.backgroundtasks: - environment: - - ASPNETCORE_ENVIRONMENT=Development - - ASPNETCORE_URLS=http://0.0.0.0:80 - - ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word} - - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} - - EventBusUserName=${ESHOP_SERVICE_BUS_USERNAME} - - EventBusPassword=${ESHOP_SERVICE_BUS_PASSWORD} - - UseCustomizationData=True - - AzureServiceBusEnabled=False - - CheckUpdateTime=30000 - - GracePeriodTime=1 - - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - - OrchestratorType=${ORCHESTRATOR_TYPE} - - UseLoadTest=${USE_LOADTEST:-False} - ports: - - "5111:80" - marketing.api: environment: - ASPNETCORE_ENVIRONMENT=Development @@ -179,7 +160,6 @@ services: - ASPNETCORE_URLS=http://0.0.0.0:80 - CatalogUrl=http://catalog.api/hc - OrderingUrl=http://ordering.api/hc - - OrderingBackgroundTasksUrl=http://ordering.backgroundtasks/hc - BasketUrl=http://basket.api/hc - IdentityUrl=http://identity.api/hc - LocationsUrl=http://locations.api/hc diff --git a/docker-compose.yml b/docker-compose.yml index 243fbf2c6..ccc888bf2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -52,15 +52,7 @@ services: depends_on: - sql.data - rabbitmq - - ordering.backgroundtasks: - image: ${REGISTRY:-eshop}/ordering.backgroundtasks:${PLATFORM:-linux}-${TAG:-latest} - build: - context: . - dockerfile: src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile - depends_on: - - sql.data - - rabbitmq + - identity.api marketing.api: image: ${REGISTRY:-eshop}/marketing.api:${PLATFORM:-linux}-${TAG:-latest} diff --git a/eShopOnContainers.sln b/eShopOnContainers.sln index c3e63925d..232331854 100644 --- a/eShopOnContainers.sln +++ b/eShopOnContainers.sln @@ -99,8 +99,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "eShopOnContainers.TestRunne EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "eShopOnContainers.TestRunner.Windows", "src\Mobile\eShopOnContainers\eShopOnContainers.TestRunner.Windows\eShopOnContainers.TestRunner.Windows.csproj", "{A7337243-33B8-463A-87AD-944B75EFD820}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.BackgroundTasks", "src\Services\Ordering\Ordering.BackgroundTasks\Ordering.BackgroundTasks.csproj", "{16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basket.FunctionalTests", "src\Services\Basket\Basket.FunctionalTests\Basket.FunctionalTests.csproj", "{9F00E62F-E180-4A9C-8794-98A72AFAC2DB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basket.UnitTests", "src\Services\Basket\Basket.UnitTests\Basket.UnitTests.csproj", "{63417272-1E6A-406A-AD11-C738558D89C0}" diff --git a/k8s/build-push-images.ps1 b/k8s/build-push-images.ps1 index e2c8e06b6..769e74abc 100644 --- a/k8s/build-push-images.ps1 +++ b/k8s/build-push-images.ps1 @@ -57,7 +57,7 @@ if (-not [string]::IsNullOrEmpty($dockerUser)) { # Push images to Docker registry if ($pushImages) { Write-Host "Pushing images to $registry/$dockerOrg..." -ForegroundColor Yellow - $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "ordering.backgroundtasks", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") + $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") foreach ($service in $services) { $imageFqdn = if ($useDockerHub) {"$dockerOrg/${service}"} else {"$registry/$dockerOrg/${service}"} diff --git a/k8s/deploy.ps1 b/k8s/deploy.ps1 index abeb12aed..81af1bec7 100644 --- a/k8s/deploy.ps1 +++ b/k8s/deploy.ps1 @@ -68,7 +68,7 @@ if ($buildImages) { if ($pushImages) { Write-Host "Pushing images to $registry/$dockerOrg..." -ForegroundColor Yellow - $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "ordering.backgroundtasks", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") + $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") foreach ($service in $services) { $imageFqdn = if ($useDockerHub) {"$dockerOrg/${service}"} else {"$registry/$dockerOrg/${service}"} diff --git a/k8s/deployments.yaml b/k8s/deployments.yaml index f362c319c..46d139d1c 100644 --- a/k8s/deployments.yaml +++ b/k8s/deployments.yaml @@ -265,65 +265,6 @@ spec: --- apiVersion: extensions/v1beta1 kind: Deployment -metadata: - name: ordering-backgroundtasks -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: ordering-backgroundtasks - spec: - containers: - - name: ordering-backgroundtasks - image: eshop/ordering.backgroundtasks - imagePullPolicy: Always - env: - - name: ConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: ordering__ConnectionString - - name: EventBusConnection - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EventBusConnection - - name: AzureServiceBusEnabled - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__UseAzureServiceBus - - name: CheckUpdateTime - valueFrom: - configMapKeyRef: - name: externalcfg - key: GracePeriodManager__CheckUpdateTime - - name: GracePeriodTime - valueFrom: - configMapKeyRef: - name: externalcfg - key: GracePeriodManager__GracePeriodTime - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: UseLoadTest - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EnableLoadTest - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment metadata: name: ordering-signalrhub spec: @@ -702,11 +643,6 @@ spec: configMapKeyRef: name: internalurls key: ordering__hc - - name: OrderingBackgroundTasksUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: ordering-background__hc - name: LocationsUrl valueFrom: configMapKeyRef: diff --git a/k8s/helm/app.yaml b/k8s/helm/app.yaml index 91e829b27..390844a6e 100644 --- a/k8s/helm/app.yaml +++ b/k8s/helm/app.yaml @@ -28,7 +28,6 @@ app: # app global settings basket: basket # service name for basket api catalog: catalog # service name for catalog api ordering: ordering # service name for ordering api - orderingbackgroundtasks: orderingbackgroundtasks # service name for orderingbackgroundtasks orderingsignalrhub: ordering-signalrhub # service name for orderingsignalrhub identity: identity # service name for identity api mvc: webmvc # service name for web mvc diff --git a/k8s/helm/deploy-all-istio.ps1 b/k8s/helm/deploy-all-istio.ps1 index 5e05c6dbb..9e32704b1 100644 --- a/k8s/helm/deploy-all-istio.ps1 +++ b/k8s/helm/deploy-all-istio.ps1 @@ -80,7 +80,7 @@ if (-not [string]::IsNullOrEmpty($registry)) { Write-Host "Begin eShopOnContainers installation using Helm" -ForegroundColor Green $infras = ("sql-data", "nosql-data", "rabbitmq", "keystore-data", "basket-data") -$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-backgroundtasks","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") +$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") if ($deployInfrastructure) { foreach ($infra in $infras) { diff --git a/k8s/helm/deploy-all.ps1 b/k8s/helm/deploy-all.ps1 index 3cf6936bc..21bb2f1a0 100644 --- a/k8s/helm/deploy-all.ps1 +++ b/k8s/helm/deploy-all.ps1 @@ -62,7 +62,7 @@ if (-not [string]::IsNullOrEmpty($registry)) { Write-Host "Begin eShopOnContainers installation using Helm" -ForegroundColor Green $infras = ("sql-data", "nosql-data", "rabbitmq", "keystore-data", "basket-data") -$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-backgroundtasks","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") +$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") if ($deployInfrastructure) { foreach ($infra in $infras) { diff --git a/k8s/helm/deploy-all.sh b/k8s/helm/deploy-all.sh index 705b172f5..04891799b 100755 --- a/k8s/helm/deploy-all.sh +++ b/k8s/helm/deploy-all.sh @@ -185,7 +185,7 @@ fi echo "#################### Begin $app_name installation using Helm ####################" infras=(sql-data nosql-data rabbitmq keystore-data basket-data) -charts=(eshop-common apigwmm apigwms apigwwm apigwws basket-api catalog-api identity-api locations-api marketing-api mobileshoppingagg ordering-api ordering-backgroundtasks ordering-signalrhub payment-api webmvc webshoppingagg webspa webstatus webhooks-api webhooks-web) +charts=(eshop-common apigwmm apigwms apigwwm apigwws basket-api catalog-api identity-api locations-api marketing-api mobileshoppingagg ordering-api ordering-signalrhub payment-api webmvc webshoppingagg webspa webstatus webhooks-api webhooks-web) if [[ !$skip_infrastructure ]]; then for infra in "${infras[@]}" diff --git a/k8s/helm/istio/doc.md b/k8s/helm/istio/doc.md index b8c0a0257..f60b714f1 100644 --- a/k8s/helm/istio/doc.md +++ b/k8s/helm/istio/doc.md @@ -258,7 +258,6 @@ fec1e3499416 a3f21ec4bd11 "/entrypoint.sh /ngi…" 76485867f032 eshop/payment.api "dotnet Payment.API.…" 2 hours ago Up 2 hours k8s_payment-api_eshop-payment-api-75d5f9bdf6-6zx2v_default_4a3cdab4-e67f-11e8-b4b6-00155d016146_1 c2c4640ed610 eshop/marketing.api "dotnet Marketing.AP…" 2 hours ago Up 2 hours k8s_marketing-api_eshop-marketing-api-6b8c5989fd-jpxqv_default_45780626-e67f-11e8-b4b6-00155d016146_1 85301d538574 eshop/ordering.signalrhub "dotnet Ordering.Sig…" 2 hours ago Up 2 hours k8s_ordering-signalrhub_eshop-ordering-signalrhub-58cf5ff6-cnlm8_default_4932c344-e67f-11e8-b4b6-00155d016146_1 -7a408a98000e eshop/ordering.backgroundtasks "dotnet Ordering.Bac…" 2 hours ago Up 2 hours k8s_ordering-backgroundtasks_eshop-ordering-backgroundtasks-cc8f6d4d8-ztfk7_default_47f9cf10-e67f-11e8-b4b6-00155d016146_1 12c64b3a13e0 eshop/basket.api "dotnet Basket.API.d…" 2 hours ago Up 2 hours k8s_basket-api_eshop-basket-api-658546684d-6hlvd_default_4262d022-e67f-11e8-b4b6-00155d016146_1 133fccfeeff3 eshop/webstatus "dotnet WebStatus.dll" 2 hours ago Up 2 hours k8s_webstatus_eshop-webstatus-7f46479dc4-bqnq7_default_4dc13eb2-e67f-11e8-b4b6-00155d016146_0 00c6e4c52135 eshop/webspa "dotnet WebSPA.dll" 2 hours ago Up 2 hours k8s_webspa_eshop-webspa-64cb8df9cb-dcbwg_default_4cd47376-e67f-11e8-b4b6-00155d016146_0 diff --git a/k8s/helm/ordering-backgroundtasks/.helmignore b/k8s/helm/ordering-backgroundtasks/.helmignore deleted file mode 100644 index f0c131944..000000000 --- a/k8s/helm/ordering-backgroundtasks/.helmignore +++ /dev/null @@ -1,21 +0,0 @@ -# Patterns to ignore when building packages. -# This supports shell glob matching, relative path matching, and -# negation (prefixed with !). Only one pattern per line. -.DS_Store -# Common VCS dirs -.git/ -.gitignore -.bzr/ -.bzrignore -.hg/ -.hgignore -.svn/ -# Common backup files -*.swp -*.bak -*.tmp -*~ -# Various IDEs -.project -.idea/ -*.tmproj diff --git a/k8s/helm/ordering-backgroundtasks/Chart.yaml b/k8s/helm/ordering-backgroundtasks/Chart.yaml deleted file mode 100644 index 6ad4f47e6..000000000 --- a/k8s/helm/ordering-backgroundtasks/Chart.yaml +++ /dev/null @@ -1,5 +0,0 @@ -apiVersion: v1 -appVersion: "1.0" -description: A Helm chart for Kubernetes -name: ordering-backgroundtasks -version: 0.1.0 diff --git a/k8s/helm/ordering-backgroundtasks/templates/NOTES.txt b/k8s/helm/ordering-backgroundtasks/templates/NOTES.txt deleted file mode 100644 index 54e1b49ea..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/NOTES.txt +++ /dev/null @@ -1,3 +0,0 @@ -eShop Ordering Background Tasks installed. ------------------------------------------- - diff --git a/k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl b/k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl deleted file mode 100644 index e61b78285..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl +++ /dev/null @@ -1,32 +0,0 @@ -{{/* vim: set filetype=mustache: */}} -{{/* -Expand the name of the chart. -*/}} -{{- define "ordering-backgroundtasks.name" -}} -{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} -{{- end -}} - -{{/* -Create a default fully qualified app name. -We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). -If release name contains chart name it will be used as a full name. -*/}} -{{- define "ordering-backgroundtasks.fullname" -}} -{{- if .Values.fullnameOverride -}} -{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} -{{- else -}} -{{- $name := default .Chart.Name .Values.nameOverride -}} -{{- if contains $name .Release.Name -}} -{{- .Release.Name | trunc 63 | trimSuffix "-" -}} -{{- else -}} -{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} -{{- end -}} -{{- end -}} -{{- end -}} - -{{/* -Create chart name and version as used by the chart label. -*/}} -{{- define "ordering-backgroundtasks.chart" -}} -{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} -{{- end -}} diff --git a/k8s/helm/ordering-backgroundtasks/templates/_names.tpl b/k8s/helm/ordering-backgroundtasks/templates/_names.tpl deleted file mode 100644 index 39ee485ef..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/_names.tpl +++ /dev/null @@ -1,51 +0,0 @@ -{{- define "suffix-name" -}} -{{- if .Values.app.name -}} -{{- .Values.app.name -}} -{{- else -}} -{{- .Release.Name -}} -{{- end -}} -{{- end -}} - -{{- define "sql-name" -}} -{{- if .Values.inf.sql.host -}} -{{- .Values.inf.sql.host -}} -{{- else -}} -{{- printf "%s" "sql-data" -}} -{{- end -}} -{{- end -}} - -{{- define "mongo-name" -}} -{{- if .Values.inf.mongo.host -}} -{{- .Values.inf.mongo.host -}} -{{- else -}} -{{- printf "%s" "nosql-data" -}} -{{- end -}} -{{- end -}} - -{{- define "url-of" -}} -{{- $name := first .}} -{{- $ctx := last .}} -{{- if eq $name "" -}} -{{- $ctx.Values.inf.k8s.dns -}} -{{- else -}} -{{- printf "%s/%s" $ctx.Values.inf.k8s.dns $name -}} {{/*Value is just / */}} -{{- end -}} -{{- end -}} - - -{{- define "pathBase" -}} -{{- if .Values.inf.k8s.suffix -}} -{{- $suffix := include "suffix-name" . -}} -{{- printf "%s-%s" .Values.pathBase $suffix -}} -{{- else -}} -{{- .Values.pathBase -}} -{{- end -}} -{{- end -}} - -{{- define "fqdn-image" -}} -{{- if .Values.inf.registry -}} -{{- printf "%s/%s" .Values.inf.registry.server .Values.image.repository -}} -{{- else -}} -{{- .Values.image.repository -}} -{{- end -}} -{{- end -}} \ No newline at end of file diff --git a/k8s/helm/ordering-backgroundtasks/templates/configmap.yaml b/k8s/helm/ordering-backgroundtasks/templates/configmap.yaml deleted file mode 100644 index 7ed4a0e8e..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/configmap.yaml +++ /dev/null @@ -1,21 +0,0 @@ -{{- $name := include "ordering-backgroundtasks.fullname" . -}} -{{- $sqlsrv := include "sql-name" . -}} -{{- $cfgname := printf "cfg-%s" $name | trunc 63 }} - -apiVersion: v1 -kind: ConfigMap -metadata: - name: "{{ $cfgname }}" - labels: - app: {{ template "ordering-backgroundtasks.name" . }} - chart: {{ template "ordering-backgroundtasks.chart" .}} - release: {{ .Release.Name }} - heritage: {{ .Release.Service }} -data: - ordering__ConnectionString: Server={{ $sqlsrv }};Initial Catalog={{ .Values.inf.sql.ordering.db }};User Id={{ .Values.inf.sql.common.user }};Password={{ .Values.inf.sql.common.pwd }}; - ordering__EnableLoadTest: "{{ .Values.inf.misc.useLoadTest }}" - all__EventBusConnection: {{ .Values.inf.eventbus.constr }} - all__InstrumentationKey: "{{ .Values.inf.appinsights.key }}" - all__UseAzureServiceBus: "{{ .Values.inf.eventbus.useAzure }}" - graceperiodmanager__CheckUpdateTime: "{{ .Values.cfg.checkUpdateTime }}" - graceperiodmanager__GracePeriodTime: "{{ .Values.cfg.gracePeriodTime }}" \ No newline at end of file diff --git a/k8s/helm/ordering-backgroundtasks/templates/deployment.yaml b/k8s/helm/ordering-backgroundtasks/templates/deployment.yaml deleted file mode 100644 index d93c7f764..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/deployment.yaml +++ /dev/null @@ -1,92 +0,0 @@ -{{- $name := include "ordering-backgroundtasks.fullname" . -}} -{{- $cfgname := printf "cfg-%s" $name | trunc 63 }} - -apiVersion: apps/v1beta2 -kind: Deployment -metadata: - name: {{ template "ordering-backgroundtasks.fullname" . }} - labels: - app: {{ template "ordering-backgroundtasks.name" . }} - chart: {{ template "ordering-backgroundtasks.chart" . }} - release: {{ .Release.Name }} - heritage: {{ .Release.Service }} -spec: - replicas: {{ .Values.replicaCount }} - selector: - matchLabels: - app: {{ template "ordering-backgroundtasks.name" . }} - release: {{ .Release.Name }} - template: - metadata: - labels: - app: {{ template "ordering-backgroundtasks.name" . }} - release: {{ .Release.Name }} - spec: - {{ if .Values.inf.registry -}} - imagePullSecrets: - - name: {{ .Values.inf.registry.secretName }} - {{- end }} - containers: - - name: {{ .Chart.Name }} - {{ if .Values.probes -}} - {{- if .Values.probes.liveness -}} - livenessProbe: - httpGet: - port: {{ .Values.probes.liveness.port }} - path: {{ .Values.probes.liveness.path }} - initialDelaySeconds: {{ .Values.probes.liveness.initialDelaySeconds }} - periodSeconds: {{ .Values.probes.liveness.periodSeconds }} - {{- end -}} - {{- end -}} - {{- if .Values.probes -}} - {{- if .Values.probes.readiness }} - readinessProbe: - httpGet: - port: {{ .Values.probes.readiness.port }} - path: {{ .Values.probes.readiness.path }} - initialDelaySeconds: {{ .Values.probes.readiness.initialDelaySeconds }} - periodSeconds: {{ .Values.probes.readiness.periodSeconds }} - timeoutSeconds: {{ .Values.probes.readiness.timeoutSeconds }} - {{- end -}} - {{- end }} - image: "{{ template "fqdn-image" . }}:{{ .Values.image.tag }}" - imagePullPolicy: {{ .Values.image.pullPolicy }} - env: - - name: PATH_BASE - value: {{ include "pathBase" . }} - - name: k8sname - value: {{ .Values.clusterName }} - {{- if .Values.env.values -}} - {{- range .Values.env.values }} - - name: {{ .name }} - value: {{ .value | quote }} - {{- end -}} - {{- end -}} - {{- if .Values.env.configmap -}} - {{- range .Values.env.configmap }} - - name: {{ .name }} - valueFrom: - configMapKeyRef: - name: {{ $cfgname }} - key: {{ .key }} - {{- end -}} - {{- end }} - ports: - - name: http - containerPort: 80 - protocol: TCP - resources: -{{ toYaml .Values.resources | indent 12 }} - {{- with .Values.nodeSelector }} - nodeSelector: -{{ toYaml . | indent 8 }} - {{- end }} - {{- with .Values.affinity }} - affinity: -{{ toYaml . | indent 8 }} - {{- end }} - {{- with .Values.tolerations }} - tolerations: -{{ toYaml . | indent 8 }} - {{- end }} - diff --git a/k8s/helm/ordering-backgroundtasks/templates/service.yaml b/k8s/helm/ordering-backgroundtasks/templates/service.yaml deleted file mode 100644 index d8fcba036..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/service.yaml +++ /dev/null @@ -1,19 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: {{ .Values.app.svc.orderingbackgroundtasks }} - labels: - app: {{ template "ordering-backgroundtasks.name" . }} - chart: {{ template "ordering-backgroundtasks.chart" . }} - release: {{ .Release.Name }} - heritage: {{ .Release.Service }} -spec: - type: {{ .Values.service.type }} - ports: - - port: {{ .Values.service.port }} - targetPort: http - protocol: TCP - name: http - selector: - app: {{ template "ordering-backgroundtasks.name" . }} - release: {{ .Release.Name }} diff --git a/k8s/helm/ordering-backgroundtasks/values.yaml b/k8s/helm/ordering-backgroundtasks/values.yaml deleted file mode 100644 index d065f0345..000000000 --- a/k8s/helm/ordering-backgroundtasks/values.yaml +++ /dev/null @@ -1,70 +0,0 @@ -replicaCount: 1 -clusterName: eshop-aks -pathBase: /ordering-backgroundtasks - -image: - repository: eshop/ordering.backgroundtasks - tag: latest - pullPolicy: IfNotPresent - -service: - type: ClusterIP - port: 80 - -ingress: - enabled: false - annotations: {} - hosts: - - chart-example.local - tls: [] - -cfg: - checkUpdateTime: "15000" - gracePeriodTime: "1" - -resources: {} - - -nodeSelector: {} - -tolerations: [] - -affinity: {} - -# env defines the environment variables that will be declared in the pod -env: - urls: - # configmap declares variables which value is taken from the config map defined in template configmap.yaml (name is name of var and key the key in configmap). - configmap: - - name: ConnectionString - key: ordering__ConnectionString - - name: ApplicationInsights__InstrumentationKey - key: all__InstrumentationKey - - name: EventBusConnection - key: all__EventBusConnection - - name: AzureServiceBusEnabled - key: all__UseAzureServiceBus - - name: UseLoadTest - key: ordering__EnableLoadTest - - name: CheckUpdateTime - key: graceperiodmanager__CheckUpdateTime - - name: GracePeriodTime - key: graceperiodmanager__GracePeriodTime - # values define environment variables with a fixed value (no configmap involved) (name is name of var, and value is its value) - values: - - name: ASPNETCORE_ENVIRONMENT - value: Development - - name: OrchestratorType - value: 'K8S' -probes: - liveness: - path: /liveness - initialDelaySeconds: 10 - periodSeconds: 15 - port: 80 - readiness: - path: /hc - timeoutSeconds: 5 - initialDelaySeconds: 90 - periodSeconds: 60 - port: 80 diff --git a/src/csproj-files.txt b/src/csproj-files.txt index 6dc3532d9..96420d96e 100644 --- a/src/csproj-files.txt +++ b/src/csproj-files.txt @@ -20,7 +20,6 @@ COPY src/Services/Location/Locations.FunctionalTests/*.csproj /src/src/Services/ COPY src/Services/Marketing/Marketing.API/*.csproj /src/src/Services/Marketing/Marketing.API/ COPY src/Services/Marketing/Marketing.FunctionalTests/*.csproj /src/src/Services/Marketing/Marketing.FunctionalTests/ COPY src/Services/Ordering/Ordering.API/*.csproj /src/src/Services/Ordering/Ordering.API/ -COPY src/Services/Ordering/Ordering.BackgroundTasks/*.csproj /src/src/Services/Ordering/Ordering.BackgroundTasks/ COPY src/Services/Ordering/Ordering.Domain/*.csproj /src/src/Services/Ordering/Ordering.Domain/ COPY src/Services/Ordering/Ordering.FunctionalTests/*.csproj /src/src/Services/Ordering/Ordering.FunctionalTests/ COPY src/Services/Ordering/Ordering.Infrastructure/*.csproj /src/src/Services/Ordering/Ordering.Infrastructure/ diff --git a/src/prepare-devspaces.ps1 b/src/prepare-devspaces.ps1 index 5b692e908..5e1b72d4e 100644 --- a/src/prepare-devspaces.ps1 +++ b/src/prepare-devspaces.ps1 @@ -52,9 +52,6 @@ Copy-Item "..\k8s\helm\inf.yaml" -Destination ".\Services\Ordering\Ordering.API" Copy-Item "..\k8s\helm\app.yaml" -Destination ".\Services\Ordering\Ordering.SignalrHub" -Force Copy-Item "..\k8s\helm\inf.yaml" -Destination ".\Services\Ordering\Ordering.SignalrHub" -Force -Copy-Item "..\k8s\helm\app.yaml" -Destination ".\Services\Ordering\Ordering.BackgroundTasks" -Force -Copy-Item "..\k8s\helm\inf.yaml" -Destination ".\Services\Ordering\Ordering.BackgroundTasks" -Force - Write-Host "Copying app.yaml and inf.yaml to Payment API" -ForegroundColor Yellow Copy-Item "..\k8s\helm\app.yaml" -Destination ".\Services\Payment\Payment.API" -Force Copy-Item "..\k8s\helm\inf.yaml" -Destination ".\Services\Payment\Payment.API" -Force From 445c43221bdccfba93fc043dd02e9db9baf903fd Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 31 Jul 2019 09:12:46 +0200 Subject: [PATCH 036/113] fix basket api --- .../AuthorizeCheckOperationFilter.cs | 36 +++++++++ src/Services/Basket/Basket.API/Startup.cs | 81 ++++++++++--------- 2 files changed, 79 insertions(+), 38 deletions(-) create mode 100644 src/Services/Basket/Basket.API/Infrastructure/Middlewares/AuthorizeCheckOperationFilter.cs diff --git a/src/Services/Basket/Basket.API/Infrastructure/Middlewares/AuthorizeCheckOperationFilter.cs b/src/Services/Basket/Basket.API/Infrastructure/Middlewares/AuthorizeCheckOperationFilter.cs new file mode 100644 index 000000000..4a1c24aa6 --- /dev/null +++ b/src/Services/Basket/Basket.API/Infrastructure/Middlewares/AuthorizeCheckOperationFilter.cs @@ -0,0 +1,36 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; +using System.Collections.Generic; +using System.Linq; + +namespace Basket.API.Infrastructure.Filters +{ + public class AuthorizeCheckOperationFilter : IOperationFilter + { + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + // Check for authorize attribute + var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || + context.MethodInfo.GetCustomAttributes(true).OfType().Any(); + + if (!hasAuthorize) return; + + operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" }); + + var oAuthScheme = new OpenApiSecurityScheme + { + Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } + }; + + operation.Security = new List + { + new OpenApiSecurityRequirement + { + [ oAuthScheme ] = new [] { "basketapi" } + } + }; + } + } +} \ No newline at end of file diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index 3620b0b00..098428ad9 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -55,6 +55,37 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API }).AddNewtonsoftJson(); + services.AddSwaggerGen(options => + { + options.DescribeAllEnumsAsStrings(); + options.SwaggerDoc("v1", new OpenApiInfo + { + Title = "eShopOnContainers - Basket HTTP API", + Version = "v1", + Description = "The Basket Service HTTP API" + }); + + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme + { + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() + { + Implicit = new OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "basket", "Basket API" } + } + } + } + }); + + options.OperationFilter(); + }); + + ConfigureAuthService(services); services.AddCustomHealthCheck(Configuration); @@ -124,33 +155,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API RegisterEventBus(services); - services.AddSwaggerGen(options => - { - options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = "eShopOnContainers - Basket HTTP API", - Version = "v1", - Description = "The Basket Service HTTP API" - }); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows() - { - Implicit = new OpenApiOAuthFlow() - { - AuthorizationUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), - TokenUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/token"), - Scopes = new Dictionary() - { - { "basket", "Basket API" } - } - } - } - }); - }); services.AddCors(options => { @@ -185,20 +189,12 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UsePathBase(pathBase); } + app.UseRouting(); ConfigureAuth(app); app.UseStaticFiles(); - app.UseSwagger() - .UseSwaggerUI(setup => - { - setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); - setup.OAuthClientId("basketswaggerui"); - setup.OAuthAppName("Basket Swagger UI"); - }); - app.UseCors("CorsPolicy"); - app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); @@ -213,6 +209,15 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API Predicate = r => r.Name.Contains("self") }); }); + + app.UseSwagger() + .UseSwaggerUI(setup => + { + setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); + setup.OAuthClientId("basketswaggerui"); + setup.OAuthAppName("Basket Swagger UI"); + }); + ConfigureEventBus(app); } @@ -226,7 +231,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API private void ConfigureAuthService(IServiceCollection services) { // prevent from mapping "sub" claim to nameidentifier. - JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); + JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); var identityUrl = Configuration.GetValue("IdentityUrl"); @@ -250,8 +255,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UseMiddleware(); } - app.UseAuthorization(); app.UseAuthentication(); + app.UseAuthorization(); } private void RegisterEventBus(IServiceCollection services) From 6e69b36a778dfed312f938ed5c48791441d45c92 Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 31 Jul 2019 09:13:04 +0200 Subject: [PATCH 037/113] migrate functional tests of ordering api --- .../Commands/CancelOrderCommand.cs | 3 +++ .../Ordering/Ordering.API/Ordering.API.csproj | 1 + src/Services/Ordering/Ordering.API/Startup.cs | 23 +++++++++---------- .../Ordering.FunctionalTests.csproj | 3 +-- .../OrderingTestStartup.cs | 12 +++++++++- .../Ordering.FunctionalTests/appsettings.json | 3 ++- src/_build/dependencies.props | 1 + 7 files changed, 30 insertions(+), 16 deletions(-) diff --git a/src/Services/Ordering/Ordering.API/Application/Commands/CancelOrderCommand.cs b/src/Services/Ordering/Ordering.API/Application/Commands/CancelOrderCommand.cs index 0672807f3..c2a1c2be5 100644 --- a/src/Services/Ordering/Ordering.API/Application/Commands/CancelOrderCommand.cs +++ b/src/Services/Ordering/Ordering.API/Application/Commands/CancelOrderCommand.cs @@ -12,7 +12,10 @@ namespace Ordering.API.Application.Commands [DataMember] public int OrderNumber { get; private set; } + public CancelOrderCommand() + { + } public CancelOrderCommand(int orderNumber) { OrderNumber = orderNumber; diff --git a/src/Services/Ordering/Ordering.API/Ordering.API.csproj b/src/Services/Ordering/Ordering.API/Ordering.API.csproj index 4bd20f8a3..1b3c36daa 100644 --- a/src/Services/Ordering/Ordering.API/Ordering.API.csproj +++ b/src/Services/Ordering/Ordering.API/Ordering.API.csproj @@ -30,6 +30,7 @@ + diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index e8640489c..fca490f28 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -22,6 +22,7 @@ using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus; using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF; using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services; + using Microsoft.eShopOnContainers.Services.Ordering.API.Controllers; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; @@ -44,7 +45,7 @@ public IConfiguration Configuration { get; } - public IServiceProvider ConfigureServices(IServiceCollection services) + public virtual IServiceProvider ConfigureServices(IServiceCollection services) { services.AddApplicationInsights(Configuration) .AddCustomMvc() @@ -81,9 +82,9 @@ app.UseCors("CorsPolicy"); + app.UseRouting(); ConfigureAuth(app); - app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); @@ -149,16 +150,14 @@ { // Add framework services. services.AddControllers(options => - { - options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - }); - //services.AddMvc(options => - // { - // options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - // }) - // .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) - // .AddControllersAsServices(); //Injecting Controllers themselves thru DI - // //For further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services + { + options.Filters.Add(typeof(HttpGlobalExceptionFilter)); + }) + // Added for functional tests + .AddApplicationPart(typeof(OrdersController).Assembly) + .AddNewtonsoftJson() + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) + ; services.AddCors(options => { diff --git a/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj b/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj index 5acad11ca..17845a375 100644 --- a/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj +++ b/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj @@ -17,8 +17,7 @@ - - + diff --git a/src/Services/Ordering/Ordering.FunctionalTests/OrderingTestStartup.cs b/src/Services/Ordering/Ordering.FunctionalTests/OrderingTestStartup.cs index d68dd7c3a..9d1975cb7 100644 --- a/src/Services/Ordering/Ordering.FunctionalTests/OrderingTestStartup.cs +++ b/src/Services/Ordering/Ordering.FunctionalTests/OrderingTestStartup.cs @@ -1,6 +1,9 @@ -using Microsoft.AspNetCore.Builder; +using System; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Routing; using Microsoft.eShopOnContainers.Services.Ordering.API; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; namespace Ordering.FunctionalTests { @@ -10,6 +13,13 @@ namespace Ordering.FunctionalTests { } + public override IServiceProvider ConfigureServices(IServiceCollection services) + { + // Added to avoid the Authorize data annotation in test environment. + // Property "SuppressCheckForUnhandledSecurityMetadata" in appsettings.json + services.Configure(Configuration); + return base.ConfigureServices(services); + } protected override void ConfigureAuth(IApplicationBuilder app) { if (Configuration["isTest"] == bool.TrueString.ToLowerInvariant()) diff --git a/src/Services/Ordering/Ordering.FunctionalTests/appsettings.json b/src/Services/Ordering/Ordering.FunctionalTests/appsettings.json index 70f1af3c0..07bb1638a 100644 --- a/src/Services/Ordering/Ordering.FunctionalTests/appsettings.json +++ b/src/Services/Ordering/Ordering.FunctionalTests/appsettings.json @@ -6,5 +6,6 @@ "EventBusConnection": "localhost", "CheckUpdateTime": "30000", "GracePeriodTime": "1", - "SubscriptionClientName": "Ordering" + "SubscriptionClientName": "Ordering", + "SuppressCheckForUnhandledSecurityMetadata":true } diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 7f81abf62..b83d987cc 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -86,6 +86,7 @@ 2.9.0-beta2 4.10.1 12.0.2 + 3.0.0-preview7.19365.7 12.0.1 6.0.1 3.0.0-preview3.4 From 76cb5c5e795a69ca003044ebfcddfddc73e34dfa Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 31 Jul 2019 09:13:14 +0200 Subject: [PATCH 038/113] add comment --- src/Services/Location/Locations.API/Startup.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Services/Location/Locations.API/Startup.cs b/src/Services/Location/Locations.API/Startup.cs index 5deaae52d..4f79b8977 100644 --- a/src/Services/Location/Locations.API/Startup.cs +++ b/src/Services/Location/Locations.API/Startup.cs @@ -48,6 +48,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }) + // Added for functional tests .AddApplicationPart(typeof(LocationsController).Assembly) .AddNewtonsoftJson(); From 267a2f5e4805170ca62bf1acd1fa863bb6f699d6 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Wed, 31 Jul 2019 12:05:11 +0200 Subject: [PATCH 039/113] fix deserialize error --- src/Services/Basket/Basket.API/Model/CustomerBasket.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Services/Basket/Basket.API/Model/CustomerBasket.cs b/src/Services/Basket/Basket.API/Model/CustomerBasket.cs index 3dd034f6c..b075f3150 100644 --- a/src/Services/Basket/Basket.API/Model/CustomerBasket.cs +++ b/src/Services/Basket/Basket.API/Model/CustomerBasket.cs @@ -4,8 +4,14 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Model { public class CustomerBasket { - public string BuyerId { get; set; } - public List Items { get; set; } + public string BuyerId { get; set; } + + public List Items { get; set; } + + public CustomerBasket() + { + + } public CustomerBasket(string customerId) { From 8fbc266fb9bf204b9fc9757a135fe41608ae354b Mon Sep 17 00:00:00 2001 From: ericuss Date: Thu, 1 Aug 2019 09:49:08 +0200 Subject: [PATCH 040/113] Migrated --- src/Services/Basket/Basket.API/Startup.cs | 13 ++++++++----- .../Base/BasketTestStartup.cs | 13 ++++++++++++- .../Basket.FunctionalTests.csproj | 3 +-- .../Basket/Basket.FunctionalTests/appsettings.json | 3 ++- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index 098428ad9..2533f31e5 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -15,6 +15,7 @@ using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ; using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus; +using Microsoft.eShopOnContainers.Services.Basket.API.Controllers; using Microsoft.eShopOnContainers.Services.Basket.API.Infrastructure.Repositories; using Microsoft.eShopOnContainers.Services.Basket.API.IntegrationEvents.EventHandling; using Microsoft.eShopOnContainers.Services.Basket.API.IntegrationEvents.Events; @@ -44,16 +45,18 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. - public IServiceProvider ConfigureServices(IServiceCollection services) + public virtual IServiceProvider ConfigureServices(IServiceCollection services) { RegisterAppInsights(services); services.AddControllers(options => - { - options.Filters.Add(typeof(HttpGlobalExceptionFilter)); - options.Filters.Add(typeof(ValidateModelStateFilter)); + { + options.Filters.Add(typeof(HttpGlobalExceptionFilter)); + options.Filters.Add(typeof(ValidateModelStateFilter)); - }).AddNewtonsoftJson(); + }) // Added for functional tests + .AddApplicationPart(typeof(BasketController).Assembly) + .AddNewtonsoftJson(); services.AddSwaggerGen(options => { diff --git a/src/Services/Basket/Basket.FunctionalTests/Base/BasketTestStartup.cs b/src/Services/Basket/Basket.FunctionalTests/Base/BasketTestStartup.cs index 4d77f6dc5..cb8ec8641 100644 --- a/src/Services/Basket/Basket.FunctionalTests/Base/BasketTestStartup.cs +++ b/src/Services/Basket/Basket.FunctionalTests/Base/BasketTestStartup.cs @@ -1,6 +1,9 @@ -using Microsoft.AspNetCore.Builder; +using System; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Routing; using Microsoft.eShopOnContainers.Services.Basket.API; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; namespace Basket.FunctionalTests.Base { @@ -10,6 +13,14 @@ namespace Basket.FunctionalTests.Base { } + public override IServiceProvider ConfigureServices(IServiceCollection services) + { + // Added to avoid the Authorize data annotation in test environment. + // Property "SuppressCheckForUnhandledSecurityMetadata" in appsettings.json + services.Configure(Configuration); + return base.ConfigureServices(services); + } + protected override void ConfigureAuth(IApplicationBuilder app) { if (Configuration["isTest"] == bool.TrueString.ToLowerInvariant()) diff --git a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj index 168176aaf..269a133f2 100644 --- a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj +++ b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj @@ -16,8 +16,7 @@ - - + diff --git a/src/Services/Basket/Basket.FunctionalTests/appsettings.json b/src/Services/Basket/Basket.FunctionalTests/appsettings.json index 5e8dbc02e..3f882d1bc 100644 --- a/src/Services/Basket/Basket.FunctionalTests/appsettings.json +++ b/src/Services/Basket/Basket.FunctionalTests/appsettings.json @@ -11,5 +11,6 @@ "ConnectionString": "127.0.0.1", "isTest": "true", "EventBusConnection": "localhost", - "SubscriptionClientName": "Basket" + "SubscriptionClientName": "Basket", + "SuppressCheckForUnhandledSecurityMetadata":true } From 92eef22187bb39ff5ab71e4809065085917042f6 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Thu, 1 Aug 2019 09:50:45 +0200 Subject: [PATCH 041/113] add nuget to ocelot --- src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj | 1 + src/ApiGateways/ApiGw-Base/Startup.cs | 1 + .../aggregator/Models/BasketData.cs | 11 ++++++---- .../aggregator/Models/CatalogItem.cs | 9 +------- .../Mobile.Bff.Shopping/aggregator/Startup.cs | 22 +++++-------------- .../aggregator/Models/BasketData.cs | 11 ++++++---- .../aggregator/Models/CatalogItem.cs | 9 +------- .../Web.Bff.Shopping/aggregator/Startup.cs | 1 + src/Web/WebMVC/Startup.cs | 4 ++-- src/_build/dependencies.props | 1 + 10 files changed, 27 insertions(+), 43 deletions(-) diff --git a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj index c7855f18e..eb2eacb0a 100644 --- a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj +++ b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj @@ -10,6 +10,7 @@ + diff --git a/src/ApiGateways/ApiGw-Base/Startup.cs b/src/ApiGateways/ApiGw-Base/Startup.cs index f4b7eaff7..8d52851b4 100644 --- a/src/ApiGateways/ApiGw-Base/Startup.cs +++ b/src/ApiGateways/ApiGw-Base/Startup.cs @@ -92,6 +92,7 @@ namespace OcelotApiGw app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapControllers(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/BasketData.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/BasketData.cs index 1b9348c44..302f6bd32 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/BasketData.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/BasketData.cs @@ -1,15 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System.Collections.Generic; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models { public class BasketData { public string BuyerId { get; set; } + public List Items { get; set; } + public BasketData() + { + + } + public BasketData(string buyerId) { BuyerId = buyerId; diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/CatalogItem.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/CatalogItem.cs index 25f766719..603c70bd7 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/CatalogItem.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/CatalogItem.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models +namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models { public class CatalogItem { @@ -13,8 +8,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models public decimal Price { get; set; } - public string PictureUri { get; set; } - } } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index 0c690bbcc..986973f93 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Filters.Basket.API.Infrastructure.Filters; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastructure; @@ -46,7 +45,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator .AddUrlGroup(new Uri(Configuration["PaymentUrlHC"]), name: "paymentapi-check", tags: new string[] { "paymentapi" }) .AddUrlGroup(new Uri(Configuration["LocationUrlHC"]), name: "locationapi-check", tags: new string[] { "locationapi" }); - services.AddCustomMvc(Configuration) + services.AddCustomRouting(Configuration) .AddCustomAuthentication(Configuration) .AddDevspaces() .AddHttpServices(); @@ -77,12 +76,13 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator app.UseHsts(); } - app.UseAuthentication(); app.UseHttpsRedirection(); app.UseRouting(); + app.UseAuthentication(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -108,14 +108,11 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator public static class ServiceCollectionExtensions { - public static IServiceCollection AddCustomMvc(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddCustomRouting(this IServiceCollection services, IConfiguration configuration) { services.AddOptions(); services.Configure(configuration.GetSection("urls")); - - services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); - + services.AddControllers().AddNewtonsoftJson(); services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); @@ -174,15 +171,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator options.Authority = identityUrl; options.RequireHttpsMetadata = false; options.Audience = "mobileshoppingagg"; - options.Events = new JwtBearerEvents() - { - OnAuthenticationFailed = async ctx => - { - }, - OnTokenValidated = async ctx => - { - } - }; }); return services; diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/BasketData.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/BasketData.cs index 01831a5c9..d29afb5c6 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/BasketData.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/BasketData.cs @@ -1,15 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System.Collections.Generic; namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models { public class BasketData { public string BuyerId { get; set; } + public List Items { get; set; } + public BasketData() + { + + } + public BasketData(string buyerId) { BuyerId = buyerId; diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/CatalogItem.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/CatalogItem.cs index c6085f934..43e8e1cd1 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/CatalogItem.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/CatalogItem.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models +namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models { public class CatalogItem { @@ -13,8 +8,6 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models public decimal Price { get; set; } - public string PictureUri { get; set; } - } } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index 9edbf2815..0b7790e36 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -82,6 +82,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, diff --git a/src/Web/WebMVC/Startup.cs b/src/Web/WebMVC/Startup.cs index b250c365c..014dca9f6 100644 --- a/src/Web/WebMVC/Startup.cs +++ b/src/Web/WebMVC/Startup.cs @@ -81,16 +81,16 @@ namespace Microsoft.eShopOnContainers.WebMVC app.UseMiddleware(); } - app.UseAuthentication(); - WebContextSeed.Seed(app, env, loggerFactory); app.UseHttpsRedirection(); app.UseRouting(); + app.UseAuthentication(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Catalog}/{action=Index}/{id?}"); endpoints.MapControllerRoute("defaultError", "{controller=Error}/{action=Error}"); + endpoints.MapControllers(); endpoints.MapHealthChecks("/liveness", new HealthCheckOptions { Predicate = r => r.Name.Contains("self") diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index b83d987cc..4de3340c6 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -40,6 +40,7 @@ 5.2.7 15.9.20 1.0.172 + 3.0.0-preview4-19123-01 1.0.2105168 3.0.0-preview6-19319-03 5.1.0 From cb942598c8f593a5d9dd18be4ef0bf8d0028dc8a Mon Sep 17 00:00:00 2001 From: ericuss Date: Thu, 1 Aug 2019 11:04:54 +0200 Subject: [PATCH 042/113] Migrate catalog functional tests --- .../Extensions/WebHostExtensions.cs | 80 +++++++++++++++++++ src/Services/Catalog/Catalog.API/Program.cs | 1 - src/Services/Catalog/Catalog.API/Startup.cs | 3 +- .../Catalog.FunctionalTests.csproj | 2 +- .../CatalogScenarioBase.cs | 9 ++- 5 files changed, 90 insertions(+), 5 deletions(-) create mode 100644 src/Services/Catalog/Catalog.API/Extensions/WebHostExtensions.cs diff --git a/src/Services/Catalog/Catalog.API/Extensions/WebHostExtensions.cs b/src/Services/Catalog/Catalog.API/Extensions/WebHostExtensions.cs new file mode 100644 index 000000000..b7a982b2e --- /dev/null +++ b/src/Services/Catalog/Catalog.API/Extensions/WebHostExtensions.cs @@ -0,0 +1,80 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Polly; +using System.Data.SqlClient; +using Microsoft.AspNetCore.Hosting; + +namespace Catalog.API.Extensions +{ + public static class WebHostExtensions + { + public static bool IsInKubernetes(this IWebHost host) + { + var cfg = host.Services.GetService(); + var orchestratorType = cfg.GetValue("OrchestratorType"); + return orchestratorType?.ToUpper() == "K8S"; + } + + public static IWebHost MigrateDbContext(this IWebHost host, Action seeder) where TContext : DbContext + { + var underK8s = host.IsInKubernetes(); + + using (var scope = host.Services.CreateScope()) + { + var services = scope.ServiceProvider; + + var logger = services.GetRequiredService>(); + + var context = services.GetService(); + + try + { + logger.LogInformation("Migrating database associated with context {DbContextName}", typeof(TContext).Name); + + if (underK8s) + { + InvokeSeeder(seeder, context, services); + } + else + { + var retry = Policy.Handle() + .WaitAndRetry(new TimeSpan[] + { + TimeSpan.FromSeconds(3), + TimeSpan.FromSeconds(5), + TimeSpan.FromSeconds(8), + }); + + //if the sql server container is not created on run docker compose this + //migration can't fail for network related exception. The retry options for DbContext only + //apply to transient exceptions + // Note that this is NOT applied when running some orchestrators (let the orchestrator to recreate the failing service) + retry.Execute(() => InvokeSeeder(seeder, context, services)); + } + + logger.LogInformation("Migrated database associated with context {DbContextName}", typeof(TContext).Name); + } + catch (Exception ex) + { + logger.LogError(ex, "An error occurred while migrating the database used on context {DbContextName}", typeof(TContext).Name); + if (underK8s) + { + throw; // Rethrow under k8s because we rely on k8s to re-run the pod + } + } + } + + return host; + } + + private static void InvokeSeeder(Action seeder, TContext context, IServiceProvider services) + where TContext : DbContext + { + context.Database.Migrate(); + seeder(context, services); + } + } +} diff --git a/src/Services/Catalog/Catalog.API/Program.cs b/src/Services/Catalog/Catalog.API/Program.cs index 39f3643d8..d24f976f9 100644 --- a/src/Services/Catalog/Catalog.API/Program.cs +++ b/src/Services/Catalog/Catalog.API/Program.cs @@ -68,7 +68,6 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API private static IHostBuilder CreateHostBuilder(IConfiguration configuration, string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices(services => services.AddAutofac()) - .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(builder => { builder.CaptureStartupErrors(false) diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 9dcf81f01..64441f9ea 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -44,7 +44,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API public IConfiguration Configuration { get; } - public void ConfigureServices(IServiceCollection services) + public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddAppInsight(Configuration) .AddGrpc().Services @@ -59,6 +59,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API var container = new ContainerBuilder(); container.Populate(services); + return new AutofacServiceProvider(container.Build()); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) diff --git a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj index a679d5d35..9db9a3c37 100644 --- a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj +++ b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj @@ -33,7 +33,7 @@ - + diff --git a/src/Services/Catalog/Catalog.FunctionalTests/CatalogScenarioBase.cs b/src/Services/Catalog/Catalog.FunctionalTests/CatalogScenarioBase.cs index 46bdb07d1..6a8cbd72f 100644 --- a/src/Services/Catalog/Catalog.FunctionalTests/CatalogScenarioBase.cs +++ b/src/Services/Catalog/Catalog.FunctionalTests/CatalogScenarioBase.cs @@ -1,3 +1,5 @@ +using Autofac.Extensions.DependencyInjection; +using Catalog.API.Extensions; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF; @@ -5,6 +7,7 @@ using Microsoft.eShopOnContainers.Services.Catalog.API; using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System.IO; @@ -25,14 +28,16 @@ namespace Catalog.FunctionalTests { cb.AddJsonFile("appsettings.json", optional: false) .AddEnvironmentVariables(); - }).UseStartup(); + }) + .UseStartup(); + var testServer = new TestServer(hostBuilder); testServer.Host .MigrateDbContext((context, services) => { - var env = services.GetService(); + var env = services.GetService(); var settings = services.GetService>(); var logger = services.GetService>(); From 1c88396c99f12836eb47f3d993434f1ff784fca7 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Fri, 2 Aug 2019 12:26:13 +0200 Subject: [PATCH 043/113] return ocelote to 2.2 for incompatibility of 3.0 --- src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj | 19 +++++++++--------- src/ApiGateways/ApiGw-Base/Startup.cs | 20 ++++++++----------- .../Mobile.Bff.Shopping/aggregator/Startup.cs | 3 ++- .../Web.Bff.Shopping/aggregator/Startup.cs | 3 ++- 4 files changed, 21 insertions(+), 24 deletions(-) diff --git a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj index eb2eacb0a..442fa36a3 100644 --- a/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj +++ b/src/ApiGateways/ApiGw-Base/OcelotApiGw.csproj @@ -1,19 +1,18 @@  - $(NetCoreTargetVersion) + netcoreapp2.2 $(LangVersion) - - - - - - - - - + + + + + + + + diff --git a/src/ApiGateways/ApiGw-Base/Startup.cs b/src/ApiGateways/ApiGw-Base/Startup.cs index 8d52851b4..be845edca 100644 --- a/src/ApiGateways/ApiGw-Base/Startup.cs +++ b/src/ApiGateways/ApiGw-Base/Startup.cs @@ -89,19 +89,15 @@ namespace OcelotApiGw app.UseDeveloperExceptionPage(); } - app.UseRouting(); - app.UseEndpoints(endpoints => + app.UseHealthChecks("/hc", new HealthCheckOptions() { - endpoints.MapControllers(); - endpoints.MapHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - endpoints.MapHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + + app.UseHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") }); app.UseCors("CorsPolicy"); diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index 986973f93..602477dde 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -50,7 +50,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator .AddDevspaces() .AddHttpServices(); - services.AddControllers(); + services.AddControllers().AddNewtonsoftJson(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -79,6 +79,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); + app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index 0b7790e36..257334aa3 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -51,7 +51,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator .AddDevspaces() .AddApplicationServices(); - services.AddControllers(); + services.AddControllers().AddNewtonsoftJson(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -77,6 +77,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator } app.UseAuthentication(); + app.UseAuthorization(); app.UseHttpsRedirection(); app.UseRouting(); app.UseEndpoints(endpoints => From 7fba79b048f7381ed3a776107869fd791444966f Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Fri, 2 Aug 2019 14:20:25 +0200 Subject: [PATCH 044/113] change ihost for iwebhost --- src/Services/Catalog/Catalog.API/Program.cs | 48 ++++++++++----------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/src/Services/Catalog/Catalog.API/Program.cs b/src/Services/Catalog/Catalog.API/Program.cs index d24f976f9..d28ee5a54 100644 --- a/src/Services/Catalog/Catalog.API/Program.cs +++ b/src/Services/Catalog/Catalog.API/Program.cs @@ -33,7 +33,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API try { Log.Information("Configuring web host ({ApplicationContext})...", AppName); - var host = CreateHostBuilder(configuration, args).Build(); + var host = CreateHostBuilder(configuration, args); Log.Information("Applying migrations ({ApplicationContext})...", AppName); host.MigrateDbContext((context, services) => @@ -64,33 +64,29 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API } } - - private static IHostBuilder CreateHostBuilder(IConfiguration configuration, string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureServices(services => services.AddAutofac()) - .ConfigureWebHostDefaults(builder => + private static IWebHost CreateHostBuilder(IConfiguration configuration, string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseConfiguration(configuration) + .CaptureStartupErrors(false) + .ConfigureKestrel(options => { - builder.CaptureStartupErrors(false) - .UseConfiguration(configuration) - .ConfigureKestrel(options => + var ports = GetDefinedPorts(configuration); + options.Listen(IPAddress.Any, ports.httpPort, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http1AndHttp2; + }); + options.Listen(IPAddress.Any, ports.grpcPort, listenOptions => { - var ports = GetDefinedPorts(configuration); - options.Listen(IPAddress.Any, ports.httpPort, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http1AndHttp2; - }); - options.Listen(IPAddress.Any, ports.grpcPort, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http2; - }); - - }) - .UseStartup() - .UseApplicationInsights() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseWebRoot("Pics") - .UseSerilog(); - }); + listenOptions.Protocols = HttpProtocols.Http2; + }); + + }) + .UseStartup() + .UseApplicationInsights() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseWebRoot("Pics") + .UseSerilog() + .Build(); private static Serilog.ILogger CreateSerilogLogger(IConfiguration configuration) { From aedd0e38e9fc9ffdde6feadb6e7752d4105ecb32 Mon Sep 17 00:00:00 2001 From: ericuss Date: Mon, 5 Aug 2019 10:20:20 +0200 Subject: [PATCH 045/113] partial checkin --- .../WebHostExtensions.cs | 9 ++- .../Infrastructure/MarketingContext.cs | 15 +++- .../Marketing/Marketing.API/Startup.cs | 78 +++++++++++-------- .../Marketing.FunctionalTests.csproj | 3 +- .../MarketingTestStartup.cs | 13 +++- .../appsettings.json | 3 +- 6 files changed, 81 insertions(+), 40 deletions(-) diff --git a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs index 17f030e02..e6e1e22a1 100644 --- a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs +++ b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs @@ -39,8 +39,15 @@ namespace Microsoft.AspNetCore.Hosting } else { + var retries = 10; var retry = Policy.Handle() - .WaitAndRetry(10, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); + .WaitAndRetry( + retryCount: retries, + sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), + onRetry: (exception, timeSpan, retry, ctx) => + { + logger.LogWarning(exception, "[{prefix}] Exception {ExceptionType} with message {Message} detected on attempt {retry} of {retries}", nameof(TContext), exception.GetType().Name, exception.Message, retry, retries); + }); //if the sql server container is not created on run docker compose this //migration can't fail for network related exception. The retry options for DbContext only diff --git a/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs b/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs index dae9b5bb4..c4a803212 100644 --- a/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs +++ b/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs @@ -1,9 +1,12 @@ namespace Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure { + using System; + using System.IO; using EntityConfigurations; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.eShopOnContainers.Services.Marketing.API.Model; + using Microsoft.Extensions.Configuration; public class MarketingContext : DbContext { @@ -27,9 +30,17 @@ { public MarketingContext CreateDbContext(string[] args) { + IConfigurationRoot configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) + .AddEnvironmentVariables() + .Build(); + var connectionString = configuration["ConnectionString"]; + Console.WriteLine(" -- Connection string"); + Console.WriteLine(connectionString); var optionsBuilder = new DbContextOptionsBuilder() - .UseSqlServer("Server=.;Initial Catalog=Microsoft.eShopOnContainers.Services.MarketingDb;Integrated Security=true"); - + .UseSqlServer(connectionString); + // .UseSqlServer("Server=.;Initial Catalog=Microsoft.eShopOnContainers.Services.MarketingDb;Integrated Security=true"); return new MarketingContext(optionsBuilder.Options); } } diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index c3ae02e23..ff6fdd43a 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -23,7 +23,9 @@ using Marketing.API.IntegrationEvents.Handlers; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Diagnostics.HealthChecks; + using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore.Diagnostics; + using Microsoft.eShopOnContainers.Services.Marketing.API.Controllers; using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Middlewares; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.OpenApi.Models; @@ -44,13 +46,18 @@ // This method gets called by the runtime. Use this method to add services to the container. - public IServiceProvider ConfigureServices(IServiceCollection services) + public virtual IServiceProvider ConfigureServices(IServiceCollection services) { RegisterAppInsights(services); // Add framework services. services.AddCustomHealthCheck(Configuration); - services.AddControllers().AddNewtonsoftJson(); + services + .AddControllers() + // Added for functional tests + .AddApplicationPart(typeof(LocationsController).Assembly) + .AddNewtonsoftJson() + .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.Configure(Configuration); ConfigureAuthService(services); @@ -117,36 +124,8 @@ } // Add framework services. - services.AddSwaggerGen(options => - { - options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = "eShopOnContainers - Marketing HTTP API", - Version = "v1", - Description = "The Marketing Service HTTP API" - }); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows() - { - Implicit = new OpenApiOAuthFlow() - { - AuthorizationUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), - TokenUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/token"), - Scopes = new Dictionary() - { - { "marketing", "Marketing API" } - } - } - } - }); - - options.OperationFilter(); - }); + AddCustomSwagger(services); services.AddCors(options => { options.AddPolicy("CorsPolicy", @@ -186,10 +165,10 @@ } app.UseCors("CorsPolicy"); + app.UseRouting(); ConfigureAuth(app); - app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); @@ -216,6 +195,39 @@ ConfigureEventBus(app); } + private void AddCustomSwagger(IServiceCollection services) + { + services.AddSwaggerGen(options => + { + options.DescribeAllEnumsAsStrings(); + options.SwaggerDoc("v1", new OpenApiInfo + { + Title = "eShopOnContainers - Marketing HTTP API", + Version = "v1", + Description = "The Marketing Service HTTP API" + }); + + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme + { + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() + { + Implicit = new OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{Configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "marketing", "Marketing API" } + } + } + } + }); + + options.OperationFilter(); + }); + } + private void RegisterAppInsights(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration); @@ -225,7 +237,7 @@ private void ConfigureAuthService(IServiceCollection services) { // prevent from mapping "sub" claim to nameidentifier. - JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); + JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); services.AddAuthentication(options => { diff --git a/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj b/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj index eddf06086..41deec5d4 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj +++ b/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj @@ -17,8 +17,7 @@ - - + diff --git a/src/Services/Marketing/Marketing.FunctionalTests/MarketingTestStartup.cs b/src/Services/Marketing/Marketing.FunctionalTests/MarketingTestStartup.cs index e227deff6..87d0fb991 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/MarketingTestStartup.cs +++ b/src/Services/Marketing/Marketing.FunctionalTests/MarketingTestStartup.cs @@ -1,6 +1,9 @@ -using Microsoft.AspNetCore.Builder; +using System; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Routing; using Microsoft.eShopOnContainers.Services.Marketing.API; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; namespace Marketing.FunctionalTests { @@ -10,6 +13,14 @@ namespace Marketing.FunctionalTests { } + public override IServiceProvider ConfigureServices(IServiceCollection services) + { + // Added to avoid the Authorize data annotation in test environment. + // Property "SuppressCheckForUnhandledSecurityMetadata" in appsettings.json + services.Configure(Configuration); + return base.ConfigureServices(services); + } + protected override void ConfigureAuth(IApplicationBuilder app) { if (Configuration["isTest"] == bool.TrueString.ToLowerInvariant()) diff --git a/src/Services/Marketing/Marketing.FunctionalTests/appsettings.json b/src/Services/Marketing/Marketing.FunctionalTests/appsettings.json index 4a57bb0f5..11a1e090d 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/appsettings.json +++ b/src/Services/Marketing/Marketing.FunctionalTests/appsettings.json @@ -6,5 +6,6 @@ "isTest": "true", "EventBusConnection": "localhost", "PicBaseUrl": "http://localhost:5110/api/v1/campaigns/[0]/pic/", - "SubscriptionClientName": "Marketing" + "SubscriptionClientName": "Marketing", + "SuppressCheckForUnhandledSecurityMetadata":true } From 44af7aa8d267c9c59d87c278c8a518c44a50d9f3 Mon Sep 17 00:00:00 2001 From: ericuss Date: Mon, 5 Aug 2019 14:21:58 +0200 Subject: [PATCH 046/113] Partial checkin --- .../WebHostExtensions.cs | 62 +++++++++++++++++++ .../Infrastructure/MarketingContext.cs | 1 + .../CampaignScenarios.cs | 4 +- .../MarketingScenarioBase.cs | 34 +++++++++- 4 files changed, 97 insertions(+), 4 deletions(-) diff --git a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs index e6e1e22a1..2b7f661da 100644 --- a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs +++ b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs @@ -60,6 +60,7 @@ namespace Microsoft.AspNetCore.Hosting } catch (Exception ex) { + Console.WriteLine(ex.Message.ToString() + "An error occurred while migrating the database used on context {DbContextName}" + typeof(TContext).Name); logger.LogError(ex, "An error occurred while migrating the database used on context {DbContextName}", typeof(TContext).Name); if (underK8s) { @@ -71,11 +72,72 @@ namespace Microsoft.AspNetCore.Hosting return webHost; } + + public static IWebHost RemoveDbContext(this IWebHost webHost) where TContext : DbContext + { + var underK8s = webHost.IsInKubernetes(); + + using (var scope = webHost.Services.CreateScope()) + { + var services = scope.ServiceProvider; + var logger = services.GetRequiredService>(); + var context = services.GetService(); + + try + { + logger.LogInformation("Deleting the database associated with context {DbContextName}" + typeof(TContext).Name); + + if (underK8s) + { + InvokeRemover(context); + } + else + { + var retries = 10; + var retry = Policy.Handle() + .WaitAndRetry( + retryCount: retries, + sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), + onRetry: (exception, timeSpan, retry, ctx) => + { + Console.WriteLine(" --RETRYING Exception " + exception.Message.ToString()); + logger.LogWarning(exception, "[{prefix}] Exception {ExceptionType} with message {Message} detected on attempt {retry} of {retries}", nameof(TContext), exception.GetType().Name, exception.Message, retry, retries); + }); + + //if the sql server container is not created on run docker compose this + //migration can't fail for network related exception. The retry options for DbContext only + //apply to transient exceptions + // Note that this is NOT applied when running some orchestrators (let the orchestrator to recreate the failing service) + retry.Execute(() => InvokeRemover(context)); + } + + Console.WriteLine("Deleted database associated with context {DbContextName}", typeof(TContext).Name); + logger.LogInformation("Deleted database associated with context {DbContextName}", typeof(TContext).Name); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message.ToString() + "An error occurred while deleting the database used on context {DbContextName}" + typeof(TContext).Name); + logger.LogError(ex, "An error occurred while deleting the database used on context {DbContextName}", typeof(TContext).Name); + if (underK8s) + { + throw; // Rethrow under k8s because we rely on k8s to re-run the pod + } + } + } + + return webHost; + } + private static void InvokeSeeder(Action seeder, TContext context, IServiceProvider services) where TContext : DbContext { context.Database.Migrate(); seeder(context, services); } + private static void InvokeRemover(TContext context) + where TContext : DbContext + { + context.Database.EnsureDeleted(); + } } } diff --git a/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs b/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs index c4a803212..064a1c3e5 100644 --- a/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs +++ b/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs @@ -38,6 +38,7 @@ var connectionString = configuration["ConnectionString"]; Console.WriteLine(" -- Connection string"); Console.WriteLine(connectionString); + var optionsBuilder = new DbContextOptionsBuilder() .UseSqlServer(connectionString); // .UseSqlServer("Server=.;Initial Catalog=Microsoft.eShopOnContainers.Services.MarketingDb;Integrated Security=true"); diff --git a/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs b/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs index abeb4a504..f2643e998 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs +++ b/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs @@ -75,7 +75,7 @@ namespace Marketing.FunctionalTests var campaignResponse = await server.CreateClient() .PostAsync(Post.AddNewCampaign, content); - if (int.TryParse(campaignResponse.Headers.Location.Segments[4], out int id)) + if (int.TryParse(campaignResponse.Headers.Location.Segments[3], out int id)) { var response = await server.CreateClient() .DeleteAsync(Delete.CampaignBy(id)); @@ -99,7 +99,7 @@ namespace Marketing.FunctionalTests var campaignResponse = await server.CreateClient() .PostAsync(Post.AddNewCampaign, content); - if (int.TryParse(campaignResponse.Headers.Location.Segments[4], out int id)) + if (int.TryParse(campaignResponse.Headers.Location.Segments[3], out int id)) { fakeCampaignDto.Description = "FakeCampaignUpdatedDescription"; content = new StringContent(JsonConvert.SerializeObject(fakeCampaignDto), Encoding.UTF8, "application/json"); diff --git a/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs b/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs index 274db5f69..fdee81ce3 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs +++ b/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs @@ -1,11 +1,16 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using Microsoft.eShopOnContainers.Services.Marketing.API; using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; using System.IO; using System.Reflection; +using System.Threading; +using System.Threading.Tasks; namespace Marketing.FunctionalTests { @@ -15,29 +20,54 @@ namespace Marketing.FunctionalTests public TestServer CreateServer() { + + Console.WriteLine(" Creating test server"); var path = Assembly.GetAssembly(typeof(MarketingScenarioBase)) .Location; + Console.WriteLine(" Creating builder"); + var hostBuilder = new WebHostBuilder() .UseContentRoot(Path.GetDirectoryName(path)) .ConfigureAppConfiguration(cb => { - cb.AddJsonFile("appsettings.json", optional: false) + var h = cb.AddJsonFile("appsettings.json", optional: false) .AddEnvironmentVariables(); - }).UseStartup(); + }) + .CaptureStartupErrors(true) + .UseStartup(); + Console.WriteLine(" Created builder"); + var testServer = new TestServer(hostBuilder); + using (var scope = testServer.Services.CreateScope()) + { + var services = scope.ServiceProvider; + + var logger = services.GetRequiredService>(); + var settings = services.GetRequiredService>(); + logger.LogError("connectionString " + settings.Value.ConnectionString); + Console.WriteLine("connectionString " + settings.Value.ConnectionString); + } + testServer.Host + .RemoveDbContext() .MigrateDbContext((context, services) => { var logger = services.GetService>(); + logger.LogError("Migrating MarketingContextSeed"); new MarketingContextSeed() .SeedAsync(context, logger) .Wait(); }); + Console.WriteLine(" Thread to sleep"); + + Thread.Sleep(5000); + Console.WriteLine(" Thread after"); + return testServer; } From c52484859f724d0748ef23bbf49924869dfaf655 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Mon, 5 Aug 2019 15:03:57 +0200 Subject: [PATCH 047/113] change bff to 2.2 and fix mvc routing --- src/ApiGateways/ApiGw-Base/Dockerfile | 5 +- .../Mobile.Bff.Shopping/aggregator/Dockerfile | 4 +- .../Filters/AuthorizeCheckOperationFilter.cs | 19 ++-- .../Mobile.Shopping.HttpAggregator.csproj | 34 ++++++- .../Mobile.Bff.Shopping/aggregator/Startup.cs | 95 ++++++++++--------- .../Web.Bff.Shopping/aggregator/Dockerfile | 4 +- .../Filters/AuthorizeCheckOperationFilter.cs | 19 ++-- .../Web.Bff.Shopping/aggregator/Startup.cs | 60 +++++------- .../Web.Shopping.HttpAggregator.csproj | 33 ++++++- .../Devspaces.Support.csproj | 2 +- .../WebMVC/Controllers/AccountController.cs | 5 +- .../WebMVC/Controllers/CampaignsController.cs | 2 +- src/Web/WebMVC/Controllers/CartController.cs | 2 +- src/Web/WebMVC/Controllers/OrderController.cs | 2 +- .../Controllers/OrderManagementController.cs | 2 +- src/Web/WebMVC/Startup.cs | 34 ++++--- 16 files changed, 185 insertions(+), 137 deletions(-) diff --git a/src/ApiGateways/ApiGw-Base/Dockerfile b/src/ApiGateways/ApiGw-Base/Dockerfile index 0d66ada6b..7a5bb928c 100644 --- a/src/ApiGateways/ApiGw-Base/Dockerfile +++ b/src/ApiGateways/ApiGw-Base/Dockerfile @@ -1,10 +1,9 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build +FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build WORKDIR /src - COPY scripts scripts/ COPY src/ApiGateways/*/*.csproj /src/csproj-files/ diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile index 3d89c9b27..9b03eccbd 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build +FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs index 3b8298bfe..21997360b 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs @@ -1,7 +1,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Filters { using Microsoft.AspNetCore.Authorization; - using Microsoft.OpenApi.Models; + using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using System.Linq; @@ -10,7 +10,7 @@ { public class AuthorizeCheckOperationFilter : IOperationFilter { - public void Apply(OpenApiOperation operation, OperationFilterContext context) + public void Apply(Operation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || @@ -18,19 +18,14 @@ if (!hasAuthorize) return; - operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" }); + operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); - var oAuthScheme = new OpenApiSecurityScheme + operation.Security = new List>> { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } - }; - - operation.Security = new List - { - new OpenApiSecurityRequirement + new Dictionary> { - [ oAuthScheme ] = new [] { "Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator" } + { "oauth2", new [] { "Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator" } } } }; } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj index fdf05ab76..57efd4a9f 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj @@ -1,4 +1,4 @@ - + + + + + netcoreapp2.2 + Mobile.Shopping.HttpAggregator + Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator + ..\..\..\docker-compose.dcproj + $(LangVersion) + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index 602477dde..c60cb787a 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Filters.Basket.API.Infrastructure.Filters; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastructure; @@ -13,9 +14,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; -using Microsoft.OpenApi.Models; using Polly; using Polly.Extensions.Http; +using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; @@ -45,12 +46,10 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator .AddUrlGroup(new Uri(Configuration["PaymentUrlHC"]), name: "paymentapi-check", tags: new string[] { "paymentapi" }) .AddUrlGroup(new Uri(Configuration["LocationUrlHC"]), name: "locationapi-check", tags: new string[] { "locationapi" }); - services.AddCustomRouting(Configuration) + services.AddCustomMvc(Configuration) .AddCustomAuthentication(Configuration) .AddDevspaces() .AddHttpServices(); - - services.AddControllers().AddNewtonsoftJson(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -64,6 +63,17 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator app.UsePathBase(pathBase); } + app.UseHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + + app.UseHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + app.UseCors("CorsPolicy"); if (env.IsDevelopment()) @@ -76,68 +86,52 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator app.UseHsts(); } - app.UseHttpsRedirection(); - app.UseRouting(); app.UseAuthentication(); - app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - endpoints.MapControllers(); - endpoints.MapHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - endpoints.MapHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - }); + app.UseHttpsRedirection(); + app.UseMvc(); app.UseSwagger().UseSwaggerUI(c => - { - c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1"); - - c.OAuthClientId("Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregatorwaggerui"); - c.OAuthClientSecret(string.Empty); - c.OAuthRealm(string.Empty); - c.OAuthAppName("Purchase BFF Swagger UI"); - }); + { + c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1"); + + c.OAuthClientId("Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregatorwaggerui"); + c.OAuthClientSecret(string.Empty); + c.OAuthRealm(string.Empty); + c.OAuthAppName("Purchase BFF Swagger UI"); + }); } } public static class ServiceCollectionExtensions { - public static IServiceCollection AddCustomRouting(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddCustomMvc(this IServiceCollection services, IConfiguration configuration) { services.AddOptions(); services.Configure(configuration.GetSection("urls")); - services.AddControllers().AddNewtonsoftJson(); + + services.AddMvc() + .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new OpenApiInfo + options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { - Title = "eShopOnContainers - Shopping Aggregator for Mobile Clients", + Title = "Shopping Aggregator for Mobile Clients", Version = "v1", - Description = "Shopping Aggregator for Mobile Clients" + Description = "Shopping Aggregator for Mobile Clients", + TermsOfService = "Terms Of Service" }); - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme + options.AddSecurityDefinition("oauth2", new OAuth2Scheme { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows() + Type = "oauth2", + Flow = "implicit", + AuthorizationUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize", + TokenUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/token", + Scopes = new Dictionary() { - Implicit = new OpenApiOAuthFlow() - { - AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), - TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), - Scopes = new Dictionary() - { - { "marketing", "Marketing API" } - } - } + { "mobileshoppingagg", "Shopping Aggregator for Mobile Clients" } } }); @@ -172,6 +166,15 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator options.Authority = identityUrl; options.RequireHttpsMetadata = false; options.Audience = "mobileshoppingagg"; + options.Events = new JwtBearerEvents() + { + OnAuthenticationFailed = async ctx => + { + }, + OnTokenValidated = async ctx => + { + } + }; }); return services; diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile b/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile index 2a3b551a2..fbce2f0ab 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build +FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs index 45c191104..e93ec157c 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs @@ -1,7 +1,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Filters { using Microsoft.AspNetCore.Authorization; - using Microsoft.OpenApi.Models; + using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using System.Linq; @@ -10,7 +10,7 @@ { public class AuthorizeCheckOperationFilter : IOperationFilter { - public void Apply(OpenApiOperation operation, OperationFilterContext context) + public void Apply(Operation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || @@ -18,19 +18,14 @@ if (!hasAuthorize) return; - operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" }); + operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); - var oAuthScheme = new OpenApiSecurityScheme + operation.Security = new List>> { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } - }; - - operation.Security = new List - { - new OpenApiSecurityRequirement + new Dictionary> { - [ oAuthScheme ] = new [] { "Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator" } + { "oauth2", new [] { "Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator" } } } }; } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index 257334aa3..9b144db48 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -14,9 +14,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; -using Microsoft.OpenApi.Models; using Polly; using Polly.Extensions.Http; +using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; @@ -50,8 +50,6 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator .AddCustomAuthentication(Configuration) .AddDevspaces() .AddApplicationServices(); - - services.AddControllers().AddNewtonsoftJson(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -64,6 +62,17 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator app.UsePathBase(pathBase); } + app.UseHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + + app.UseHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + app.UseCors("CorsPolicy"); if (env.IsDevelopment()) @@ -77,23 +86,8 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator } app.UseAuthentication(); - app.UseAuthorization(); app.UseHttpsRedirection(); - app.UseRouting(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - endpoints.MapControllers(); - endpoints.MapHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - endpoints.MapHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - }); + app.UseMvc(); app.UseSwagger() .UseSwaggerUI(c => @@ -142,32 +136,28 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator services.Configure(configuration.GetSection("urls")); services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); + .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new OpenApiInfo + options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { - Title = "eShopOnContainers - Shopping Aggregator for Web Clients", + Title = "Shopping Aggregator for Web Clients", Version = "v1", - Description = "Shopping Aggregator for Web Clients" + Description = "Shopping Aggregator for Web Clients", + TermsOfService = "Terms Of Service" }); - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme + options.AddSecurityDefinition("oauth2", new OAuth2Scheme { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows() + Type = "oauth2", + Flow = "implicit", + AuthorizationUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize", + TokenUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/token", + Scopes = new Dictionary() { - Implicit = new OpenApiOAuthFlow() - { - AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), - TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), - Scopes = new Dictionary() - { - { "webshoppingagg", "Shopping Aggregator for Web Clients" } - } - } + { "webshoppingagg", "Shopping Aggregator for Web Clients" } } }); diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj index a3eaa1ae6..ef610d572 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj @@ -1,4 +1,4 @@ - + + + + + netcoreapp2.2 + Web.Shopping.HttpAggregator + Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator + ..\..\..\docker-compose.dcproj + $(LangVersion) + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj b/src/BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj index 05fc111a4..47c724f39 100644 --- a/src/BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj +++ b/src/BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj @@ -1,7 +1,7 @@  - $(NetStandardTargetVersion) + netstandard2.0 diff --git a/src/Web/WebMVC/Controllers/AccountController.cs b/src/Web/WebMVC/Controllers/AccountController.cs index de10770f5..8b82498ba 100644 --- a/src/Web/WebMVC/Controllers/AccountController.cs +++ b/src/Web/WebMVC/Controllers/AccountController.cs @@ -10,7 +10,7 @@ using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.WebMVC.Controllers { - [Authorize] + [Authorize(AuthenticationSchemes = "OpenIdConnect")] public class AccountController : Controller { private readonly ILogger _logger; @@ -20,8 +20,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } - [Authorize] - public async Task SignIn(string returnUrl) + [Authorize(AuthenticationSchemes = "OpenIdConnect")] public async Task SignIn(string returnUrl) { var user = User as ClaimsPrincipal; var token = await HttpContext.GetTokenAsync("access_token"); diff --git a/src/Web/WebMVC/Controllers/CampaignsController.cs b/src/Web/WebMVC/Controllers/CampaignsController.cs index d26e60f94..cf210318b 100644 --- a/src/Web/WebMVC/Controllers/CampaignsController.cs +++ b/src/Web/WebMVC/Controllers/CampaignsController.cs @@ -12,7 +12,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers using ViewModels; using ViewModels.Pagination; - [Authorize] + [Authorize(AuthenticationSchemes = "OpenIdConnect")] public class CampaignsController : Controller { private readonly ICampaignService _campaignService; diff --git a/src/Web/WebMVC/Controllers/CartController.cs b/src/Web/WebMVC/Controllers/CartController.cs index 30ac77e8b..6887c8d41 100644 --- a/src/Web/WebMVC/Controllers/CartController.cs +++ b/src/Web/WebMVC/Controllers/CartController.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.WebMVC.Controllers { - [Authorize] + [Authorize(AuthenticationSchemes = "OpenIdConnect")] public class CartController : Controller { private readonly IBasketService _basketSvc; diff --git a/src/Web/WebMVC/Controllers/OrderController.cs b/src/Web/WebMVC/Controllers/OrderController.cs index cb5234e3c..6249492da 100644 --- a/src/Web/WebMVC/Controllers/OrderController.cs +++ b/src/Web/WebMVC/Controllers/OrderController.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.WebMVC.Controllers { - [Authorize] + [Authorize(AuthenticationSchemes = "OpenIdConnect")] public class OrderController : Controller { private IOrderingService _orderSvc; diff --git a/src/Web/WebMVC/Controllers/OrderManagementController.cs b/src/Web/WebMVC/Controllers/OrderManagementController.cs index 7d61b0221..a488dc4ae 100644 --- a/src/Web/WebMVC/Controllers/OrderManagementController.cs +++ b/src/Web/WebMVC/Controllers/OrderManagementController.cs @@ -10,7 +10,7 @@ using Microsoft.AspNetCore.Authorization; namespace WebMVC.Controllers { - [Authorize] + [Authorize(AuthenticationSchemes = "OpenIdConnect")] public class OrderManagementController : Controller { private IOrderingService _orderSvc; diff --git a/src/Web/WebMVC/Startup.cs b/src/Web/WebMVC/Startup.cs index 014dca9f6..321e88548 100644 --- a/src/Web/WebMVC/Startup.cs +++ b/src/Web/WebMVC/Startup.cs @@ -38,21 +38,24 @@ namespace Microsoft.eShopOnContainers.WebMVC // This method gets called by the runtime. Use this method to add services to the IoC container. public void ConfigureServices(IServiceCollection services) { - services.AddAppInsight(Configuration) - .AddHealthChecks(Configuration) - .AddCustomMvc(Configuration) - .AddDevspaces() - .AddHttpClientServices(Configuration) - //.AddHttpClientLogging(Configuration) //Opt-in HttpClientLogging config - .AddCustomAuthentication(Configuration); - + services.AddControllersWithViews() + .Services + .AddAppInsight(Configuration) + .AddHealthChecks(Configuration) + .AddCustomMvc(Configuration) + .AddDevspaces() + .AddHttpClientServices(Configuration); + //.AddHttpClientLogging(Configuration) //Opt-in HttpClientLogging config + services.AddControllers(); + + services.AddCustomAuthentication(Configuration); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); + JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); //loggerFactory.AddAzureWebAppDiagnostics(); //loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); @@ -67,14 +70,15 @@ namespace Microsoft.eShopOnContainers.WebMVC } var pathBase = Configuration["PATH_BASE"]; + if (!string.IsNullOrEmpty(pathBase)) { loggerFactory.CreateLogger().LogDebug("Using PATH BASE '{PathBase}'", pathBase); app.UsePathBase(pathBase); } - app.UseSession(); app.UseStaticFiles(); + app.UseSession(); if (Configuration.GetValue("UseLoadTest")) { @@ -85,7 +89,10 @@ namespace Microsoft.eShopOnContainers.WebMVC app.UseHttpsRedirection(); app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Catalog}/{action=Index}/{id?}"); @@ -130,11 +137,8 @@ namespace Microsoft.eShopOnContainers.WebMVC { services.AddOptions(); services.Configure(configuration); - - services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); - services.AddSession(); + services.AddDistributedMemoryCache(); if (configuration.GetValue("IsClusterEnv") == bool.TrueString) { @@ -144,6 +148,7 @@ namespace Microsoft.eShopOnContainers.WebMVC }) .PersistKeysToRedis(ConnectionMultiplexer.Connect(configuration["DPConnectionString"]), "DataProtection-Keys"); } + return services; } @@ -258,7 +263,6 @@ namespace Microsoft.eShopOnContainers.WebMVC .HandleTransientHttpError() .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound) .WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); - } static IAsyncPolicy GetCircuitBreakerPolicy() { From 48bc95f88c576342f6ebe267c6684bc0dbaeac02 Mon Sep 17 00:00:00 2001 From: ericuss Date: Mon, 5 Aug 2019 16:17:18 +0200 Subject: [PATCH 048/113] Fix functional tests of Marketing --- .../WebHostExtensions.cs | 64 ------------------- .../Infrastructure/MarketingContext.cs | 5 +- .../CampaignScenarios.cs | 1 + .../MarketingScenarioBase.cs | 22 ------- .../UserLocationRoleScenarios.cs | 1 + 5 files changed, 3 insertions(+), 90 deletions(-) diff --git a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs index 2b7f661da..6316ae59d 100644 --- a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs +++ b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHostExtensions.cs @@ -24,9 +24,7 @@ namespace Microsoft.AspNetCore.Hosting using (var scope = webHost.Services.CreateScope()) { var services = scope.ServiceProvider; - var logger = services.GetRequiredService>(); - var context = services.GetService(); try @@ -60,7 +58,6 @@ namespace Microsoft.AspNetCore.Hosting } catch (Exception ex) { - Console.WriteLine(ex.Message.ToString() + "An error occurred while migrating the database used on context {DbContextName}" + typeof(TContext).Name); logger.LogError(ex, "An error occurred while migrating the database used on context {DbContextName}", typeof(TContext).Name); if (underK8s) { @@ -72,72 +69,11 @@ namespace Microsoft.AspNetCore.Hosting return webHost; } - - public static IWebHost RemoveDbContext(this IWebHost webHost) where TContext : DbContext - { - var underK8s = webHost.IsInKubernetes(); - - using (var scope = webHost.Services.CreateScope()) - { - var services = scope.ServiceProvider; - var logger = services.GetRequiredService>(); - var context = services.GetService(); - - try - { - logger.LogInformation("Deleting the database associated with context {DbContextName}" + typeof(TContext).Name); - - if (underK8s) - { - InvokeRemover(context); - } - else - { - var retries = 10; - var retry = Policy.Handle() - .WaitAndRetry( - retryCount: retries, - sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - onRetry: (exception, timeSpan, retry, ctx) => - { - Console.WriteLine(" --RETRYING Exception " + exception.Message.ToString()); - logger.LogWarning(exception, "[{prefix}] Exception {ExceptionType} with message {Message} detected on attempt {retry} of {retries}", nameof(TContext), exception.GetType().Name, exception.Message, retry, retries); - }); - - //if the sql server container is not created on run docker compose this - //migration can't fail for network related exception. The retry options for DbContext only - //apply to transient exceptions - // Note that this is NOT applied when running some orchestrators (let the orchestrator to recreate the failing service) - retry.Execute(() => InvokeRemover(context)); - } - - Console.WriteLine("Deleted database associated with context {DbContextName}", typeof(TContext).Name); - logger.LogInformation("Deleted database associated with context {DbContextName}", typeof(TContext).Name); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message.ToString() + "An error occurred while deleting the database used on context {DbContextName}" + typeof(TContext).Name); - logger.LogError(ex, "An error occurred while deleting the database used on context {DbContextName}", typeof(TContext).Name); - if (underK8s) - { - throw; // Rethrow under k8s because we rely on k8s to re-run the pod - } - } - } - - return webHost; - } - private static void InvokeSeeder(Action seeder, TContext context, IServiceProvider services) where TContext : DbContext { context.Database.Migrate(); seeder(context, services); } - private static void InvokeRemover(TContext context) - where TContext : DbContext - { - context.Database.EnsureDeleted(); - } } } diff --git a/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs b/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs index 064a1c3e5..e06106b5e 100644 --- a/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs +++ b/src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs @@ -35,13 +35,10 @@ .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables() .Build(); - var connectionString = configuration["ConnectionString"]; - Console.WriteLine(" -- Connection string"); - Console.WriteLine(connectionString); + var connectionString = configuration["ConnectionString"]; var optionsBuilder = new DbContextOptionsBuilder() .UseSqlServer(connectionString); - // .UseSqlServer("Server=.;Initial Catalog=Microsoft.eShopOnContainers.Services.MarketingDb;Integrated Security=true"); return new MarketingContext(optionsBuilder.Options); } } diff --git a/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs b/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs index f2643e998..3742b80c6 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs +++ b/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs @@ -9,6 +9,7 @@ using Xunit; namespace Marketing.FunctionalTests { + [Collection("Sequential")] public class CampaignScenarios : CampaignScenarioBase { diff --git a/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs b/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs index fdee81ce3..7ddf991a4 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs +++ b/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs @@ -20,13 +20,9 @@ namespace Marketing.FunctionalTests public TestServer CreateServer() { - - Console.WriteLine(" Creating test server"); var path = Assembly.GetAssembly(typeof(MarketingScenarioBase)) .Location; - Console.WriteLine(" Creating builder"); - var hostBuilder = new WebHostBuilder() .UseContentRoot(Path.GetDirectoryName(path)) .ConfigureAppConfiguration(cb => @@ -37,22 +33,9 @@ namespace Marketing.FunctionalTests .CaptureStartupErrors(true) .UseStartup(); - Console.WriteLine(" Created builder"); - var testServer = new TestServer(hostBuilder); - using (var scope = testServer.Services.CreateScope()) - { - var services = scope.ServiceProvider; - - var logger = services.GetRequiredService>(); - var settings = services.GetRequiredService>(); - logger.LogError("connectionString " + settings.Value.ConnectionString); - Console.WriteLine("connectionString " + settings.Value.ConnectionString); - } - testServer.Host - .RemoveDbContext() .MigrateDbContext((context, services) => { var logger = services.GetService>(); @@ -63,11 +46,6 @@ namespace Marketing.FunctionalTests .Wait(); }); - Console.WriteLine(" Thread to sleep"); - - Thread.Sleep(5000); - Console.WriteLine(" Thread after"); - return testServer; } diff --git a/src/Services/Marketing/Marketing.FunctionalTests/UserLocationRoleScenarios.cs b/src/Services/Marketing/Marketing.FunctionalTests/UserLocationRoleScenarios.cs index b8ee38e17..fe76923e0 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/UserLocationRoleScenarios.cs +++ b/src/Services/Marketing/Marketing.FunctionalTests/UserLocationRoleScenarios.cs @@ -8,6 +8,7 @@ using Xunit; namespace Marketing.FunctionalTests { + [Collection("Sequential")] public class UserLocationRoleScenarios : UserLocationRoleScenariosBase { From 17faebfa30476a8ef3020f2efe76474a82e8d26c Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Tue, 6 Aug 2019 08:51:17 +0200 Subject: [PATCH 049/113] remove mvc routing spa --- .../CampaignScenarios.cs | 1 + .../MarketingScenarioBase.cs | 18 ++---------------- .../UserLocationRoleScenarios.cs | 1 + src/Web/WebSPA/Startup.cs | 16 ++++------------ 4 files changed, 8 insertions(+), 28 deletions(-) diff --git a/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs b/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs index f2643e998..3742b80c6 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs +++ b/src/Services/Marketing/Marketing.FunctionalTests/CampaignScenarios.cs @@ -9,6 +9,7 @@ using Xunit; namespace Marketing.FunctionalTests { + [Collection("Sequential")] public class CampaignScenarios : CampaignScenarioBase { diff --git a/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs b/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs index fdee81ce3..2ae78237c 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs +++ b/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs @@ -20,13 +20,9 @@ namespace Marketing.FunctionalTests public TestServer CreateServer() { - - Console.WriteLine(" Creating test server"); var path = Assembly.GetAssembly(typeof(MarketingScenarioBase)) .Location; - Console.WriteLine(" Creating builder"); - var hostBuilder = new WebHostBuilder() .UseContentRoot(Path.GetDirectoryName(path)) .ConfigureAppConfiguration(cb => @@ -36,38 +32,28 @@ namespace Marketing.FunctionalTests }) .CaptureStartupErrors(true) .UseStartup(); - - Console.WriteLine(" Created builder"); var testServer = new TestServer(hostBuilder); - using (var scope = testServer.Services.CreateScope()) + using (var scope = testServer.Services.CreateScope()) { var services = scope.ServiceProvider; var logger = services.GetRequiredService>(); var settings = services.GetRequiredService>(); logger.LogError("connectionString " + settings.Value.ConnectionString); - Console.WriteLine("connectionString " + settings.Value.ConnectionString); } testServer.Host - .RemoveDbContext() .MigrateDbContext((context, services) => { var logger = services.GetService>(); - logger.LogError("Migrating MarketingContextSeed"); + logger.LogError("Migrating MarketingContextSeed"); new MarketingContextSeed() .SeedAsync(context, logger) .Wait(); - }); - Console.WriteLine(" Thread to sleep"); - - Thread.Sleep(5000); - Console.WriteLine(" Thread after"); - return testServer; } diff --git a/src/Services/Marketing/Marketing.FunctionalTests/UserLocationRoleScenarios.cs b/src/Services/Marketing/Marketing.FunctionalTests/UserLocationRoleScenarios.cs index b8ee38e17..fe76923e0 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/UserLocationRoleScenarios.cs +++ b/src/Services/Marketing/Marketing.FunctionalTests/UserLocationRoleScenarios.cs @@ -8,6 +8,7 @@ using Xunit; namespace Marketing.FunctionalTests { + [Collection("Sequential")] public class UserLocationRoleScenarios : UserLocationRoleScenariosBase { diff --git a/src/Web/WebSPA/Startup.cs b/src/Web/WebSPA/Startup.cs index 431ea5fbb..7e6c374f7 100644 --- a/src/Web/WebSPA/Startup.cs +++ b/src/Web/WebSPA/Startup.cs @@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; @@ -26,12 +25,8 @@ namespace eShopConContainers.WebSPA public IConfiguration Configuration { get; } - private IHostingEnvironment _hostingEnv; - - public Startup(IHostingEnvironment env) + public Startup() { - _hostingEnv = env; - var localPath = new Uri(Configuration["ASPNETCORE_URLS"])?.LocalPath ?? "/"; Configuration["BaseUrl"] = localPath; } @@ -48,8 +43,6 @@ namespace eShopConContainers.WebSPA .AddUrlGroup(new Uri(Configuration["MarketingUrlHC"]), name: "marketingapigw-check", tags: new string[] { "marketingapigw" }) .AddUrlGroup(new Uri(Configuration["IdentityUrlHC"]), name: "identityapi-check", tags: new string[] { "identityapi" }); - services.AddControllers(); - services.Configure(Configuration); if (Configuration.GetValue("IsClusterEnv") == bool.TrueString) @@ -62,16 +55,13 @@ namespace eShopConContainers.WebSPA } services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); - - services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) + services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; }); } - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IAntiforgery antiforgery) { @@ -102,6 +92,7 @@ namespace eShopConContainers.WebSPA WebContextSeed.Seed(app, env, loggerFactory); var pathBase = Configuration["PATH_BASE"]; + if (!string.IsNullOrEmpty(pathBase)) { loggerFactory.CreateLogger().LogDebug("Using PATH BASE '{pathBase}'", pathBase); @@ -127,6 +118,7 @@ namespace eShopConContainers.WebSPA app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapControllers(); endpoints.MapHealthChecks("/liveness", new HealthCheckOptions { Predicate = r => r.Name.Contains("self") From 56f3a6b82e1305b5b701fc6675651dcf899253cb Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Tue, 6 Aug 2019 16:10:39 +0200 Subject: [PATCH 050/113] move background task --- eShopOnContainers-ServicesAndWebApps.sln | 51 +++++++ .../Controllers/BasketController.cs | 33 ++-- .../IntegrationEventLogEntry.cs | 10 +- .../Services/IntegrationEventLogService.cs | 11 +- src/Services/Catalog/Catalog.API/Startup.cs | 2 +- .../Behaviors/TransactionBehaviour.cs | 2 + src/Services/Ordering/Ordering.API/Program.cs | 2 - src/Services/Ordering/Ordering.API/Startup.cs | 2 +- .../BackgroundTaskSettings.cs | 15 ++ .../Ordering.BackgroundTasks/Dockerfile | 18 +++ .../GracePeriodConfirmedIntegrationEvent.cs | 12 ++ .../Extensions/CustomExtensionMethods.cs | 141 ++++++++++++++++++ .../Ordering.BackgroundTasks.csproj | 33 ++++ .../Ordering.BackgroundTasks/Program.cs | 40 +++++ .../Properties/launchSettings.json | 13 ++ .../Tasks/GracePeriodManagerTask.cs | 11 +- .../appsettings.Development.json | 9 ++ .../Ordering.BackgroundTasks/appsettings.json | 26 ++++ src/Services/Webhooks/Webhooks.API/Startup.cs | 2 +- src/Web/WebSPA/Startup.cs | 1 + src/_build/dependencies.props | 2 + 21 files changed, 407 insertions(+), 29 deletions(-) create mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/BackgroundTaskSettings.cs create mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile create mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Events/GracePeriodConfirmedIntegrationEvent.cs create mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Extensions/CustomExtensionMethods.cs create mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj create mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Program.cs create mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Properties/launchSettings.json rename src/Services/Ordering/{Ordering.API/Infrastructure => Ordering.BackgroundTasks}/Tasks/GracePeriodManagerTask.cs (87%) create mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/appsettings.Development.json create mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/appsettings.json diff --git a/eShopOnContainers-ServicesAndWebApps.sln b/eShopOnContainers-ServicesAndWebApps.sln index 75cf60bae..52f49f96c 100644 --- a/eShopOnContainers-ServicesAndWebApps.sln +++ b/eShopOnContainers-ServicesAndWebApps.sln @@ -161,6 +161,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "config", "config", "{3ABEEE src\ApiGateways\Envoy\config\envoy.yaml = src\ApiGateways\Envoy\config\envoy.yaml EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ordering.BackgroundTasks", "src\Services\Ordering\Ordering.BackgroundTasks\Ordering.BackgroundTasks.csproj", "{D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Ad-Hoc|Any CPU = Ad-Hoc|Any CPU @@ -1759,6 +1761,54 @@ Global {56C2EF0B-6BF2-41D9-BE07-6E6D08D06B35}.Release|x64.Build.0 = Release|Any CPU {56C2EF0B-6BF2-41D9-BE07-6E6D08D06B35}.Release|x86.ActiveCfg = Release|Any CPU {56C2EF0B-6BF2-41D9-BE07-6E6D08D06B35}.Release|x86.Build.0 = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|ARM.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|ARM.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|iPhone.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|iPhoneSimulator.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|x64.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|x64.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|x86.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Ad-Hoc|x86.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|Any CPU.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|Any CPU.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|ARM.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|ARM.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|iPhone.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|iPhone.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|iPhoneSimulator.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|x64.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|x64.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|x86.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.AppStore|x86.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|ARM.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|ARM.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|iPhone.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|iPhone.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|x64.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|x64.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|x86.ActiveCfg = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Debug|x86.Build.0 = Debug|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|Any CPU.Build.0 = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|ARM.ActiveCfg = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|ARM.Build.0 = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|iPhone.ActiveCfg = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|iPhone.Build.0 = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|iPhoneSimulator.Build.0 = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|x64.ActiveCfg = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|x64.Build.0 = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|x86.ActiveCfg = Release|Any CPU + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1826,6 +1876,7 @@ Global {56C2EF0B-6BF2-41D9-BE07-6E6D08D06B35} = {68F5041D-51F2-4630-94B6-B49789F5E51A} {882A8F3A-C61F-4C44-86DD-A5A258714BF2} = {77849D35-37D4-4802-81DC-9477B2775A40} {3ABEEE8C-35E0-4185-9825-C44326151F5B} = {882A8F3A-C61F-4C44-86DD-A5A258714BF2} + {D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191} = {0BD0DB92-2D98-44D9-9AC0-C59186D59B0B} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {25728519-5F0F-4973-8A64-0A81EB4EA8D9} diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs index 00cf506a4..851368af1 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs @@ -117,18 +117,27 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers // Step 2: Get current basket status var currentBasket = (await _basket.GetByIdAsync(data.BasketId)) ?? new BasketData(data.BasketId); - // Step 3: Merge current status with new product - currentBasket.Items.Add(new BasketDataItem() - { - UnitPrice = item.Price, - PictureUrl = item.PictureUri, - ProductId = item.Id.ToString(), - ProductName = item.Name, - Quantity = data.Quantity, - Id = Guid.NewGuid().ToString() - }); - - // Step 4: Update basket + // Step 3: Search if exist product into basket + var product = currentBasket.Items.SingleOrDefault(i => i.ProductId == item.Id.ToString()); + + if(product != null){ + // Step 4: Update quantity for product + product.Quantity += data.Quantity; + } + else{ + // Step 4: Merge current status with new product + currentBasket.Items.Add(new BasketDataItem() + { + UnitPrice = item.Price, + PictureUrl = item.PictureUri, + ProductId = item.Id.ToString(), + ProductName = item.Name, + Quantity = data.Quantity, + Id = Guid.NewGuid().ToString() + }); + } + + // Step 5: Update basket await _basket.UpdateAsync(currentBasket); return Ok(); diff --git a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEntry.cs b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEntry.cs index dc65fa525..ec532d6da 100644 --- a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEntry.cs +++ b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEntry.cs @@ -6,13 +6,15 @@ using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; using System.Linq; using System.ComponentModel.DataAnnotations.Schema; using System.Reflection; +using Microsoft.Extensions.Logging; +using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services; namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF { public class IntegrationEventLogEntry { private IntegrationEventLogEntry() { } - public IntegrationEventLogEntry(IntegrationEvent @event, Guid transactionId) + public IntegrationEventLogEntry(IntegrationEvent @event, Guid transactionId, ILogger logger) { EventId = @event.Id; CreationTime = @event.CreationDate; @@ -21,8 +23,8 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF State = EventStateEnum.NotPublished; TimesSent = 0; TransactionId = transactionId.ToString(); - } + } public Guid EventId { get; private set; } public string EventTypeName { get; private set; } [NotMapped] @@ -35,8 +37,10 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF public string Content { get; private set; } public string TransactionId { get; private set; } - public IntegrationEventLogEntry DeserializeJsonContent(Type type) + public IntegrationEventLogEntry DeserializeJsonContent(Type type, ILogger logger) { + logger.LogInformation("----- DeserializeJsonContent {Content} {Type}", Content, type); + IntegrationEvent = JsonConvert.DeserializeObject(Content, type) as IntegrationEvent; return this; } diff --git a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs index 758055e69..b8e9eab9a 100644 --- a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs +++ b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; +using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections; @@ -17,11 +18,13 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Servi public class IntegrationEventLogService : IIntegrationEventLogService { private readonly IntegrationEventLogContext _integrationEventLogContext; + private readonly ILogger _logger; private readonly DbConnection _dbConnection; private readonly List _eventTypes; - public IntegrationEventLogService(DbConnection dbConnection) + public IntegrationEventLogService(DbConnection dbConnection, ILogger logger) { + _logger =logger; _dbConnection = dbConnection ?? throw new ArgumentNullException(nameof(dbConnection)); _integrationEventLogContext = new IntegrationEventLogContext( new DbContextOptionsBuilder() @@ -37,12 +40,14 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Servi public async Task> RetrieveEventLogsPendingToPublishAsync(Guid transactionId) { + _logger.LogInformation("----- RetrieveEventLogsPendingToPublishAsync {TransactionId}", transactionId); + var tid = transactionId.ToString(); return await _integrationEventLogContext.IntegrationEventLogs .Where(e => e.TransactionId == tid && e.State == EventStateEnum.NotPublished) .OrderBy(o => o.CreationTime) - .Select(e => e.DeserializeJsonContent(_eventTypes.Find(t=> t.Name == e.EventTypeShortName))) + .Select(e => e.DeserializeJsonContent(_eventTypes.Find(t=> t.Name == e.EventTypeShortName), _logger)) .ToListAsync(); } @@ -50,7 +55,7 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Servi { if (transaction == null) throw new ArgumentNullException(nameof(transaction)); - var eventLogEntry = new IntegrationEventLogEntry(@event, transaction.TransactionId); + var eventLogEntry = new IntegrationEventLogEntry(@event, transaction.TransactionId, _logger); _integrationEventLogContext.Database.UseTransaction(transaction.GetDbTransaction()); _integrationEventLogContext.IntegrationEventLogs.Add(eventLogEntry); diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 64441f9ea..451d5d5cf 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -277,7 +277,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API public static IServiceCollection AddIntegrationServices(this IServiceCollection services, IConfiguration configuration) { services.AddTransient>( - sp => (DbConnection c) => new IntegrationEventLogService(c)); + sp => (DbConnection c) => new IntegrationEventLogService(c, sp.GetService>())); services.AddTransient(); diff --git a/src/Services/Ordering/Ordering.API/Application/Behaviors/TransactionBehaviour.cs b/src/Services/Ordering/Ordering.API/Application/Behaviors/TransactionBehaviour.cs index be32daeee..0320cbd97 100644 --- a/src/Services/Ordering/Ordering.API/Application/Behaviors/TransactionBehaviour.cs +++ b/src/Services/Ordering/Ordering.API/Application/Behaviors/TransactionBehaviour.cs @@ -56,6 +56,8 @@ namespace Ordering.API.Application.Behaviors await _dbContext.CommitTransactionAsync(transaction); transactionId = transaction.TransactionId; + + _logger.LogInformation("----- End transaction {TransactionId} for {CommandName}", transaction.TransactionId, typeName); } await _orderingIntegrationEventService.PublishEventsThroughEventBusAsync(transactionId); diff --git a/src/Services/Ordering/Ordering.API/Program.cs b/src/Services/Ordering/Ordering.API/Program.cs index 251a9cbf5..50f53360c 100644 --- a/src/Services/Ordering/Ordering.API/Program.cs +++ b/src/Services/Ordering/Ordering.API/Program.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Ordering.API.Infrastructure.Tasks; using Serilog; using System; using System.IO; @@ -63,7 +62,6 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API WebHost.CreateDefaultBuilder(args) .CaptureStartupErrors(false) .UseStartup() - .ConfigureServices(service => service.AddHostedService()) .UseApplicationInsights() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(configuration) diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index fca490f28..572c83320 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -273,7 +273,7 @@ services.AddSingleton(); services.AddTransient(); services.AddTransient>( - sp => (DbConnection c) => new IntegrationEventLogService(c)); + sp => (DbConnection c) => new IntegrationEventLogService(c, sp.GetService>())); services.AddTransient(); diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/BackgroundTaskSettings.cs b/src/Services/Ordering/Ordering.BackgroundTasks/BackgroundTaskSettings.cs new file mode 100644 index 000000000..5171e7724 --- /dev/null +++ b/src/Services/Ordering/Ordering.BackgroundTasks/BackgroundTaskSettings.cs @@ -0,0 +1,15 @@ +namespace Ordering.BackgroundTasks +{ + public class BackgroundTaskSettings + { + public string ConnectionString { get; set; } + + public string EventBusConnection { get; set; } + + public int GracePeriodTime { get; set; } + + public int CheckUpdateTime { get; set; } + + public string SubscriptionClientName { get; set; } + } +} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile new file mode 100644 index 000000000..25f55a79c --- /dev/null +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile @@ -0,0 +1,18 @@ +FROM mcr.microsoft.com/dotnet/core/runtime:3.0-buster-slim AS base +WORKDIR /app + +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build +WORKDIR /src +COPY ["src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj", "src/Services/Ordering/Ordering.BackgroundTasks/"] +RUN dotnet restore "src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj" +COPY . . +WORKDIR "/src/src/Services/Ordering/Ordering.BackgroundTasks" +RUN dotnet build "Ordering.BackgroundTasks.csproj" -c Release -o /app + +FROM build AS publish +RUN dotnet publish "Ordering.BackgroundTasks.csproj" -c Release -o /app + +FROM base AS final +WORKDIR /app +COPY --from=publish /app . +ENTRYPOINT ["dotnet", "Ordering.BackgroundTasks.dll"] \ No newline at end of file diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Events/GracePeriodConfirmedIntegrationEvent.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Events/GracePeriodConfirmedIntegrationEvent.cs new file mode 100644 index 000000000..8fe92df76 --- /dev/null +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Events/GracePeriodConfirmedIntegrationEvent.cs @@ -0,0 +1,12 @@ +namespace Ordering.BackgroundTasks.Events +{ + using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; + + public class GracePeriodConfirmedIntegrationEvent : IntegrationEvent + { + public int OrderId { get; } + + public GracePeriodConfirmedIntegrationEvent(int orderId) => + OrderId = orderId; + } +} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Extensions/CustomExtensionMethods.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Extensions/CustomExtensionMethods.cs new file mode 100644 index 000000000..81d5472f4 --- /dev/null +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Extensions/CustomExtensionMethods.cs @@ -0,0 +1,141 @@ +using Autofac; +using Microsoft.Azure.ServiceBus; +using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; +using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; +using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ; +using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using RabbitMQ.Client; +using Serilog; + +namespace Ordering.BackgroundTasks.Extensions +{ + public static class CustomExtensionMethods + { + public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration) + { + var hcBuilder = services.AddHealthChecks(); + + hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy()); + + hcBuilder.AddSqlServer( + configuration["ConnectionString"], + name: "OrderingTaskDB-check", + tags: new string[] { "orderingtaskdb" }); + + if (configuration.GetValue("AzureServiceBusEnabled")) + { + hcBuilder.AddAzureServiceBusTopic( + configuration["EventBusConnection"], + topicName: "eshop_event_bus", + name: "orderingtask-servicebus-check", + tags: new string[] { "servicebus" }); + } + else + { + hcBuilder.AddRabbitMQ( + $"amqp://{configuration["EventBusConnection"]}", + name: "orderingtask-rabbitmqbus-check", + tags: new string[] { "rabbitmqbus" }); + } + + return services; + } + + public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration) + { + var subscriptionClientName = configuration["SubscriptionClientName"]; + + if (configuration.GetValue("AzureServiceBusEnabled")) + { + services.AddSingleton(sp => + { + var logger = sp.GetRequiredService>(); + + var serviceBusConnectionString = configuration["EventBusConnection"]; + var serviceBusConnection = new ServiceBusConnectionStringBuilder(serviceBusConnectionString); + + return new DefaultServiceBusPersisterConnection(serviceBusConnection, logger); + }); + + services.AddSingleton(sp => + { + var serviceBusPersisterConnection = sp.GetRequiredService(); + var iLifetimeScope = sp.GetRequiredService(); + var logger = sp.GetRequiredService>(); + var eventBusSubcriptionsManager = sp.GetRequiredService(); + + return new EventBusServiceBus(serviceBusPersisterConnection, logger, eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope); + }); + } + else + { + services.AddSingleton(sp => + { + var logger = sp.GetRequiredService>(); + + var factory = new ConnectionFactory() + { + HostName = configuration["EventBusConnection"], + DispatchConsumersAsync = true + }; + + if (!string.IsNullOrEmpty(configuration["EventBusUserName"])) + { + factory.UserName = configuration["EventBusUserName"]; + } + + if (!string.IsNullOrEmpty(configuration["EventBusPassword"])) + { + factory.Password = configuration["EventBusPassword"]; + } + + var retryCount = 5; + if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"])) + { + retryCount = int.Parse(configuration["EventBusRetryCount"]); + } + + return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount); + }); + + services.AddSingleton(sp => + { + var rabbitMQPersistentConnection = sp.GetRequiredService(); + var iLifetimeScope = sp.GetRequiredService(); + var logger = sp.GetRequiredService>(); + var eventBusSubcriptionsManager = sp.GetRequiredService(); + + var retryCount = 5; + + if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"])) + { + retryCount = int.Parse(configuration["EventBusRetryCount"]); + } + + return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount); + }); + } + + services.AddSingleton(); + + return services; + } + + public static ILoggingBuilder UseSerilog(this ILoggingBuilder builder, IConfiguration configuration) + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Verbose() + .Enrich.WithProperty("ApplicationContext", "BackgroundTasks") + .Enrich.FromLogContext() + .WriteTo.Console() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + + return builder; + } + } +} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj new file mode 100644 index 000000000..94e44bd3e --- /dev/null +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj @@ -0,0 +1,33 @@ + + + + $(NetCoreTargetVersion) + dotnet-Ordering.BackgroundTasks-9D3E1DD6-405B-447F-8AAB-1708B36D260E + Linux + $(LangVersion) + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs new file mode 100644 index 000000000..ca42a4ebb --- /dev/null +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs @@ -0,0 +1,40 @@ +using Autofac.Extensions.DependencyInjection; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Ordering.BackgroundTasks.Extensions; +using Ordering.BackgroundTasks.Tasks; +using Serilog; +using System.IO; + +namespace Ordering.BackgroundTasks +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureAppConfiguration((hostContext, builder) => + { + builder.SetBasePath(Directory.GetCurrentDirectory()); + builder.AddJsonFile("appsettings.json", optional: true); + builder.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); + builder.AddEnvironmentVariables(); + builder.AddCommandLine(args); + }) + .ConfigureLogging((host, builder) => builder.UseSerilog(host.Configuration).AddSerilog()) + .ConfigureServices((host, services) => + { + services.AddCustomHealthCheck(host.Configuration); + services.Configure(host.Configuration); + services.AddOptions(); + services.AddHostedService(); + services.AddEventBus(host.Configuration); + services.AddAutofac(container => container.Populate(services)); + }); + } +} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Properties/launchSettings.json b/src/Services/Ordering/Ordering.BackgroundTasks/Properties/launchSettings.json new file mode 100644 index 000000000..e2d987f50 --- /dev/null +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Properties/launchSettings.json @@ -0,0 +1,13 @@ +{ + "profiles": { + "Ordering.BackgroundTasks": { + "commandName": "Project", + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Development" + } + }, + "Docker": { + "commandName": "Docker" + } + } +} \ No newline at end of file diff --git a/src/Services/Ordering/Ordering.API/Infrastructure/Tasks/GracePeriodManagerTask.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs similarity index 87% rename from src/Services/Ordering/Ordering.API/Infrastructure/Tasks/GracePeriodManagerTask.cs rename to src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs index 740d1aa30..9d4c83c57 100644 --- a/src/Services/Ordering/Ordering.API/Infrastructure/Tasks/GracePeriodManagerTask.cs +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs @@ -1,25 +1,24 @@ using Dapper; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; -using Microsoft.eShopOnContainers.Services.Ordering.API; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Ordering.API.Application.IntegrationEvents.Events; +using Ordering.BackgroundTasks.Events; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading; using System.Threading.Tasks; -namespace Ordering.API.Infrastructure.Tasks +namespace Ordering.BackgroundTasks.Tasks { public class GracePeriodManagerService : BackgroundService { private readonly ILogger _logger; - private readonly OrderingSettings _settings; + private readonly BackgroundTaskSettings _settings; private readonly IEventBus _eventBus; - public GracePeriodManagerService(IOptions settings, IEventBus eventBus, ILogger logger) + public GracePeriodManagerService(IOptions settings, IEventBus eventBus, ILogger logger) { _settings = settings?.Value ?? throw new ArgumentNullException(nameof(settings)); _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus)); @@ -56,7 +55,7 @@ namespace Ordering.API.Infrastructure.Tasks { var confirmGracePeriodEvent = new GracePeriodConfirmedIntegrationEvent(orderId); - _logger.LogInformation("----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", confirmGracePeriodEvent.Id, Program.AppName, confirmGracePeriodEvent); + _logger.LogInformation("----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", confirmGracePeriodEvent.Id, _settings.SubscriptionClientName, confirmGracePeriodEvent); _eventBus.Publish(confirmGracePeriodEvent); } diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.Development.json b/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.Development.json new file mode 100644 index 000000000..e203e9407 --- /dev/null +++ b/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.json b/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.json new file mode 100644 index 000000000..88e5d6858 --- /dev/null +++ b/src/Services/Ordering/Ordering.BackgroundTasks/appsettings.json @@ -0,0 +1,26 @@ +{ + "ConnectionString": "Server=tcp:127.0.0.1,5433;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word;", + "Serilog": { + "SeqServerUrl": null, + "LogstashgUrl": null, + "MinimumLevel": { + "Default": "Information", + "Override": { + "Microsoft": "Warning", + "Microsoft.eShopOnContainers": "Information", + "System": "Warning" + } + } + }, + "SubscriptionClientName": "BackgroundTasks", + "GracePeriodTime": "1", + "CheckUpdateTime": "1000", + "ApplicationInsights": { + "InstrumentationKey": "" + }, + "AzureServiceBusEnabled": false, + "EventBusRetryCount": 5, + "EventBusConnection": "", + "EventBusUserName": "", + "EventBusPassword": "" +} \ No newline at end of file diff --git a/src/Services/Webhooks/Webhooks.API/Startup.cs b/src/Services/Webhooks/Webhooks.API/Startup.cs index 5859e9e12..1d454a7ab 100644 --- a/src/Services/Webhooks/Webhooks.API/Startup.cs +++ b/src/Services/Webhooks/Webhooks.API/Startup.cs @@ -291,7 +291,7 @@ namespace Webhooks.API public static IServiceCollection AddIntegrationServices(this IServiceCollection services, IConfiguration configuration) { services.AddTransient>( - sp => (DbConnection c) => new IntegrationEventLogService(c)); + sp => (DbConnection c) => new IntegrationEventLogService(c, sp.GetService>())); if (configuration.GetValue("AzureServiceBusEnabled")) { diff --git a/src/Web/WebSPA/Startup.cs b/src/Web/WebSPA/Startup.cs index 7e6c374f7..6ea83baa5 100644 --- a/src/Web/WebSPA/Startup.cs +++ b/src/Web/WebSPA/Startup.cs @@ -118,6 +118,7 @@ namespace eShopConContainers.WebSPA app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapDefaultControllerRoute(); endpoints.MapControllers(); endpoints.MapHealthChecks("/liveness", new HealthCheckOptions { diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 4de3340c6..dceb4edd2 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -20,6 +20,8 @@ 3.9.0-rc1 1.22.0 + 3.0.0-preview7.19362.4 + 1.7.9 2.2.0 2.2.0 2.2.0 From 7ea094b13660c36a555201feafb076431e406c62 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Tue, 6 Aug 2019 19:27:41 +0200 Subject: [PATCH 051/113] restore background config --- build/acr-build/queue-all.ps1 | 1 - .../multiarch-manifests/create-manifests.ps1 | 2 +- docker-compose-windows.prod.yml | 11 --- docker-compose.override.windows.yml | 5 - docker-compose.override.yml | 23 ----- docker-compose.prod.yml | 20 ---- docker-compose.yml | 10 +- k8s/build-push-images.ps1 | 2 +- k8s/deploy.ps1 | 2 +- k8s/deployments.yaml | 64 ------------- k8s/helm/app.yaml | 1 - k8s/helm/deploy-all-istio.ps1 | 2 +- k8s/helm/deploy-all.ps1 | 2 +- k8s/helm/deploy-all.sh | 2 +- k8s/helm/istio/doc.md | 1 - k8s/helm/ordering-backgroundtasks/.helmignore | 21 ----- k8s/helm/ordering-backgroundtasks/Chart.yaml | 5 - .../templates/NOTES.txt | 3 - .../templates/_helpers.tpl | 32 ------- .../templates/_names.tpl | 51 ---------- .../templates/configmap.yaml | 21 ----- .../templates/deployment.yaml | 92 ------------------- .../templates/service.yaml | 19 ---- k8s/helm/ordering-backgroundtasks/values.yaml | 70 -------------- 24 files changed, 7 insertions(+), 455 deletions(-) delete mode 100644 k8s/helm/ordering-backgroundtasks/.helmignore delete mode 100644 k8s/helm/ordering-backgroundtasks/Chart.yaml delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/NOTES.txt delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/_names.tpl delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/configmap.yaml delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/deployment.yaml delete mode 100644 k8s/helm/ordering-backgroundtasks/templates/service.yaml delete mode 100644 k8s/helm/ordering-backgroundtasks/values.yaml diff --git a/build/acr-build/queue-all.ps1 b/build/acr-build/queue-all.ps1 index aacffea95..60a39d92c 100644 --- a/build/acr-build/queue-all.ps1 +++ b/build/acr-build/queue-all.ps1 @@ -13,7 +13,6 @@ $services = @( @{ Name="eshopcatalog"; Image="eshop/catalog.api"; File="src/Services/Catalog/Catalog.API/Dockerfile" }, @{ Name="eshopidentity"; Image="eshop/identity.api"; File="src/Services/Identity/Identity.API/Dockerfile" }, @{ Name="eshopordering"; Image="eshop/ordering.api"; File="src/Services/Ordering/Ordering.API/Dockerfile" }, - @{ Name="eshoporderingbg"; Image="eshop/ordering.backgroundtasks"; File="src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile" }, @{ Name="eshopmarketing"; Image="eshop/marketing.api"; File="src/Services/Marketing/Marketing.API/Dockerfile" }, @{ Name="eshopwebspa"; Image="eshop/webspa"; File="src/Web/WebSPA/Dockerfile" }, @{ Name="eshopwebmvc"; Image="eshop/webmvc"; File="src/Web/WebMVC/Dockerfile" }, diff --git a/build/multiarch-manifests/create-manifests.ps1 b/build/multiarch-manifests/create-manifests.ps1 index cc7f05194..0bc6a4c7c 100644 --- a/build/multiarch-manifests/create-manifests.ps1 +++ b/build/multiarch-manifests/create-manifests.ps1 @@ -12,7 +12,7 @@ Write-Host "Tags used are linux-master, win-master, linux-dev, win-dev, linux-la Write-Host "Multiarch images tags will be master, dev, latest" -ForegroundColor Yellow -$services = "identity.api", "basket.api", "catalog.api", "ordering.api", "ordering.backgroundtasks", "marketing.api", "payment.api", "locations.api", "webhooks.api", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub", "webstatus", "webspa", "webmvc", "webhooks.client" +$services = "identity.api", "basket.api", "catalog.api", "ordering.api", "marketing.api", "payment.api", "locations.api", "webhooks.api", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub", "webstatus", "webspa", "webmvc", "webhooks.client" foreach ($svc in $services) { Write-Host "Creating manifest for $svc and tags :latest, :master, and :dev" diff --git a/docker-compose-windows.prod.yml b/docker-compose-windows.prod.yml index ead977f29..638c98d69 100644 --- a/docker-compose-windows.prod.yml +++ b/docker-compose-windows.prod.yml @@ -69,17 +69,6 @@ services: ports: - "5102:80" - ordering.backgroundtasks: - environment: - - ASPNETCORE_ENVIRONMENT=Production - - ASPNETCORE_URLS=http://0.0.0.0:80 - - ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word} - - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} - - UseCustomizationData=True - - AzureServiceBusEnabled=False - ports: - - "5111:80" - webspa: environment: - ASPNETCORE_ENVIRONMENT=Production diff --git a/docker-compose.override.windows.yml b/docker-compose.override.windows.yml index dcaac7c45..0f1e66efe 100644 --- a/docker-compose.override.windows.yml +++ b/docker-compose.override.windows.yml @@ -37,11 +37,6 @@ services: - EventBusUserName=admin - EventBusPassword=password - ordering.backgroundtasks: - environment: - - EventBusUserName=admin - - EventBusPassword=password - payment.api: environment: - EventBusUserName=admin diff --git a/docker-compose.override.yml b/docker-compose.override.yml index e4ee76650..bd04fa997 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -115,26 +115,6 @@ services: ports: - "5102:80" - - ordering.backgroundtasks: - environment: - - ASPNETCORE_ENVIRONMENT=Development - - ASPNETCORE_URLS=http://0.0.0.0:80 - - ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word} - - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} - - EventBusUserName=${ESHOP_SERVICE_BUS_USERNAME} - - EventBusPassword=${ESHOP_SERVICE_BUS_PASSWORD} - - UseCustomizationData=True - - AzureServiceBusEnabled=False - - CheckUpdateTime=30000 - - GracePeriodTime=1 - - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - - OrchestratorType=${ORCHESTRATOR_TYPE} - - UseLoadTest=${USE_LOADTEST:-False} - - Serilog__MinimumLevel__Override__Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ=Verbose - ports: - - "5111:80" - marketing.api: environment: - ASPNETCORE_ENVIRONMENT=Development @@ -343,8 +323,6 @@ services: - HealthChecks-UI__HealthChecks__7__Uri=http://webmarketingapigw/hc - HealthChecks-UI__HealthChecks__8__Name=Ordering HTTP Check - HealthChecks-UI__HealthChecks__8__Uri=http://ordering.api/hc - - HealthChecks-UI__HealthChecks__9__Name=Ordering HTTP Background Check - - HealthChecks-UI__HealthChecks__9__Uri=http://ordering.backgroundtasks/hc - HealthChecks-UI__HealthChecks__10__Name=Basket HTTP Check - HealthChecks-UI__HealthChecks__10__Uri=http://basket.api/hc - HealthChecks-UI__HealthChecks__11__Name=Catalog HTTP Check @@ -359,7 +337,6 @@ services: - HealthChecks-UI__HealthChecks__15__Uri=http://payment.api/hc - HealthChecks-UI__HealthChecks__16__Name=Ordering SignalRHub HTTP Check - HealthChecks-UI__HealthChecks__16__Uri=http://ordering.signalrhub/hc - - OrderingBackgroundTasksUrl=http://ordering.backgroundtasks/hc - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - OrchestratorType=${ORCHESTRATOR_TYPE} ports: diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 4bf465565..e1825a8c4 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -91,25 +91,6 @@ services: ports: - "80" # The API Gateway redirects and access through the internal port (80). - - ordering.backgroundtasks: - environment: - - ASPNETCORE_ENVIRONMENT=Development - - ASPNETCORE_URLS=http://0.0.0.0:80 - - ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word} - - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} - - EventBusUserName=${ESHOP_SERVICE_BUS_USERNAME} - - EventBusPassword=${ESHOP_SERVICE_BUS_PASSWORD} - - UseCustomizationData=True - - AzureServiceBusEnabled=False - - CheckUpdateTime=30000 - - GracePeriodTime=1 - - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - - OrchestratorType=${ORCHESTRATOR_TYPE} - - UseLoadTest=${USE_LOADTEST:-False} - ports: - - "5111:80" - marketing.api: environment: - ASPNETCORE_ENVIRONMENT=Development @@ -179,7 +160,6 @@ services: - ASPNETCORE_URLS=http://0.0.0.0:80 - CatalogUrl=http://catalog.api/hc - OrderingUrl=http://ordering.api/hc - - OrderingBackgroundTasksUrl=http://ordering.backgroundtasks/hc - BasketUrl=http://basket.api/hc - IdentityUrl=http://identity.api/hc - LocationsUrl=http://locations.api/hc diff --git a/docker-compose.yml b/docker-compose.yml index 243fbf2c6..ccc888bf2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -52,15 +52,7 @@ services: depends_on: - sql.data - rabbitmq - - ordering.backgroundtasks: - image: ${REGISTRY:-eshop}/ordering.backgroundtasks:${PLATFORM:-linux}-${TAG:-latest} - build: - context: . - dockerfile: src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile - depends_on: - - sql.data - - rabbitmq + - identity.api marketing.api: image: ${REGISTRY:-eshop}/marketing.api:${PLATFORM:-linux}-${TAG:-latest} diff --git a/k8s/build-push-images.ps1 b/k8s/build-push-images.ps1 index e2c8e06b6..769e74abc 100644 --- a/k8s/build-push-images.ps1 +++ b/k8s/build-push-images.ps1 @@ -57,7 +57,7 @@ if (-not [string]::IsNullOrEmpty($dockerUser)) { # Push images to Docker registry if ($pushImages) { Write-Host "Pushing images to $registry/$dockerOrg..." -ForegroundColor Yellow - $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "ordering.backgroundtasks", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") + $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") foreach ($service in $services) { $imageFqdn = if ($useDockerHub) {"$dockerOrg/${service}"} else {"$registry/$dockerOrg/${service}"} diff --git a/k8s/deploy.ps1 b/k8s/deploy.ps1 index abeb12aed..81af1bec7 100644 --- a/k8s/deploy.ps1 +++ b/k8s/deploy.ps1 @@ -68,7 +68,7 @@ if ($buildImages) { if ($pushImages) { Write-Host "Pushing images to $registry/$dockerOrg..." -ForegroundColor Yellow - $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "ordering.backgroundtasks", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") + $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") foreach ($service in $services) { $imageFqdn = if ($useDockerHub) {"$dockerOrg/${service}"} else {"$registry/$dockerOrg/${service}"} diff --git a/k8s/deployments.yaml b/k8s/deployments.yaml index f362c319c..46d139d1c 100644 --- a/k8s/deployments.yaml +++ b/k8s/deployments.yaml @@ -265,65 +265,6 @@ spec: --- apiVersion: extensions/v1beta1 kind: Deployment -metadata: - name: ordering-backgroundtasks -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: ordering-backgroundtasks - spec: - containers: - - name: ordering-backgroundtasks - image: eshop/ordering.backgroundtasks - imagePullPolicy: Always - env: - - name: ConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: ordering__ConnectionString - - name: EventBusConnection - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EventBusConnection - - name: AzureServiceBusEnabled - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__UseAzureServiceBus - - name: CheckUpdateTime - valueFrom: - configMapKeyRef: - name: externalcfg - key: GracePeriodManager__CheckUpdateTime - - name: GracePeriodTime - valueFrom: - configMapKeyRef: - name: externalcfg - key: GracePeriodManager__GracePeriodTime - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: UseLoadTest - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EnableLoadTest - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment metadata: name: ordering-signalrhub spec: @@ -702,11 +643,6 @@ spec: configMapKeyRef: name: internalurls key: ordering__hc - - name: OrderingBackgroundTasksUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: ordering-background__hc - name: LocationsUrl valueFrom: configMapKeyRef: diff --git a/k8s/helm/app.yaml b/k8s/helm/app.yaml index 91e829b27..390844a6e 100644 --- a/k8s/helm/app.yaml +++ b/k8s/helm/app.yaml @@ -28,7 +28,6 @@ app: # app global settings basket: basket # service name for basket api catalog: catalog # service name for catalog api ordering: ordering # service name for ordering api - orderingbackgroundtasks: orderingbackgroundtasks # service name for orderingbackgroundtasks orderingsignalrhub: ordering-signalrhub # service name for orderingsignalrhub identity: identity # service name for identity api mvc: webmvc # service name for web mvc diff --git a/k8s/helm/deploy-all-istio.ps1 b/k8s/helm/deploy-all-istio.ps1 index 5e05c6dbb..9e32704b1 100644 --- a/k8s/helm/deploy-all-istio.ps1 +++ b/k8s/helm/deploy-all-istio.ps1 @@ -80,7 +80,7 @@ if (-not [string]::IsNullOrEmpty($registry)) { Write-Host "Begin eShopOnContainers installation using Helm" -ForegroundColor Green $infras = ("sql-data", "nosql-data", "rabbitmq", "keystore-data", "basket-data") -$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-backgroundtasks","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") +$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") if ($deployInfrastructure) { foreach ($infra in $infras) { diff --git a/k8s/helm/deploy-all.ps1 b/k8s/helm/deploy-all.ps1 index 3cf6936bc..21bb2f1a0 100644 --- a/k8s/helm/deploy-all.ps1 +++ b/k8s/helm/deploy-all.ps1 @@ -62,7 +62,7 @@ if (-not [string]::IsNullOrEmpty($registry)) { Write-Host "Begin eShopOnContainers installation using Helm" -ForegroundColor Green $infras = ("sql-data", "nosql-data", "rabbitmq", "keystore-data", "basket-data") -$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-backgroundtasks","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") +$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") if ($deployInfrastructure) { foreach ($infra in $infras) { diff --git a/k8s/helm/deploy-all.sh b/k8s/helm/deploy-all.sh index 705b172f5..04891799b 100755 --- a/k8s/helm/deploy-all.sh +++ b/k8s/helm/deploy-all.sh @@ -185,7 +185,7 @@ fi echo "#################### Begin $app_name installation using Helm ####################" infras=(sql-data nosql-data rabbitmq keystore-data basket-data) -charts=(eshop-common apigwmm apigwms apigwwm apigwws basket-api catalog-api identity-api locations-api marketing-api mobileshoppingagg ordering-api ordering-backgroundtasks ordering-signalrhub payment-api webmvc webshoppingagg webspa webstatus webhooks-api webhooks-web) +charts=(eshop-common apigwmm apigwms apigwwm apigwws basket-api catalog-api identity-api locations-api marketing-api mobileshoppingagg ordering-api ordering-signalrhub payment-api webmvc webshoppingagg webspa webstatus webhooks-api webhooks-web) if [[ !$skip_infrastructure ]]; then for infra in "${infras[@]}" diff --git a/k8s/helm/istio/doc.md b/k8s/helm/istio/doc.md index b8c0a0257..f60b714f1 100644 --- a/k8s/helm/istio/doc.md +++ b/k8s/helm/istio/doc.md @@ -258,7 +258,6 @@ fec1e3499416 a3f21ec4bd11 "/entrypoint.sh /ngi…" 76485867f032 eshop/payment.api "dotnet Payment.API.…" 2 hours ago Up 2 hours k8s_payment-api_eshop-payment-api-75d5f9bdf6-6zx2v_default_4a3cdab4-e67f-11e8-b4b6-00155d016146_1 c2c4640ed610 eshop/marketing.api "dotnet Marketing.AP…" 2 hours ago Up 2 hours k8s_marketing-api_eshop-marketing-api-6b8c5989fd-jpxqv_default_45780626-e67f-11e8-b4b6-00155d016146_1 85301d538574 eshop/ordering.signalrhub "dotnet Ordering.Sig…" 2 hours ago Up 2 hours k8s_ordering-signalrhub_eshop-ordering-signalrhub-58cf5ff6-cnlm8_default_4932c344-e67f-11e8-b4b6-00155d016146_1 -7a408a98000e eshop/ordering.backgroundtasks "dotnet Ordering.Bac…" 2 hours ago Up 2 hours k8s_ordering-backgroundtasks_eshop-ordering-backgroundtasks-cc8f6d4d8-ztfk7_default_47f9cf10-e67f-11e8-b4b6-00155d016146_1 12c64b3a13e0 eshop/basket.api "dotnet Basket.API.d…" 2 hours ago Up 2 hours k8s_basket-api_eshop-basket-api-658546684d-6hlvd_default_4262d022-e67f-11e8-b4b6-00155d016146_1 133fccfeeff3 eshop/webstatus "dotnet WebStatus.dll" 2 hours ago Up 2 hours k8s_webstatus_eshop-webstatus-7f46479dc4-bqnq7_default_4dc13eb2-e67f-11e8-b4b6-00155d016146_0 00c6e4c52135 eshop/webspa "dotnet WebSPA.dll" 2 hours ago Up 2 hours k8s_webspa_eshop-webspa-64cb8df9cb-dcbwg_default_4cd47376-e67f-11e8-b4b6-00155d016146_0 diff --git a/k8s/helm/ordering-backgroundtasks/.helmignore b/k8s/helm/ordering-backgroundtasks/.helmignore deleted file mode 100644 index f0c131944..000000000 --- a/k8s/helm/ordering-backgroundtasks/.helmignore +++ /dev/null @@ -1,21 +0,0 @@ -# Patterns to ignore when building packages. -# This supports shell glob matching, relative path matching, and -# negation (prefixed with !). Only one pattern per line. -.DS_Store -# Common VCS dirs -.git/ -.gitignore -.bzr/ -.bzrignore -.hg/ -.hgignore -.svn/ -# Common backup files -*.swp -*.bak -*.tmp -*~ -# Various IDEs -.project -.idea/ -*.tmproj diff --git a/k8s/helm/ordering-backgroundtasks/Chart.yaml b/k8s/helm/ordering-backgroundtasks/Chart.yaml deleted file mode 100644 index 6ad4f47e6..000000000 --- a/k8s/helm/ordering-backgroundtasks/Chart.yaml +++ /dev/null @@ -1,5 +0,0 @@ -apiVersion: v1 -appVersion: "1.0" -description: A Helm chart for Kubernetes -name: ordering-backgroundtasks -version: 0.1.0 diff --git a/k8s/helm/ordering-backgroundtasks/templates/NOTES.txt b/k8s/helm/ordering-backgroundtasks/templates/NOTES.txt deleted file mode 100644 index 54e1b49ea..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/NOTES.txt +++ /dev/null @@ -1,3 +0,0 @@ -eShop Ordering Background Tasks installed. ------------------------------------------- - diff --git a/k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl b/k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl deleted file mode 100644 index e61b78285..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl +++ /dev/null @@ -1,32 +0,0 @@ -{{/* vim: set filetype=mustache: */}} -{{/* -Expand the name of the chart. -*/}} -{{- define "ordering-backgroundtasks.name" -}} -{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} -{{- end -}} - -{{/* -Create a default fully qualified app name. -We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). -If release name contains chart name it will be used as a full name. -*/}} -{{- define "ordering-backgroundtasks.fullname" -}} -{{- if .Values.fullnameOverride -}} -{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} -{{- else -}} -{{- $name := default .Chart.Name .Values.nameOverride -}} -{{- if contains $name .Release.Name -}} -{{- .Release.Name | trunc 63 | trimSuffix "-" -}} -{{- else -}} -{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} -{{- end -}} -{{- end -}} -{{- end -}} - -{{/* -Create chart name and version as used by the chart label. -*/}} -{{- define "ordering-backgroundtasks.chart" -}} -{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} -{{- end -}} diff --git a/k8s/helm/ordering-backgroundtasks/templates/_names.tpl b/k8s/helm/ordering-backgroundtasks/templates/_names.tpl deleted file mode 100644 index 39ee485ef..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/_names.tpl +++ /dev/null @@ -1,51 +0,0 @@ -{{- define "suffix-name" -}} -{{- if .Values.app.name -}} -{{- .Values.app.name -}} -{{- else -}} -{{- .Release.Name -}} -{{- end -}} -{{- end -}} - -{{- define "sql-name" -}} -{{- if .Values.inf.sql.host -}} -{{- .Values.inf.sql.host -}} -{{- else -}} -{{- printf "%s" "sql-data" -}} -{{- end -}} -{{- end -}} - -{{- define "mongo-name" -}} -{{- if .Values.inf.mongo.host -}} -{{- .Values.inf.mongo.host -}} -{{- else -}} -{{- printf "%s" "nosql-data" -}} -{{- end -}} -{{- end -}} - -{{- define "url-of" -}} -{{- $name := first .}} -{{- $ctx := last .}} -{{- if eq $name "" -}} -{{- $ctx.Values.inf.k8s.dns -}} -{{- else -}} -{{- printf "%s/%s" $ctx.Values.inf.k8s.dns $name -}} {{/*Value is just / */}} -{{- end -}} -{{- end -}} - - -{{- define "pathBase" -}} -{{- if .Values.inf.k8s.suffix -}} -{{- $suffix := include "suffix-name" . -}} -{{- printf "%s-%s" .Values.pathBase $suffix -}} -{{- else -}} -{{- .Values.pathBase -}} -{{- end -}} -{{- end -}} - -{{- define "fqdn-image" -}} -{{- if .Values.inf.registry -}} -{{- printf "%s/%s" .Values.inf.registry.server .Values.image.repository -}} -{{- else -}} -{{- .Values.image.repository -}} -{{- end -}} -{{- end -}} \ No newline at end of file diff --git a/k8s/helm/ordering-backgroundtasks/templates/configmap.yaml b/k8s/helm/ordering-backgroundtasks/templates/configmap.yaml deleted file mode 100644 index 7ed4a0e8e..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/configmap.yaml +++ /dev/null @@ -1,21 +0,0 @@ -{{- $name := include "ordering-backgroundtasks.fullname" . -}} -{{- $sqlsrv := include "sql-name" . -}} -{{- $cfgname := printf "cfg-%s" $name | trunc 63 }} - -apiVersion: v1 -kind: ConfigMap -metadata: - name: "{{ $cfgname }}" - labels: - app: {{ template "ordering-backgroundtasks.name" . }} - chart: {{ template "ordering-backgroundtasks.chart" .}} - release: {{ .Release.Name }} - heritage: {{ .Release.Service }} -data: - ordering__ConnectionString: Server={{ $sqlsrv }};Initial Catalog={{ .Values.inf.sql.ordering.db }};User Id={{ .Values.inf.sql.common.user }};Password={{ .Values.inf.sql.common.pwd }}; - ordering__EnableLoadTest: "{{ .Values.inf.misc.useLoadTest }}" - all__EventBusConnection: {{ .Values.inf.eventbus.constr }} - all__InstrumentationKey: "{{ .Values.inf.appinsights.key }}" - all__UseAzureServiceBus: "{{ .Values.inf.eventbus.useAzure }}" - graceperiodmanager__CheckUpdateTime: "{{ .Values.cfg.checkUpdateTime }}" - graceperiodmanager__GracePeriodTime: "{{ .Values.cfg.gracePeriodTime }}" \ No newline at end of file diff --git a/k8s/helm/ordering-backgroundtasks/templates/deployment.yaml b/k8s/helm/ordering-backgroundtasks/templates/deployment.yaml deleted file mode 100644 index d93c7f764..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/deployment.yaml +++ /dev/null @@ -1,92 +0,0 @@ -{{- $name := include "ordering-backgroundtasks.fullname" . -}} -{{- $cfgname := printf "cfg-%s" $name | trunc 63 }} - -apiVersion: apps/v1beta2 -kind: Deployment -metadata: - name: {{ template "ordering-backgroundtasks.fullname" . }} - labels: - app: {{ template "ordering-backgroundtasks.name" . }} - chart: {{ template "ordering-backgroundtasks.chart" . }} - release: {{ .Release.Name }} - heritage: {{ .Release.Service }} -spec: - replicas: {{ .Values.replicaCount }} - selector: - matchLabels: - app: {{ template "ordering-backgroundtasks.name" . }} - release: {{ .Release.Name }} - template: - metadata: - labels: - app: {{ template "ordering-backgroundtasks.name" . }} - release: {{ .Release.Name }} - spec: - {{ if .Values.inf.registry -}} - imagePullSecrets: - - name: {{ .Values.inf.registry.secretName }} - {{- end }} - containers: - - name: {{ .Chart.Name }} - {{ if .Values.probes -}} - {{- if .Values.probes.liveness -}} - livenessProbe: - httpGet: - port: {{ .Values.probes.liveness.port }} - path: {{ .Values.probes.liveness.path }} - initialDelaySeconds: {{ .Values.probes.liveness.initialDelaySeconds }} - periodSeconds: {{ .Values.probes.liveness.periodSeconds }} - {{- end -}} - {{- end -}} - {{- if .Values.probes -}} - {{- if .Values.probes.readiness }} - readinessProbe: - httpGet: - port: {{ .Values.probes.readiness.port }} - path: {{ .Values.probes.readiness.path }} - initialDelaySeconds: {{ .Values.probes.readiness.initialDelaySeconds }} - periodSeconds: {{ .Values.probes.readiness.periodSeconds }} - timeoutSeconds: {{ .Values.probes.readiness.timeoutSeconds }} - {{- end -}} - {{- end }} - image: "{{ template "fqdn-image" . }}:{{ .Values.image.tag }}" - imagePullPolicy: {{ .Values.image.pullPolicy }} - env: - - name: PATH_BASE - value: {{ include "pathBase" . }} - - name: k8sname - value: {{ .Values.clusterName }} - {{- if .Values.env.values -}} - {{- range .Values.env.values }} - - name: {{ .name }} - value: {{ .value | quote }} - {{- end -}} - {{- end -}} - {{- if .Values.env.configmap -}} - {{- range .Values.env.configmap }} - - name: {{ .name }} - valueFrom: - configMapKeyRef: - name: {{ $cfgname }} - key: {{ .key }} - {{- end -}} - {{- end }} - ports: - - name: http - containerPort: 80 - protocol: TCP - resources: -{{ toYaml .Values.resources | indent 12 }} - {{- with .Values.nodeSelector }} - nodeSelector: -{{ toYaml . | indent 8 }} - {{- end }} - {{- with .Values.affinity }} - affinity: -{{ toYaml . | indent 8 }} - {{- end }} - {{- with .Values.tolerations }} - tolerations: -{{ toYaml . | indent 8 }} - {{- end }} - diff --git a/k8s/helm/ordering-backgroundtasks/templates/service.yaml b/k8s/helm/ordering-backgroundtasks/templates/service.yaml deleted file mode 100644 index d8fcba036..000000000 --- a/k8s/helm/ordering-backgroundtasks/templates/service.yaml +++ /dev/null @@ -1,19 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: {{ .Values.app.svc.orderingbackgroundtasks }} - labels: - app: {{ template "ordering-backgroundtasks.name" . }} - chart: {{ template "ordering-backgroundtasks.chart" . }} - release: {{ .Release.Name }} - heritage: {{ .Release.Service }} -spec: - type: {{ .Values.service.type }} - ports: - - port: {{ .Values.service.port }} - targetPort: http - protocol: TCP - name: http - selector: - app: {{ template "ordering-backgroundtasks.name" . }} - release: {{ .Release.Name }} diff --git a/k8s/helm/ordering-backgroundtasks/values.yaml b/k8s/helm/ordering-backgroundtasks/values.yaml deleted file mode 100644 index d065f0345..000000000 --- a/k8s/helm/ordering-backgroundtasks/values.yaml +++ /dev/null @@ -1,70 +0,0 @@ -replicaCount: 1 -clusterName: eshop-aks -pathBase: /ordering-backgroundtasks - -image: - repository: eshop/ordering.backgroundtasks - tag: latest - pullPolicy: IfNotPresent - -service: - type: ClusterIP - port: 80 - -ingress: - enabled: false - annotations: {} - hosts: - - chart-example.local - tls: [] - -cfg: - checkUpdateTime: "15000" - gracePeriodTime: "1" - -resources: {} - - -nodeSelector: {} - -tolerations: [] - -affinity: {} - -# env defines the environment variables that will be declared in the pod -env: - urls: - # configmap declares variables which value is taken from the config map defined in template configmap.yaml (name is name of var and key the key in configmap). - configmap: - - name: ConnectionString - key: ordering__ConnectionString - - name: ApplicationInsights__InstrumentationKey - key: all__InstrumentationKey - - name: EventBusConnection - key: all__EventBusConnection - - name: AzureServiceBusEnabled - key: all__UseAzureServiceBus - - name: UseLoadTest - key: ordering__EnableLoadTest - - name: CheckUpdateTime - key: graceperiodmanager__CheckUpdateTime - - name: GracePeriodTime - key: graceperiodmanager__GracePeriodTime - # values define environment variables with a fixed value (no configmap involved) (name is name of var, and value is its value) - values: - - name: ASPNETCORE_ENVIRONMENT - value: Development - - name: OrchestratorType - value: 'K8S' -probes: - liveness: - path: /liveness - initialDelaySeconds: 10 - periodSeconds: 15 - port: 80 - readiness: - path: /hc - timeoutSeconds: 5 - initialDelaySeconds: 90 - periodSeconds: 60 - port: 80 From 0988dcd8c2e0845de44c58fea0c288c4ed83e056 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Wed, 7 Aug 2019 09:28:08 +0200 Subject: [PATCH 052/113] background --- build/acr-build/queue-all.ps1 | 1 + .../multiarch-manifests/create-manifests.ps1 | 2 +- docker-compose-windows.prod.yml | 11 +++ docker-compose.override.windows.yml | 5 + docker-compose.override.yml | 21 ++++- docker-compose.prod.yml | 18 ++++ docker-compose.yml | 10 +- k8s/build-push-images.ps1 | 2 +- k8s/deploy.ps1 | 2 +- k8s/deployments.yaml | 59 ++++++++++++ k8s/helm/app.yaml | 1 + k8s/helm/deploy-all-istio.ps1 | 2 +- k8s/helm/deploy-all.ps1 | 2 +- k8s/helm/deploy-all.sh | 2 +- k8s/helm/istio/doc.md | 1 + k8s/helm/ordering-backgroundtasks/.helmignore | 21 +++++ k8s/helm/ordering-backgroundtasks/Chart.yaml | 5 + .../templates/NOTES.txt | 3 + .../templates/_helpers.tpl | 32 +++++++ .../templates/_names.tpl | 51 ++++++++++ .../templates/configmap.yaml | 21 +++++ .../templates/deployment.yaml | 92 +++++++++++++++++++ .../templates/service.yaml | 19 ++++ k8s/helm/ordering-backgroundtasks/values.yaml | 70 ++++++++++++++ .../Ordering.BackgroundTasks/Dockerfile | 17 +++- .../Extensions/CustomExtensionMethods.cs | 1 + .../Ordering.BackgroundTasks.csproj | 1 + .../Ordering.BackgroundTasks/Program.cs | 7 +- src/csproj-files.txt | 1 + src/prepare-devspaces.ps1 | 3 + 30 files changed, 467 insertions(+), 16 deletions(-) create mode 100644 k8s/helm/ordering-backgroundtasks/.helmignore create mode 100644 k8s/helm/ordering-backgroundtasks/Chart.yaml create mode 100644 k8s/helm/ordering-backgroundtasks/templates/NOTES.txt create mode 100644 k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl create mode 100644 k8s/helm/ordering-backgroundtasks/templates/_names.tpl create mode 100644 k8s/helm/ordering-backgroundtasks/templates/configmap.yaml create mode 100644 k8s/helm/ordering-backgroundtasks/templates/deployment.yaml create mode 100644 k8s/helm/ordering-backgroundtasks/templates/service.yaml create mode 100644 k8s/helm/ordering-backgroundtasks/values.yaml diff --git a/build/acr-build/queue-all.ps1 b/build/acr-build/queue-all.ps1 index 60a39d92c..69448f9a2 100644 --- a/build/acr-build/queue-all.ps1 +++ b/build/acr-build/queue-all.ps1 @@ -13,6 +13,7 @@ $services = @( @{ Name="eshopcatalog"; Image="eshop/catalog.api"; File="src/Services/Catalog/Catalog.API/Dockerfile" }, @{ Name="eshopidentity"; Image="eshop/identity.api"; File="src/Services/Identity/Identity.API/Dockerfile" }, @{ Name="eshopordering"; Image="eshop/ordering.api"; File="src/Services/Ordering/Ordering.API/Dockerfile" }, + @{ Name="eshoporderingbg"; Image="eshop/ordering.backgroundtasks"; File="src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile" }, @{ Name="eshopmarketing"; Image="eshop/marketing.api"; File="src/Services/Marketing/Marketing.API/Dockerfile" }, @{ Name="eshopwebspa"; Image="eshop/webspa"; File="src/Web/WebSPA/Dockerfile" }, @{ Name="eshopwebmvc"; Image="eshop/webmvc"; File="src/Web/WebMVC/Dockerfile" }, diff --git a/build/multiarch-manifests/create-manifests.ps1 b/build/multiarch-manifests/create-manifests.ps1 index 0bc6a4c7c..cc7f05194 100644 --- a/build/multiarch-manifests/create-manifests.ps1 +++ b/build/multiarch-manifests/create-manifests.ps1 @@ -12,7 +12,7 @@ Write-Host "Tags used are linux-master, win-master, linux-dev, win-dev, linux-la Write-Host "Multiarch images tags will be master, dev, latest" -ForegroundColor Yellow -$services = "identity.api", "basket.api", "catalog.api", "ordering.api", "marketing.api", "payment.api", "locations.api", "webhooks.api", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub", "webstatus", "webspa", "webmvc", "webhooks.client" +$services = "identity.api", "basket.api", "catalog.api", "ordering.api", "ordering.backgroundtasks", "marketing.api", "payment.api", "locations.api", "webhooks.api", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub", "webstatus", "webspa", "webmvc", "webhooks.client" foreach ($svc in $services) { Write-Host "Creating manifest for $svc and tags :latest, :master, and :dev" diff --git a/docker-compose-windows.prod.yml b/docker-compose-windows.prod.yml index 638c98d69..9b9c552cc 100644 --- a/docker-compose-windows.prod.yml +++ b/docker-compose-windows.prod.yml @@ -68,6 +68,17 @@ services: - AzureServiceBusEnabled=False ports: - "5102:80" + + ordering.backgroundtasks: + environment: + - ASPNETCORE_ENVIRONMENT=Production + - ASPNETCORE_URLS=http://0.0.0.0:80 + - ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word} + - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} + - UseCustomizationData=True + - AzureServiceBusEnabled=False + ports: + - "5111:80" webspa: environment: diff --git a/docker-compose.override.windows.yml b/docker-compose.override.windows.yml index 0f1e66efe..dcaac7c45 100644 --- a/docker-compose.override.windows.yml +++ b/docker-compose.override.windows.yml @@ -37,6 +37,11 @@ services: - EventBusUserName=admin - EventBusPassword=password + ordering.backgroundtasks: + environment: + - EventBusUserName=admin + - EventBusPassword=password + payment.api: environment: - EventBusUserName=admin diff --git a/docker-compose.override.yml b/docker-compose.override.yml index bd04fa997..24b0cf9a8 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -113,7 +113,26 @@ services: - Serilog__MinimumLevel__Override__Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ=Verbose - Serilog__MinimumLevel__Override__Ordering.API=Verbose ports: - - "5102:80" + - "5102:80" + + ordering.backgroundtasks: + environment: + - ASPNETCORE_ENVIRONMENT=Development + - ASPNETCORE_URLS=http://0.0.0.0:80 + - ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word} + - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} + - EventBusUserName=${ESHOP_SERVICE_BUS_USERNAME} + - EventBusPassword=${ESHOP_SERVICE_BUS_PASSWORD} + - UseCustomizationData=True + - AzureServiceBusEnabled=False + - CheckUpdateTime=30000 + - GracePeriodTime=1 + - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} + - OrchestratorType=${ORCHESTRATOR_TYPE} + - UseLoadTest=${USE_LOADTEST:-False} + - Serilog__MinimumLevel__Override__Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ=Verbose + ports: + - "5111:80" marketing.api: environment: diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index e1825a8c4..aed216ef9 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -91,6 +91,24 @@ services: ports: - "80" # The API Gateway redirects and access through the internal port (80). + ordering.backgroundtasks: + environment: + - ASPNETCORE_ENVIRONMENT=Development + - ASPNETCORE_URLS=http://0.0.0.0:80 + - ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sql.data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word} + - EventBusConnection=${ESHOP_AZURE_SERVICE_BUS:-rabbitmq} + - EventBusUserName=${ESHOP_SERVICE_BUS_USERNAME} + - EventBusPassword=${ESHOP_SERVICE_BUS_PASSWORD} + - UseCustomizationData=True + - AzureServiceBusEnabled=False + - CheckUpdateTime=30000 + - GracePeriodTime=1 + - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} + - OrchestratorType=${ORCHESTRATOR_TYPE} + - UseLoadTest=${USE_LOADTEST:-False} + ports: + - "5111:80" + marketing.api: environment: - ASPNETCORE_ENVIRONMENT=Development diff --git a/docker-compose.yml b/docker-compose.yml index ccc888bf2..243fbf2c6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -52,7 +52,15 @@ services: depends_on: - sql.data - rabbitmq - - identity.api + + ordering.backgroundtasks: + image: ${REGISTRY:-eshop}/ordering.backgroundtasks:${PLATFORM:-linux}-${TAG:-latest} + build: + context: . + dockerfile: src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile + depends_on: + - sql.data + - rabbitmq marketing.api: image: ${REGISTRY:-eshop}/marketing.api:${PLATFORM:-linux}-${TAG:-latest} diff --git a/k8s/build-push-images.ps1 b/k8s/build-push-images.ps1 index 769e74abc..e2c8e06b6 100644 --- a/k8s/build-push-images.ps1 +++ b/k8s/build-push-images.ps1 @@ -57,7 +57,7 @@ if (-not [string]::IsNullOrEmpty($dockerUser)) { # Push images to Docker registry if ($pushImages) { Write-Host "Pushing images to $registry/$dockerOrg..." -ForegroundColor Yellow - $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") + $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "ordering.backgroundtasks", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") foreach ($service in $services) { $imageFqdn = if ($useDockerHub) {"$dockerOrg/${service}"} else {"$registry/$dockerOrg/${service}"} diff --git a/k8s/deploy.ps1 b/k8s/deploy.ps1 index 81af1bec7..abeb12aed 100644 --- a/k8s/deploy.ps1 +++ b/k8s/deploy.ps1 @@ -68,7 +68,7 @@ if ($buildImages) { if ($pushImages) { Write-Host "Pushing images to $registry/$dockerOrg..." -ForegroundColor Yellow - $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") + $services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "ordering.backgroundtasks", "marketing.api","payment.api","locations.api", "webmvc", "webspa", "webstatus", "ocelotapigw", "mobileshoppingagg", "webshoppingagg", "ordering.signalrhub") foreach ($service in $services) { $imageFqdn = if ($useDockerHub) {"$dockerOrg/${service}"} else {"$registry/$dockerOrg/${service}"} diff --git a/k8s/deployments.yaml b/k8s/deployments.yaml index 46d139d1c..ca97df9eb 100644 --- a/k8s/deployments.yaml +++ b/k8s/deployments.yaml @@ -265,6 +265,65 @@ spec: --- apiVersion: extensions/v1beta1 kind: Deployment +metadata: + name: ordering-backgroundtasks +spec: + paused: true + template: + metadata: + labels: + app: eshop + component: ordering-backgroundtasks + spec: + containers: + - name: ordering-backgroundtasks + image: eshop/ordering.backgroundtasks + imagePullPolicy: Always + env: + - name: ConnectionString + valueFrom: + configMapKeyRef: + name: externalcfg + key: ordering__ConnectionString + - name: EventBusConnection + valueFrom: + configMapKeyRef: + name: externalcfg + key: all__EventBusConnection + - name: AzureServiceBusEnabled + valueFrom: + configMapKeyRef: + name: externalcfg + key: all__UseAzureServiceBus + - name: CheckUpdateTime + valueFrom: + configMapKeyRef: + name: externalcfg + key: GracePeriodManager__CheckUpdateTime + - name: GracePeriodTime + valueFrom: + configMapKeyRef: + name: externalcfg + key: GracePeriodManager__GracePeriodTime + - name: ApplicationInsights__InstrumentationKey + valueFrom: + configMapKeyRef: + name: externalcfg + key: all__InstrumentationKey + - name: UseLoadTest + valueFrom: + configMapKeyRef: + name: externalcfg + key: all__EnableLoadTest + - name: OrchestratorType + value: 'K8S' + ports: + - containerPort: 80 + imagePullSecrets: + - name: registry-key +--- +apiVersion: extensions/v1beta1 +kind: Deployment metadata: name: ordering-signalrhub spec: diff --git a/k8s/helm/app.yaml b/k8s/helm/app.yaml index 390844a6e..91e829b27 100644 --- a/k8s/helm/app.yaml +++ b/k8s/helm/app.yaml @@ -28,6 +28,7 @@ app: # app global settings basket: basket # service name for basket api catalog: catalog # service name for catalog api ordering: ordering # service name for ordering api + orderingbackgroundtasks: orderingbackgroundtasks # service name for orderingbackgroundtasks orderingsignalrhub: ordering-signalrhub # service name for orderingsignalrhub identity: identity # service name for identity api mvc: webmvc # service name for web mvc diff --git a/k8s/helm/deploy-all-istio.ps1 b/k8s/helm/deploy-all-istio.ps1 index 9e32704b1..5e05c6dbb 100644 --- a/k8s/helm/deploy-all-istio.ps1 +++ b/k8s/helm/deploy-all-istio.ps1 @@ -80,7 +80,7 @@ if (-not [string]::IsNullOrEmpty($registry)) { Write-Host "Begin eShopOnContainers installation using Helm" -ForegroundColor Green $infras = ("sql-data", "nosql-data", "rabbitmq", "keystore-data", "basket-data") -$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") +$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-backgroundtasks","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") if ($deployInfrastructure) { foreach ($infra in $infras) { diff --git a/k8s/helm/deploy-all.ps1 b/k8s/helm/deploy-all.ps1 index 21bb2f1a0..3cf6936bc 100644 --- a/k8s/helm/deploy-all.ps1 +++ b/k8s/helm/deploy-all.ps1 @@ -62,7 +62,7 @@ if (-not [string]::IsNullOrEmpty($registry)) { Write-Host "Begin eShopOnContainers installation using Helm" -ForegroundColor Green $infras = ("sql-data", "nosql-data", "rabbitmq", "keystore-data", "basket-data") -$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") +$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-backgroundtasks","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web") if ($deployInfrastructure) { foreach ($infra in $infras) { diff --git a/k8s/helm/deploy-all.sh b/k8s/helm/deploy-all.sh index 04891799b..705b172f5 100755 --- a/k8s/helm/deploy-all.sh +++ b/k8s/helm/deploy-all.sh @@ -185,7 +185,7 @@ fi echo "#################### Begin $app_name installation using Helm ####################" infras=(sql-data nosql-data rabbitmq keystore-data basket-data) -charts=(eshop-common apigwmm apigwms apigwwm apigwws basket-api catalog-api identity-api locations-api marketing-api mobileshoppingagg ordering-api ordering-signalrhub payment-api webmvc webshoppingagg webspa webstatus webhooks-api webhooks-web) +charts=(eshop-common apigwmm apigwms apigwwm apigwws basket-api catalog-api identity-api locations-api marketing-api mobileshoppingagg ordering-api ordering-backgroundtasks ordering-signalrhub payment-api webmvc webshoppingagg webspa webstatus webhooks-api webhooks-web) if [[ !$skip_infrastructure ]]; then for infra in "${infras[@]}" diff --git a/k8s/helm/istio/doc.md b/k8s/helm/istio/doc.md index f60b714f1..b8c0a0257 100644 --- a/k8s/helm/istio/doc.md +++ b/k8s/helm/istio/doc.md @@ -258,6 +258,7 @@ fec1e3499416 a3f21ec4bd11 "/entrypoint.sh /ngi…" 76485867f032 eshop/payment.api "dotnet Payment.API.…" 2 hours ago Up 2 hours k8s_payment-api_eshop-payment-api-75d5f9bdf6-6zx2v_default_4a3cdab4-e67f-11e8-b4b6-00155d016146_1 c2c4640ed610 eshop/marketing.api "dotnet Marketing.AP…" 2 hours ago Up 2 hours k8s_marketing-api_eshop-marketing-api-6b8c5989fd-jpxqv_default_45780626-e67f-11e8-b4b6-00155d016146_1 85301d538574 eshop/ordering.signalrhub "dotnet Ordering.Sig…" 2 hours ago Up 2 hours k8s_ordering-signalrhub_eshop-ordering-signalrhub-58cf5ff6-cnlm8_default_4932c344-e67f-11e8-b4b6-00155d016146_1 +7a408a98000e eshop/ordering.backgroundtasks "dotnet Ordering.Bac…" 2 hours ago Up 2 hours k8s_ordering-backgroundtasks_eshop-ordering-backgroundtasks-cc8f6d4d8-ztfk7_default_47f9cf10-e67f-11e8-b4b6-00155d016146_1 12c64b3a13e0 eshop/basket.api "dotnet Basket.API.d…" 2 hours ago Up 2 hours k8s_basket-api_eshop-basket-api-658546684d-6hlvd_default_4262d022-e67f-11e8-b4b6-00155d016146_1 133fccfeeff3 eshop/webstatus "dotnet WebStatus.dll" 2 hours ago Up 2 hours k8s_webstatus_eshop-webstatus-7f46479dc4-bqnq7_default_4dc13eb2-e67f-11e8-b4b6-00155d016146_0 00c6e4c52135 eshop/webspa "dotnet WebSPA.dll" 2 hours ago Up 2 hours k8s_webspa_eshop-webspa-64cb8df9cb-dcbwg_default_4cd47376-e67f-11e8-b4b6-00155d016146_0 diff --git a/k8s/helm/ordering-backgroundtasks/.helmignore b/k8s/helm/ordering-backgroundtasks/.helmignore new file mode 100644 index 000000000..f0c131944 --- /dev/null +++ b/k8s/helm/ordering-backgroundtasks/.helmignore @@ -0,0 +1,21 @@ +# Patterns to ignore when building packages. +# This supports shell glob matching, relative path matching, and +# negation (prefixed with !). Only one pattern per line. +.DS_Store +# Common VCS dirs +.git/ +.gitignore +.bzr/ +.bzrignore +.hg/ +.hgignore +.svn/ +# Common backup files +*.swp +*.bak +*.tmp +*~ +# Various IDEs +.project +.idea/ +*.tmproj diff --git a/k8s/helm/ordering-backgroundtasks/Chart.yaml b/k8s/helm/ordering-backgroundtasks/Chart.yaml new file mode 100644 index 000000000..6ad4f47e6 --- /dev/null +++ b/k8s/helm/ordering-backgroundtasks/Chart.yaml @@ -0,0 +1,5 @@ +apiVersion: v1 +appVersion: "1.0" +description: A Helm chart for Kubernetes +name: ordering-backgroundtasks +version: 0.1.0 diff --git a/k8s/helm/ordering-backgroundtasks/templates/NOTES.txt b/k8s/helm/ordering-backgroundtasks/templates/NOTES.txt new file mode 100644 index 000000000..54e1b49ea --- /dev/null +++ b/k8s/helm/ordering-backgroundtasks/templates/NOTES.txt @@ -0,0 +1,3 @@ +eShop Ordering Background Tasks installed. +------------------------------------------ + diff --git a/k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl b/k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl new file mode 100644 index 000000000..e61b78285 --- /dev/null +++ b/k8s/helm/ordering-backgroundtasks/templates/_helpers.tpl @@ -0,0 +1,32 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Expand the name of the chart. +*/}} +{{- define "ordering-backgroundtasks.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "ordering-backgroundtasks.fullname" -}} +{{- if .Values.fullnameOverride -}} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- $name := default .Chart.Name .Values.nameOverride -}} +{{- if contains $name .Release.Name -}} +{{- .Release.Name | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "ordering-backgroundtasks.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} +{{- end -}} diff --git a/k8s/helm/ordering-backgroundtasks/templates/_names.tpl b/k8s/helm/ordering-backgroundtasks/templates/_names.tpl new file mode 100644 index 000000000..39ee485ef --- /dev/null +++ b/k8s/helm/ordering-backgroundtasks/templates/_names.tpl @@ -0,0 +1,51 @@ +{{- define "suffix-name" -}} +{{- if .Values.app.name -}} +{{- .Values.app.name -}} +{{- else -}} +{{- .Release.Name -}} +{{- end -}} +{{- end -}} + +{{- define "sql-name" -}} +{{- if .Values.inf.sql.host -}} +{{- .Values.inf.sql.host -}} +{{- else -}} +{{- printf "%s" "sql-data" -}} +{{- end -}} +{{- end -}} + +{{- define "mongo-name" -}} +{{- if .Values.inf.mongo.host -}} +{{- .Values.inf.mongo.host -}} +{{- else -}} +{{- printf "%s" "nosql-data" -}} +{{- end -}} +{{- end -}} + +{{- define "url-of" -}} +{{- $name := first .}} +{{- $ctx := last .}} +{{- if eq $name "" -}} +{{- $ctx.Values.inf.k8s.dns -}} +{{- else -}} +{{- printf "%s/%s" $ctx.Values.inf.k8s.dns $name -}} {{/*Value is just / */}} +{{- end -}} +{{- end -}} + + +{{- define "pathBase" -}} +{{- if .Values.inf.k8s.suffix -}} +{{- $suffix := include "suffix-name" . -}} +{{- printf "%s-%s" .Values.pathBase $suffix -}} +{{- else -}} +{{- .Values.pathBase -}} +{{- end -}} +{{- end -}} + +{{- define "fqdn-image" -}} +{{- if .Values.inf.registry -}} +{{- printf "%s/%s" .Values.inf.registry.server .Values.image.repository -}} +{{- else -}} +{{- .Values.image.repository -}} +{{- end -}} +{{- end -}} \ No newline at end of file diff --git a/k8s/helm/ordering-backgroundtasks/templates/configmap.yaml b/k8s/helm/ordering-backgroundtasks/templates/configmap.yaml new file mode 100644 index 000000000..7ed4a0e8e --- /dev/null +++ b/k8s/helm/ordering-backgroundtasks/templates/configmap.yaml @@ -0,0 +1,21 @@ +{{- $name := include "ordering-backgroundtasks.fullname" . -}} +{{- $sqlsrv := include "sql-name" . -}} +{{- $cfgname := printf "cfg-%s" $name | trunc 63 }} + +apiVersion: v1 +kind: ConfigMap +metadata: + name: "{{ $cfgname }}" + labels: + app: {{ template "ordering-backgroundtasks.name" . }} + chart: {{ template "ordering-backgroundtasks.chart" .}} + release: {{ .Release.Name }} + heritage: {{ .Release.Service }} +data: + ordering__ConnectionString: Server={{ $sqlsrv }};Initial Catalog={{ .Values.inf.sql.ordering.db }};User Id={{ .Values.inf.sql.common.user }};Password={{ .Values.inf.sql.common.pwd }}; + ordering__EnableLoadTest: "{{ .Values.inf.misc.useLoadTest }}" + all__EventBusConnection: {{ .Values.inf.eventbus.constr }} + all__InstrumentationKey: "{{ .Values.inf.appinsights.key }}" + all__UseAzureServiceBus: "{{ .Values.inf.eventbus.useAzure }}" + graceperiodmanager__CheckUpdateTime: "{{ .Values.cfg.checkUpdateTime }}" + graceperiodmanager__GracePeriodTime: "{{ .Values.cfg.gracePeriodTime }}" \ No newline at end of file diff --git a/k8s/helm/ordering-backgroundtasks/templates/deployment.yaml b/k8s/helm/ordering-backgroundtasks/templates/deployment.yaml new file mode 100644 index 000000000..d93c7f764 --- /dev/null +++ b/k8s/helm/ordering-backgroundtasks/templates/deployment.yaml @@ -0,0 +1,92 @@ +{{- $name := include "ordering-backgroundtasks.fullname" . -}} +{{- $cfgname := printf "cfg-%s" $name | trunc 63 }} + +apiVersion: apps/v1beta2 +kind: Deployment +metadata: + name: {{ template "ordering-backgroundtasks.fullname" . }} + labels: + app: {{ template "ordering-backgroundtasks.name" . }} + chart: {{ template "ordering-backgroundtasks.chart" . }} + release: {{ .Release.Name }} + heritage: {{ .Release.Service }} +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + app: {{ template "ordering-backgroundtasks.name" . }} + release: {{ .Release.Name }} + template: + metadata: + labels: + app: {{ template "ordering-backgroundtasks.name" . }} + release: {{ .Release.Name }} + spec: + {{ if .Values.inf.registry -}} + imagePullSecrets: + - name: {{ .Values.inf.registry.secretName }} + {{- end }} + containers: + - name: {{ .Chart.Name }} + {{ if .Values.probes -}} + {{- if .Values.probes.liveness -}} + livenessProbe: + httpGet: + port: {{ .Values.probes.liveness.port }} + path: {{ .Values.probes.liveness.path }} + initialDelaySeconds: {{ .Values.probes.liveness.initialDelaySeconds }} + periodSeconds: {{ .Values.probes.liveness.periodSeconds }} + {{- end -}} + {{- end -}} + {{- if .Values.probes -}} + {{- if .Values.probes.readiness }} + readinessProbe: + httpGet: + port: {{ .Values.probes.readiness.port }} + path: {{ .Values.probes.readiness.path }} + initialDelaySeconds: {{ .Values.probes.readiness.initialDelaySeconds }} + periodSeconds: {{ .Values.probes.readiness.periodSeconds }} + timeoutSeconds: {{ .Values.probes.readiness.timeoutSeconds }} + {{- end -}} + {{- end }} + image: "{{ template "fqdn-image" . }}:{{ .Values.image.tag }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + env: + - name: PATH_BASE + value: {{ include "pathBase" . }} + - name: k8sname + value: {{ .Values.clusterName }} + {{- if .Values.env.values -}} + {{- range .Values.env.values }} + - name: {{ .name }} + value: {{ .value | quote }} + {{- end -}} + {{- end -}} + {{- if .Values.env.configmap -}} + {{- range .Values.env.configmap }} + - name: {{ .name }} + valueFrom: + configMapKeyRef: + name: {{ $cfgname }} + key: {{ .key }} + {{- end -}} + {{- end }} + ports: + - name: http + containerPort: 80 + protocol: TCP + resources: +{{ toYaml .Values.resources | indent 12 }} + {{- with .Values.nodeSelector }} + nodeSelector: +{{ toYaml . | indent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: +{{ toYaml . | indent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: +{{ toYaml . | indent 8 }} + {{- end }} + diff --git a/k8s/helm/ordering-backgroundtasks/templates/service.yaml b/k8s/helm/ordering-backgroundtasks/templates/service.yaml new file mode 100644 index 000000000..d8fcba036 --- /dev/null +++ b/k8s/helm/ordering-backgroundtasks/templates/service.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ .Values.app.svc.orderingbackgroundtasks }} + labels: + app: {{ template "ordering-backgroundtasks.name" . }} + chart: {{ template "ordering-backgroundtasks.chart" . }} + release: {{ .Release.Name }} + heritage: {{ .Release.Service }} +spec: + type: {{ .Values.service.type }} + ports: + - port: {{ .Values.service.port }} + targetPort: http + protocol: TCP + name: http + selector: + app: {{ template "ordering-backgroundtasks.name" . }} + release: {{ .Release.Name }} diff --git a/k8s/helm/ordering-backgroundtasks/values.yaml b/k8s/helm/ordering-backgroundtasks/values.yaml new file mode 100644 index 000000000..d065f0345 --- /dev/null +++ b/k8s/helm/ordering-backgroundtasks/values.yaml @@ -0,0 +1,70 @@ +replicaCount: 1 +clusterName: eshop-aks +pathBase: /ordering-backgroundtasks + +image: + repository: eshop/ordering.backgroundtasks + tag: latest + pullPolicy: IfNotPresent + +service: + type: ClusterIP + port: 80 + +ingress: + enabled: false + annotations: {} + hosts: + - chart-example.local + tls: [] + +cfg: + checkUpdateTime: "15000" + gracePeriodTime: "1" + +resources: {} + + +nodeSelector: {} + +tolerations: [] + +affinity: {} + +# env defines the environment variables that will be declared in the pod +env: + urls: + # configmap declares variables which value is taken from the config map defined in template configmap.yaml (name is name of var and key the key in configmap). + configmap: + - name: ConnectionString + key: ordering__ConnectionString + - name: ApplicationInsights__InstrumentationKey + key: all__InstrumentationKey + - name: EventBusConnection + key: all__EventBusConnection + - name: AzureServiceBusEnabled + key: all__UseAzureServiceBus + - name: UseLoadTest + key: ordering__EnableLoadTest + - name: CheckUpdateTime + key: graceperiodmanager__CheckUpdateTime + - name: GracePeriodTime + key: graceperiodmanager__GracePeriodTime + # values define environment variables with a fixed value (no configmap involved) (name is name of var, and value is its value) + values: + - name: ASPNETCORE_ENVIRONMENT + value: Development + - name: OrchestratorType + value: 'K8S' +probes: + liveness: + path: /liveness + initialDelaySeconds: 10 + periodSeconds: 15 + port: 80 + readiness: + path: /hc + timeoutSeconds: 5 + initialDelaySeconds: 90 + periodSeconds: 60 + port: 80 diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile index 25f55a79c..1aeaaafc0 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile @@ -1,16 +1,23 @@ FROM mcr.microsoft.com/dotnet/core/runtime:3.0-buster-slim AS base WORKDIR /app +EXPOSE 80 FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src -COPY ["src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj", "src/Services/Ordering/Ordering.BackgroundTasks/"] -RUN dotnet restore "src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj" + +COPY scripts scripts/ + +COPY src/ApiGateways/*/*.csproj /src/csproj-files/ +COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ +COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ +COPY src/Services/*/*/*.csproj /src/csproj-files/ +COPY src/Web/*/*.csproj /src/csproj-files/ + COPY . . -WORKDIR "/src/src/Services/Ordering/Ordering.BackgroundTasks" -RUN dotnet build "Ordering.BackgroundTasks.csproj" -c Release -o /app +WORKDIR /src/src/Services/Ordering/Ordering.BackgroundTasks +RUN dotnet publish -c Release -o /app FROM build AS publish -RUN dotnet publish "Ordering.BackgroundTasks.csproj" -c Release -o /app FROM base AS final WORKDIR /app diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Extensions/CustomExtensionMethods.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Extensions/CustomExtensionMethods.cs index 81d5472f4..751ae71ee 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Extensions/CustomExtensionMethods.cs +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Extensions/CustomExtensionMethods.cs @@ -94,6 +94,7 @@ namespace Ordering.BackgroundTasks.Extensions } var retryCount = 5; + if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"])) { retryCount = int.Parse(configuration["EventBusRetryCount"]); diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj index 94e44bd3e..50c756633 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj @@ -3,6 +3,7 @@ $(NetCoreTargetVersion) dotnet-Ordering.BackgroundTasks-9D3E1DD6-405B-447F-8AAB-1708B36D260E + false Linux $(LangVersion) diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs index ca42a4ebb..6d4e72ded 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs @@ -18,11 +18,11 @@ namespace Ordering.BackgroundTasks public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) - .ConfigureAppConfiguration((hostContext, builder) => + .ConfigureAppConfiguration((host, builder) => { builder.SetBasePath(Directory.GetCurrentDirectory()); builder.AddJsonFile("appsettings.json", optional: true); - builder.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); + builder.AddJsonFile($"appsettings.{host.HostingEnvironment.EnvironmentName}.json", optional: true); builder.AddEnvironmentVariables(); builder.AddCommandLine(args); }) @@ -35,6 +35,7 @@ namespace Ordering.BackgroundTasks services.AddHostedService(); services.AddEventBus(host.Configuration); services.AddAutofac(container => container.Populate(services)); - }); + }) + .UseServiceProviderFactory(new AutofacServiceProviderFactory()); } } diff --git a/src/csproj-files.txt b/src/csproj-files.txt index 96420d96e..6dc3532d9 100644 --- a/src/csproj-files.txt +++ b/src/csproj-files.txt @@ -20,6 +20,7 @@ COPY src/Services/Location/Locations.FunctionalTests/*.csproj /src/src/Services/ COPY src/Services/Marketing/Marketing.API/*.csproj /src/src/Services/Marketing/Marketing.API/ COPY src/Services/Marketing/Marketing.FunctionalTests/*.csproj /src/src/Services/Marketing/Marketing.FunctionalTests/ COPY src/Services/Ordering/Ordering.API/*.csproj /src/src/Services/Ordering/Ordering.API/ +COPY src/Services/Ordering/Ordering.BackgroundTasks/*.csproj /src/src/Services/Ordering/Ordering.BackgroundTasks/ COPY src/Services/Ordering/Ordering.Domain/*.csproj /src/src/Services/Ordering/Ordering.Domain/ COPY src/Services/Ordering/Ordering.FunctionalTests/*.csproj /src/src/Services/Ordering/Ordering.FunctionalTests/ COPY src/Services/Ordering/Ordering.Infrastructure/*.csproj /src/src/Services/Ordering/Ordering.Infrastructure/ diff --git a/src/prepare-devspaces.ps1 b/src/prepare-devspaces.ps1 index 5e1b72d4e..5b692e908 100644 --- a/src/prepare-devspaces.ps1 +++ b/src/prepare-devspaces.ps1 @@ -52,6 +52,9 @@ Copy-Item "..\k8s\helm\inf.yaml" -Destination ".\Services\Ordering\Ordering.API" Copy-Item "..\k8s\helm\app.yaml" -Destination ".\Services\Ordering\Ordering.SignalrHub" -Force Copy-Item "..\k8s\helm\inf.yaml" -Destination ".\Services\Ordering\Ordering.SignalrHub" -Force +Copy-Item "..\k8s\helm\app.yaml" -Destination ".\Services\Ordering\Ordering.BackgroundTasks" -Force +Copy-Item "..\k8s\helm\inf.yaml" -Destination ".\Services\Ordering\Ordering.BackgroundTasks" -Force + Write-Host "Copying app.yaml and inf.yaml to Payment API" -ForegroundColor Yellow Copy-Item "..\k8s\helm\app.yaml" -Destination ".\Services\Payment\Payment.API" -Force Copy-Item "..\k8s\helm\inf.yaml" -Destination ".\Services\Payment\Payment.API" -Force From d29f6c21f9dab43d4837e6cac436be74b909335c Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 7 Aug 2019 15:45:23 +0200 Subject: [PATCH 053/113] Add health check in Ordering.BackgroundTask project --- docker-compose.override.yml | 30 +++++----- .../Ordering.BackgroundTasks/Dockerfile | 2 +- .../Ordering.BackgroundTasks.csproj | 18 +++--- .../Ordering.BackgroundTasks/Program.cs | 20 +++---- .../Ordering.BackgroundTasks/Startup.cs | 57 +++++++++++++++++++ src/_build/dependencies.props | 1 + 6 files changed, 93 insertions(+), 35 deletions(-) create mode 100644 src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 24b0cf9a8..60f2efb45 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -342,20 +342,22 @@ services: - HealthChecks-UI__HealthChecks__7__Uri=http://webmarketingapigw/hc - HealthChecks-UI__HealthChecks__8__Name=Ordering HTTP Check - HealthChecks-UI__HealthChecks__8__Uri=http://ordering.api/hc - - HealthChecks-UI__HealthChecks__10__Name=Basket HTTP Check - - HealthChecks-UI__HealthChecks__10__Uri=http://basket.api/hc - - HealthChecks-UI__HealthChecks__11__Name=Catalog HTTP Check - - HealthChecks-UI__HealthChecks__11__Uri=http://catalog.api/hc - - HealthChecks-UI__HealthChecks__12__Name=Identity HTTP Check - - HealthChecks-UI__HealthChecks__12__Uri=http://identity.api/hc - - HealthChecks-UI__HealthChecks__13__Name=Marketing HTTP Check - - HealthChecks-UI__HealthChecks__13__Uri=http://marketing.api/hc - - HealthChecks-UI__HealthChecks__14__Name=Locations HTTP Check - - HealthChecks-UI__HealthChecks__14__Uri=http://locations.api/hc - - HealthChecks-UI__HealthChecks__15__Name=Payments HTTP Check - - HealthChecks-UI__HealthChecks__15__Uri=http://payment.api/hc - - HealthChecks-UI__HealthChecks__16__Name=Ordering SignalRHub HTTP Check - - HealthChecks-UI__HealthChecks__16__Uri=http://ordering.signalrhub/hc + - HealthChecks-UI__HealthChecks__9__Name=Basket HTTP Check + - HealthChecks-UI__HealthChecks__9__Uri=http://basket.api/hc + - HealthChecks-UI__HealthChecks__10__Name=Catalog HTTP Check + - HealthChecks-UI__HealthChecks__10__Uri=http://catalog.api/hc + - HealthChecks-UI__HealthChecks__11__Name=Identity HTTP Check + - HealthChecks-UI__HealthChecks__11__Uri=http://identity.api/hc + - HealthChecks-UI__HealthChecks__12__Name=Marketing HTTP Check + - HealthChecks-UI__HealthChecks__12__Uri=http://marketing.api/hc + - HealthChecks-UI__HealthChecks__13__Name=Locations HTTP Check + - HealthChecks-UI__HealthChecks__13__Uri=http://locations.api/hc + - HealthChecks-UI__HealthChecks__14__Name=Payments HTTP Check + - HealthChecks-UI__HealthChecks__14__Uri=http://payment.api/hc + - HealthChecks-UI__HealthChecks__15__Name=Ordering SignalRHub HTTP Check + - HealthChecks-UI__HealthChecks__15__Uri=http://ordering.signalrhub/hc + - HealthChecks-UI__HealthChecks__16__Name=Ordering HTTP Background Check + - HealthChecks-UI__HealthChecks__16__Uri=http://ordering.backgroundtasks/hc - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - OrchestratorType=${ORCHESTRATOR_TYPE} ports: diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile index 1aeaaafc0..820f8d4b1 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/core/runtime:3.0-buster-slim AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj index 50c756633..5168760a9 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj @@ -9,21 +9,25 @@ + + + + + + + + - + + + - - - - - - diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs index 6d4e72ded..152cd79a7 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Program.cs @@ -6,6 +6,8 @@ using Ordering.BackgroundTasks.Extensions; using Ordering.BackgroundTasks.Tasks; using Serilog; using System.IO; +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Hosting; namespace Ordering.BackgroundTasks { @@ -13,11 +15,11 @@ namespace Ordering.BackgroundTasks { public static void Main(string[] args) { - CreateHostBuilder(args).Build().Run(); + CreateHostBuilder(args).Run(); } - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) + public static IWebHost CreateHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((host, builder) => { builder.SetBasePath(Directory.GetCurrentDirectory()); @@ -27,15 +29,7 @@ namespace Ordering.BackgroundTasks builder.AddCommandLine(args); }) .ConfigureLogging((host, builder) => builder.UseSerilog(host.Configuration).AddSerilog()) - .ConfigureServices((host, services) => - { - services.AddCustomHealthCheck(host.Configuration); - services.Configure(host.Configuration); - services.AddOptions(); - services.AddHostedService(); - services.AddEventBus(host.Configuration); - services.AddAutofac(container => container.Populate(services)); - }) - .UseServiceProviderFactory(new AutofacServiceProviderFactory()); + .UseStartup() + .Build(); } } diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs new file mode 100644 index 000000000..1f35b711c --- /dev/null +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Startup.cs @@ -0,0 +1,57 @@ +namespace Ordering.BackgroundTasks +{ + using Autofac; + using Autofac.Extensions.DependencyInjection; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Diagnostics.HealthChecks; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; + using Ordering.BackgroundTasks.Extensions; + using Ordering.BackgroundTasks.Tasks; + using System; + using HealthChecks.UI.Client; + + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + public virtual IServiceProvider ConfigureServices(IServiceCollection services) + { + services.AddCustomHealthCheck(this.Configuration) + .Configure(this.Configuration) + .AddOptions() + .AddHostedService() + .AddEventBus(this.Configuration) + .AddAutofac(container => container.Populate(services)); + + var container = new ContainerBuilder(); + container.Populate(services); + + return new AutofacServiceProvider(container.Build()); + } + + + public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) + { + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + }); + } + } +} diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index dceb4edd2..5ea99f10c 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -58,6 +58,7 @@ 2.2.0 1.0.0 2.2.0 + 3.0.0-preview4-19123-01 3.0.0-preview6.19307.2 3.0.0-preview7.19365.7 3.0.0-preview7.19365.7 From 4a30a1cc9e8ac4385d565db8e4eef0efb4fb2054 Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 7 Aug 2019 15:56:24 +0200 Subject: [PATCH 054/113] add package version to dependencies.props --- .../Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj | 2 +- src/_build/dependencies.props | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj index 5168760a9..df73288bc 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj @@ -16,7 +16,7 @@ - + diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 5ea99f10c..f472ce237 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -50,6 +50,7 @@ 2.6.1 1.0.2 3.0.0-preview4-19123-01 + 3.0.0-preview7.19365.7 3.0.0-alpha1-10670 2.2.0-preview2-35157 3.0.0-alpha1-34847 From 216463f847c113f95b400d9109977818ca9fb4b0 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Wed, 7 Aug 2019 17:06:20 +0200 Subject: [PATCH 055/113] ordering.api error integrationevents --- .../IntegrationEventLogEntry.cs | 7 ++---- .../Services/IntegrationEventLogService.cs | 22 +++++++++---------- .../Controllers/BasketController.cs | 12 +++++++++- src/Services/Catalog/Catalog.API/Startup.cs | 2 +- .../Behaviors/TransactionBehaviour.cs | 2 -- src/Services/Ordering/Ordering.API/Startup.cs | 2 +- .../Ordering.SignalrHub.csproj | 1 + .../Ordering/Ordering.SignalrHub/Startup.cs | 6 ++++- src/Services/Webhooks/Webhooks.API/Startup.cs | 2 +- src/Web/WebMVC/Services/BasketService.cs | 7 +++++- 10 files changed, 39 insertions(+), 24 deletions(-) diff --git a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEntry.cs b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEntry.cs index ec532d6da..f9cf4a2c1 100644 --- a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEntry.cs +++ b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEntry.cs @@ -14,7 +14,7 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF public class IntegrationEventLogEntry { private IntegrationEventLogEntry() { } - public IntegrationEventLogEntry(IntegrationEvent @event, Guid transactionId, ILogger logger) + public IntegrationEventLogEntry(IntegrationEvent @event, Guid transactionId) { EventId = @event.Id; CreationTime = @event.CreationDate; @@ -23,7 +23,6 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF State = EventStateEnum.NotPublished; TimesSent = 0; TransactionId = transactionId.ToString(); - } public Guid EventId { get; private set; } public string EventTypeName { get; private set; } @@ -37,10 +36,8 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF public string Content { get; private set; } public string TransactionId { get; private set; } - public IntegrationEventLogEntry DeserializeJsonContent(Type type, ILogger logger) + public IntegrationEventLogEntry DeserializeJsonContent(Type type) { - logger.LogInformation("----- DeserializeJsonContent {Content} {Type}", Content, type); - IntegrationEvent = JsonConvert.DeserializeObject(Content, type) as IntegrationEvent; return this; } diff --git a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs index b8e9eab9a..04fa84618 100644 --- a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs +++ b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs @@ -18,13 +18,11 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Servi public class IntegrationEventLogService : IIntegrationEventLogService { private readonly IntegrationEventLogContext _integrationEventLogContext; - private readonly ILogger _logger; private readonly DbConnection _dbConnection; private readonly List _eventTypes; - public IntegrationEventLogService(DbConnection dbConnection, ILogger logger) + public IntegrationEventLogService(DbConnection dbConnection) { - _logger =logger; _dbConnection = dbConnection ?? throw new ArgumentNullException(nameof(dbConnection)); _integrationEventLogContext = new IntegrationEventLogContext( new DbContextOptionsBuilder() @@ -40,22 +38,24 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Servi public async Task> RetrieveEventLogsPendingToPublishAsync(Guid transactionId) { - _logger.LogInformation("----- RetrieveEventLogsPendingToPublishAsync {TransactionId}", transactionId); - var tid = transactionId.ToString(); - return await _integrationEventLogContext.IntegrationEventLogs - .Where(e => e.TransactionId == tid && e.State == EventStateEnum.NotPublished) - .OrderBy(o => o.CreationTime) - .Select(e => e.DeserializeJsonContent(_eventTypes.Find(t=> t.Name == e.EventTypeShortName), _logger)) - .ToListAsync(); + var result = await _integrationEventLogContext.IntegrationEventLogs + .Where(e => e.TransactionId == tid && e.State == EventStateEnum.NotPublished).ToListAsync(); + + if(result != null && result.Any()){ + return result.OrderBy(o => o.CreationTime) + .Select(e => e.DeserializeJsonContent(_eventTypes.Find(t=> t.Name == e.EventTypeShortName))); + } + + return new List(); } public Task SaveEventAsync(IntegrationEvent @event, IDbContextTransaction transaction) { if (transaction == null) throw new ArgumentNullException(nameof(transaction)); - var eventLogEntry = new IntegrationEventLogEntry(@event, transaction.TransactionId, _logger); + var eventLogEntry = new IntegrationEventLogEntry(@event, transaction.TransactionId); _integrationEventLogContext.Database.UseTransaction(transaction.GetDbTransaction()); _integrationEventLogContext.IntegrationEventLogs.Add(eventLogEntry); diff --git a/src/Services/Basket/Basket.API/Controllers/BasketController.cs b/src/Services/Basket/Basket.API/Controllers/BasketController.cs index 0bf15fc42..629369dd1 100644 --- a/src/Services/Basket/Basket.API/Controllers/BasketController.cs +++ b/src/Services/Basket/Basket.API/Controllers/BasketController.cs @@ -7,7 +7,9 @@ using Microsoft.eShopOnContainers.Services.Basket.API.Model; using Microsoft.eShopOnContainers.Services.Basket.API.Services; using Microsoft.Extensions.Logging; using System; +using System.Linq; using System.Net; +using System.Security.Claims; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers @@ -61,6 +63,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers basketCheckout.RequestId = (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty) ? guid : basketCheckout.RequestId; +_logger.LogInformation("----- CheckoutAsync userId: {userId} ", userId); + var basket = await _repository.GetBasketAsync(userId); if (basket == null) @@ -68,7 +72,13 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers return BadRequest(); } - var userName = User.FindFirst(x => x.Type == "unique_name").Value; +_logger.LogInformation("----- CheckoutAsync basket: {@basket} ", basket); + +_logger.LogInformation("----- CheckoutAsync user identity: {User} ", string.Join(':', ((ClaimsIdentity)User.Identity).Claims.Select(c => c.Type + " " + c.Value))); + + var userName = User.FindFirst(x => x.Type == ClaimTypes.Name).Value; + + _logger.LogInformation("----- CheckoutAsync userName: {@userName} ", userName); var eventMessage = new UserCheckoutAcceptedIntegrationEvent(userId, userName, basketCheckout.City, basketCheckout.Street, basketCheckout.State, basketCheckout.Country, basketCheckout.ZipCode, basketCheckout.CardNumber, basketCheckout.CardHolderName, diff --git a/src/Services/Catalog/Catalog.API/Startup.cs b/src/Services/Catalog/Catalog.API/Startup.cs index 451d5d5cf..64441f9ea 100644 --- a/src/Services/Catalog/Catalog.API/Startup.cs +++ b/src/Services/Catalog/Catalog.API/Startup.cs @@ -277,7 +277,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API public static IServiceCollection AddIntegrationServices(this IServiceCollection services, IConfiguration configuration) { services.AddTransient>( - sp => (DbConnection c) => new IntegrationEventLogService(c, sp.GetService>())); + sp => (DbConnection c) => new IntegrationEventLogService(c)); services.AddTransient(); diff --git a/src/Services/Ordering/Ordering.API/Application/Behaviors/TransactionBehaviour.cs b/src/Services/Ordering/Ordering.API/Application/Behaviors/TransactionBehaviour.cs index 0320cbd97..be32daeee 100644 --- a/src/Services/Ordering/Ordering.API/Application/Behaviors/TransactionBehaviour.cs +++ b/src/Services/Ordering/Ordering.API/Application/Behaviors/TransactionBehaviour.cs @@ -56,8 +56,6 @@ namespace Ordering.API.Application.Behaviors await _dbContext.CommitTransactionAsync(transaction); transactionId = transaction.TransactionId; - - _logger.LogInformation("----- End transaction {TransactionId} for {CommandName}", transaction.TransactionId, typeName); } await _orderingIntegrationEventService.PublishEventsThroughEventBusAsync(transactionId); diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index 572c83320..fca490f28 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -273,7 +273,7 @@ services.AddSingleton(); services.AddTransient(); services.AddTransient>( - sp => (DbConnection c) => new IntegrationEventLogService(c, sp.GetService>())); + sp => (DbConnection c) => new IntegrationEventLogService(c)); services.AddTransient(); diff --git a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj index 3da5b61f7..67ad7c66f 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj +++ b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj @@ -27,6 +27,7 @@ + diff --git a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs index 456e73397..b3168e5d7 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs @@ -109,7 +109,7 @@ namespace Ordering.SignalrHub RegisterEventBus(services); services.AddOptions(); - + //configure autofac var container = new ContainerBuilder(); container.RegisterModule(new ApplicationModule()); @@ -136,6 +136,10 @@ namespace Ordering.SignalrHub app.UseCors("CorsPolicy"); app.UseRouting(); + + //app.UseAuthorization(); + app.UseAutentication(); + app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/hc", new HealthCheckOptions() diff --git a/src/Services/Webhooks/Webhooks.API/Startup.cs b/src/Services/Webhooks/Webhooks.API/Startup.cs index 1d454a7ab..5859e9e12 100644 --- a/src/Services/Webhooks/Webhooks.API/Startup.cs +++ b/src/Services/Webhooks/Webhooks.API/Startup.cs @@ -291,7 +291,7 @@ namespace Webhooks.API public static IServiceCollection AddIntegrationServices(this IServiceCollection services, IConfiguration configuration) { services.AddTransient>( - sp => (DbConnection c) => new IntegrationEventLogService(c, sp.GetService>())); + sp => (DbConnection c) => new IntegrationEventLogService(c)); if (configuration.GetValue("AzureServiceBusEnabled")) { diff --git a/src/Web/WebMVC/Services/BasketService.cs b/src/Web/WebMVC/Services/BasketService.cs index dd0a50feb..e9f015e54 100644 --- a/src/Web/WebMVC/Services/BasketService.cs +++ b/src/Web/WebMVC/Services/BasketService.cs @@ -1,4 +1,5 @@ using Microsoft.eShopOnContainers.WebMVC.ViewModels; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System.Collections.Generic; @@ -14,15 +15,17 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services { private readonly IOptions _settings; private readonly HttpClient _apiClient; + private readonly ILogger _logger; private readonly string _basketByPassUrl; private readonly string _purchaseUrl; private readonly string _bffUrl; - public BasketService(HttpClient httpClient, IOptions settings) + public BasketService(HttpClient httpClient, IOptions settings, ILogger logger) { _apiClient = httpClient; _settings = settings; + _logger =logger; _basketByPassUrl = $"{_settings.Value.PurchaseUrl}/api/v1/b/basket"; _purchaseUrl = $"{_settings.Value.PurchaseUrl}/api/v1"; @@ -57,6 +60,8 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services var uri = API.Basket.CheckoutBasket(_basketByPassUrl); var basketContent = new StringContent(JsonConvert.SerializeObject(basket), System.Text.Encoding.UTF8, "application/json"); + _logger.LogInformation("Uri chechout {uri}", uri); + var response = await _apiClient.PostAsync(uri, basketContent); response.EnsureSuccessStatusCode(); From c8da44049a7211a7db9e1c13dfddda4d177e9313 Mon Sep 17 00:00:00 2001 From: ericuss Date: Thu, 8 Aug 2019 10:01:18 +0200 Subject: [PATCH 056/113] remove not needed code --- .../Marketing.FunctionalTests/MarketingScenarioBase.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs b/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs index 76be3b099..025934220 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs +++ b/src/Services/Marketing/Marketing.FunctionalTests/MarketingScenarioBase.cs @@ -27,8 +27,8 @@ namespace Marketing.FunctionalTests .UseContentRoot(Path.GetDirectoryName(path)) .ConfigureAppConfiguration(cb => { - var h = cb.AddJsonFile("appsettings.json", optional: false) - .AddEnvironmentVariables(); + cb.AddJsonFile("appsettings.json", optional: false) + .AddEnvironmentVariables(); }) .CaptureStartupErrors(true) .UseStartup(); @@ -40,7 +40,6 @@ namespace Marketing.FunctionalTests { var logger = services.GetService>(); - logger.LogError("Migrating MarketingContextSeed"); new MarketingContextSeed() .SeedAsync(context, logger) .Wait(); From f1cb1b6824ec8c31125d11489b6ed462016163a6 Mon Sep 17 00:00:00 2001 From: ericuss Date: Thu, 8 Aug 2019 10:27:51 +0200 Subject: [PATCH 057/113] Fix authentication in Ordering.SignalR --- .../Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj | 2 ++ src/Services/Ordering/Ordering.SignalrHub/Startup.cs | 4 ++-- src/_build/dependencies.props | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj index 67ad7c66f..52a2a3853 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj +++ b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj @@ -22,6 +22,8 @@ + + diff --git a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs index b3168e5d7..472644781 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Startup.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/Startup.cs @@ -137,8 +137,8 @@ namespace Ordering.SignalrHub app.UseCors("CorsPolicy"); app.UseRouting(); - //app.UseAuthorization(); - app.UseAutentication(); + app.UseAuthentication(); + app.UseAuthorization(); app.UseEndpoints(endpoints => { diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index f472ce237..44651cb53 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -51,6 +51,8 @@ 1.0.2 3.0.0-preview4-19123-01 3.0.0-preview7.19365.7 + 3.0.0-preview4-19123-01 + 3.0.0-preview4-19123-01 3.0.0-alpha1-10670 2.2.0-preview2-35157 3.0.0-alpha1-34847 From da6f9d7ea7e6e7954a482865575b0000e4b27926 Mon Sep 17 00:00:00 2001 From: Nish Anil Date: Thu, 8 Aug 2019 21:45:48 +0530 Subject: [PATCH 058/113] Create ReadMe.md --- src/_build/ReadMe.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 src/_build/ReadMe.md diff --git a/src/_build/ReadMe.md b/src/_build/ReadMe.md new file mode 100644 index 000000000..536add60b --- /dev/null +++ b/src/_build/ReadMe.md @@ -0,0 +1 @@ +`Please define why we are using this here.` From bf85169d67340a088093321f5a71f169bce49a35 Mon Sep 17 00:00:00 2001 From: ericuss Date: Mon, 12 Aug 2019 08:27:19 +0200 Subject: [PATCH 059/113] partial checkin trying to fix checkout process --- .../Controllers/BasketController.cs | 6 +- ...PaymentMethodVerifiedDomainEventHandler.cs | 5 +- .../Factories/OrderingDbContextFactory.cs | 36 +++ ...2242_Change_Relation_Of_Orders.Designer.cs | 252 ++++++++++++++++++ ...0190808132242_Change_Relation_Of_Orders.cs | 16 ++ .../OrderingContextModelSnapshot.cs | 49 ++-- .../AggregatesModel/OrderAggregate/Address.cs | 2 +- .../OrderEntityTypeConfiguration.cs | 8 +- .../OrderingContext.cs | 2 +- .../Repositories/OrderRepository.cs | 7 +- 10 files changed, 353 insertions(+), 30 deletions(-) create mode 100644 src/Services/Ordering/Ordering.API/Infrastructure/Factories/OrderingDbContextFactory.cs create mode 100644 src/Services/Ordering/Ordering.API/Infrastructure/Migrations/20190808132242_Change_Relation_Of_Orders.Designer.cs create mode 100644 src/Services/Ordering/Ordering.API/Infrastructure/Migrations/20190808132242_Change_Relation_Of_Orders.cs diff --git a/src/Services/Basket/Basket.API/Controllers/BasketController.cs b/src/Services/Basket/Basket.API/Controllers/BasketController.cs index 629369dd1..fca033301 100644 --- a/src/Services/Basket/Basket.API/Controllers/BasketController.cs +++ b/src/Services/Basket/Basket.API/Controllers/BasketController.cs @@ -63,7 +63,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers basketCheckout.RequestId = (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty) ? guid : basketCheckout.RequestId; -_logger.LogInformation("----- CheckoutAsync userId: {userId} ", userId); + _logger.LogInformation("----- CheckoutAsync userId: {userId} ", userId); var basket = await _repository.GetBasketAsync(userId); @@ -72,9 +72,9 @@ _logger.LogInformation("----- CheckoutAsync userId: {userId} ", userId); return BadRequest(); } -_logger.LogInformation("----- CheckoutAsync basket: {@basket} ", basket); + _logger.LogInformation("----- CheckoutAsync basket: {@basket} ", basket); -_logger.LogInformation("----- CheckoutAsync user identity: {User} ", string.Join(':', ((ClaimsIdentity)User.Identity).Claims.Select(c => c.Type + " " + c.Value))); + _logger.LogInformation("----- CheckoutAsync user identity: {User} ", string.Join(':', ((ClaimsIdentity)User.Identity).Claims.Select(c => c.Type + " " + c.Value))); var userName = User.FindFirst(x => x.Type == ClaimTypes.Name).Value; diff --git a/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/BuyerAndPaymentMethodVerified/UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs b/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/BuyerAndPaymentMethodVerified/UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs index bea8eaac5..32b927368 100644 --- a/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/BuyerAndPaymentMethodVerified/UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs +++ b/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/BuyerAndPaymentMethodVerified/UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs @@ -26,12 +26,13 @@ namespace Ordering.API.Application.DomainEventHandlers.BuyerAndPaymentMethodVeri // then we can update the original Order with the BuyerId and PaymentId (foreign keys) public async Task Handle(BuyerAndPaymentMethodVerifiedDomainEvent buyerPaymentMethodVerifiedEvent, CancellationToken cancellationToken) { + var log = _logger.CreateLogger(); + log.LogInformation("----- Handling BuyerAndPaymentMethodVerifiedDomainEvent - buyerPaymentMethodVerifiedEvent: {@buyerPaymentMethodVerifiedEvent}", buyerPaymentMethodVerifiedEvent); var orderToUpdate = await _orderRepository.GetAsync(buyerPaymentMethodVerifiedEvent.OrderId); orderToUpdate.SetBuyerId(buyerPaymentMethodVerifiedEvent.Buyer.Id); orderToUpdate.SetPaymentId(buyerPaymentMethodVerifiedEvent.Payment.Id); - _logger.CreateLogger() - .LogTrace("Order with Id: {OrderId} has been successfully updated with a payment method {PaymentMethod} ({Id})", + log.LogTrace("Order with Id: {OrderId} has been successfully updated with a payment method {PaymentMethod} ({Id})", buyerPaymentMethodVerifiedEvent.OrderId, nameof(buyerPaymentMethodVerifiedEvent.Payment), buyerPaymentMethodVerifiedEvent.Payment.Id); } } diff --git a/src/Services/Ordering/Ordering.API/Infrastructure/Factories/OrderingDbContextFactory.cs b/src/Services/Ordering/Ordering.API/Infrastructure/Factories/OrderingDbContextFactory.cs new file mode 100644 index 000000000..a3079b32f --- /dev/null +++ b/src/Services/Ordering/Ordering.API/Infrastructure/Factories/OrderingDbContextFactory.cs @@ -0,0 +1,36 @@ +using Microsoft.eShopOnContainers.Services.Ordering.Infrastructure; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; + +namespace Ordering.API.Infrastructure.Factories +{ + public class OrderingDbContextFactory : IDesignTimeDbContextFactory + { + public OrderingContext CreateDbContext(string[] args) + { + var config = new ConfigurationBuilder() + .SetBasePath(Path.Combine(Directory.GetCurrentDirectory())) + .AddJsonFile("appsettings.json") + .AddEnvironmentVariables() + .Build(); + + var optionsBuilder = new DbContextOptionsBuilder(); + + optionsBuilder.UseSqlServer(config["ConnectionString"], sqlServerOptionsAction: o => o.MigrationsAssembly("Ordering.API")); + + return new OrderingContext(optionsBuilder.Options); + } + } +} \ No newline at end of file diff --git a/src/Services/Ordering/Ordering.API/Infrastructure/Migrations/20190808132242_Change_Relation_Of_Orders.Designer.cs b/src/Services/Ordering/Ordering.API/Infrastructure/Migrations/20190808132242_Change_Relation_Of_Orders.Designer.cs new file mode 100644 index 000000000..c9d553287 --- /dev/null +++ b/src/Services/Ordering/Ordering.API/Infrastructure/Migrations/20190808132242_Change_Relation_Of_Orders.Designer.cs @@ -0,0 +1,252 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Microsoft.eShopOnContainers.Services.Ordering.Infrastructure; + +namespace Ordering.API.Infrastructure.Migrations +{ + [DbContext(typeof(OrderingContext))] + [Migration("20190808132242_Change_Relation_Of_Orders")] + partial class Change_Relation_Of_Orders + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "3.0.0-preview7.19362.6") + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("Relational:Sequence:.orderitemseq", "'orderitemseq', '', '1', '10', '', '', 'Int64', 'False'") + .HasAnnotation("Relational:Sequence:ordering.buyerseq", "'buyerseq', 'ordering', '1', '10', '', '', 'Int64', 'False'") + .HasAnnotation("Relational:Sequence:ordering.orderseq", "'orderseq', 'ordering', '1', '10', '', '', 'Int64', 'False'") + .HasAnnotation("Relational:Sequence:ordering.paymentseq", "'paymentseq', 'ordering', '1', '10', '', '', 'Int64', 'False'") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.Buyer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:HiLoSequenceName", "buyerseq") + .HasAnnotation("SqlServer:HiLoSequenceSchema", "ordering") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.SequenceHiLo); + + b.Property("IdentityGuid") + .IsRequired() + .HasMaxLength(200); + + b.Property("Name"); + + b.HasKey("Id"); + + b.HasIndex("IdentityGuid") + .IsUnique(); + + b.ToTable("buyers","ordering"); + }); + + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.CardType", b => + { + b.Property("Id") + .HasDefaultValue(1); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200); + + b.HasKey("Id"); + + b.ToTable("cardtypes","ordering"); + }); + + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.PaymentMethod", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:HiLoSequenceName", "paymentseq") + .HasAnnotation("SqlServer:HiLoSequenceSchema", "ordering") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.SequenceHiLo); + + b.Property("Alias") + .IsRequired() + .HasMaxLength(200); + + b.Property("BuyerId"); + + b.Property("CardHolderName") + .IsRequired() + .HasMaxLength(200); + + b.Property("CardNumber") + .IsRequired() + .HasMaxLength(25); + + b.Property("CardTypeId"); + + b.Property("Expiration"); + + b.HasKey("Id"); + + b.HasIndex("BuyerId"); + + b.HasIndex("CardTypeId"); + + b.ToTable("paymentmethods","ordering"); + }); + + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:HiLoSequenceName", "orderseq") + .HasAnnotation("SqlServer:HiLoSequenceSchema", "ordering") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.SequenceHiLo); + + b.Property("BuyerId"); + + b.Property("Description"); + + b.Property("OrderDate"); + + b.Property("OrderStatusId"); + + b.Property("PaymentMethodId"); + + b.HasKey("Id"); + + b.HasIndex("BuyerId"); + + b.HasIndex("OrderStatusId"); + + b.HasIndex("PaymentMethodId"); + + b.ToTable("orders","ordering"); + }); + + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.OrderItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation("SqlServer:HiLoSequenceName", "orderitemseq") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.SequenceHiLo); + + b.Property("Discount"); + + b.Property("OrderId"); + + b.Property("PictureUrl"); + + b.Property("ProductId"); + + b.Property("ProductName") + .IsRequired(); + + b.Property("UnitPrice"); + + b.Property("Units"); + + b.HasKey("Id"); + + b.HasIndex("OrderId"); + + b.ToTable("orderItems","ordering"); + }); + + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.OrderStatus", b => + { + b.Property("Id") + .HasDefaultValue(1); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200); + + b.HasKey("Id"); + + b.ToTable("orderstatus","ordering"); + }); + + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Idempotency.ClientRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd(); + + b.Property("Name") + .IsRequired(); + + b.Property("Time"); + + b.HasKey("Id"); + + b.ToTable("requests","ordering"); + }); + + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.PaymentMethod", b => + { + b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.Buyer", null) + .WithMany("PaymentMethods") + .HasForeignKey("BuyerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.CardType", "CardType") + .WithMany() + .HasForeignKey("CardTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.Order", b => + { + b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.Buyer", null) + .WithMany() + .HasForeignKey("BuyerId"); + + b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.OrderStatus", "OrderStatus") + .WithMany() + .HasForeignKey("OrderStatusId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.PaymentMethod", null) + .WithMany() + .HasForeignKey("PaymentMethodId") + .OnDelete(DeleteBehavior.Restrict); + + b.OwnsOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.Address", "Address", b1 => + { + b1.Property("OrderId"); + + b1.Property("City"); + + b1.Property("Country"); + + b1.Property("State"); + + b1.Property("Street"); + + b1.Property("ZipCode"); + + b1.HasKey("OrderId"); + + b1.ToTable("orders"); + + b1.WithOwner() + .HasForeignKey("OrderId"); + }); + }); + + modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.OrderItem", b => + { + b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.Order", null) + .WithMany("OrderItems") + .HasForeignKey("OrderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Services/Ordering/Ordering.API/Infrastructure/Migrations/20190808132242_Change_Relation_Of_Orders.cs b/src/Services/Ordering/Ordering.API/Infrastructure/Migrations/20190808132242_Change_Relation_Of_Orders.cs new file mode 100644 index 000000000..ba01fdcec --- /dev/null +++ b/src/Services/Ordering/Ordering.API/Infrastructure/Migrations/20190808132242_Change_Relation_Of_Orders.cs @@ -0,0 +1,16 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Ordering.API.Infrastructure.Migrations +{ + public partial class Change_Relation_Of_Orders : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + + } + } +} diff --git a/src/Services/Ordering/Ordering.API/Infrastructure/Migrations/OrderingContextModelSnapshot.cs b/src/Services/Ordering/Ordering.API/Infrastructure/Migrations/OrderingContextModelSnapshot.cs index fc5e0d1da..ab7951bc7 100644 --- a/src/Services/Ordering/Ordering.API/Infrastructure/Migrations/OrderingContextModelSnapshot.cs +++ b/src/Services/Ordering/Ordering.API/Infrastructure/Migrations/OrderingContextModelSnapshot.cs @@ -1,12 +1,10 @@ // +using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage; -using Microsoft.EntityFrameworkCore.Storage.Internal; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.eShopOnContainers.Services.Ordering.Infrastructure; -using System; namespace Ordering.API.Migrations { @@ -17,7 +15,8 @@ namespace Ordering.API.Migrations { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "2.0.1-rtm-125") + .HasAnnotation("ProductVersion", "3.0.0-preview7.19362.6") + .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("Relational:Sequence:.orderitemseq", "'orderitemseq', '', '1', '10', '', '', 'Int64', 'False'") .HasAnnotation("Relational:Sequence:ordering.buyerseq", "'buyerseq', 'ordering', '1', '10', '', '', 'Int64', 'False'") .HasAnnotation("Relational:Sequence:ordering.orderseq", "'orderseq', 'ordering', '1', '10', '', '', 'Int64', 'False'") @@ -184,29 +183,32 @@ namespace Ordering.API.Migrations modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.PaymentMethod", b => { - b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.Buyer") + b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.Buyer", null) .WithMany("PaymentMethods") .HasForeignKey("BuyerId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.CardType", "CardType") .WithMany() .HasForeignKey("CardTypeId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.Order", b => { - b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.Buyer") + b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.Buyer", null) .WithMany() .HasForeignKey("BuyerId"); b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.OrderStatus", "OrderStatus") .WithMany() .HasForeignKey("OrderStatusId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); - b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.PaymentMethod") + b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate.PaymentMethod", null) .WithMany() .HasForeignKey("PaymentMethodId") .OnDelete(DeleteBehavior.Restrict); @@ -215,21 +217,32 @@ namespace Ordering.API.Migrations { b1.Property("OrderId"); - b1.ToTable("orders","ordering"); + b1.Property("City"); + + b1.Property("Country"); - b1.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.Order") - .WithOne("Address") - .HasForeignKey("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.Address", "OrderId") - .OnDelete(DeleteBehavior.Cascade); + b1.Property("State"); + + b1.Property("Street"); + + b1.Property("ZipCode"); + + b1.HasKey("OrderId"); + + b1.ToTable("orders"); + + b1.WithOwner() + .HasForeignKey("OrderId"); }); }); modelBuilder.Entity("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.OrderItem", b => { - b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.Order") + b.HasOne("Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate.Order", null) .WithMany("OrderItems") .HasForeignKey("OrderId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); #pragma warning restore 612, 618 } diff --git a/src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Address.cs b/src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Address.cs index 9576940df..b552f5546 100644 --- a/src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Address.cs +++ b/src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Address.cs @@ -12,7 +12,7 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.O public String Country { get; private set; } public String ZipCode { get; private set; } - private Address() { } + public Address() { } public Address(string street, string city, string state, string country, string zipcode) { diff --git a/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderEntityTypeConfiguration.cs b/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderEntityTypeConfiguration.cs index d4eb1fb9a..c4c7fce38 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderEntityTypeConfiguration.cs +++ b/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderEntityTypeConfiguration.cs @@ -21,7 +21,11 @@ namespace Ordering.Infrastructure.EntityConfigurations .ForSqlServerUseSequenceHiLo("orderseq", OrderingContext.DEFAULT_SCHEMA); //Address value object persisted as owned entity type supported since EF Core 2.0 - orderConfiguration.OwnsOne(o => o.Address); + orderConfiguration + .OwnsOne(o => o.Address, a => + { + a.WithOwner(); + }); orderConfiguration.Property("OrderDate").IsRequired(); orderConfiguration.Property("BuyerId").IsRequired(false); @@ -30,7 +34,7 @@ namespace Ordering.Infrastructure.EntityConfigurations orderConfiguration.Property("Description").IsRequired(false); var navigation = orderConfiguration.Metadata.FindNavigation(nameof(Order.OrderItems)); - + // DDD Patterns comment: //Set as field (New since EF 1.1) to access the OrderItem collection property through its field navigation.SetPropertyAccessMode(PropertyAccessMode.Field); diff --git a/src/Services/Ordering/Ordering.Infrastructure/OrderingContext.cs b/src/Services/Ordering/Ordering.Infrastructure/OrderingContext.cs index 40fd9be00..d7117ba0d 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/OrderingContext.cs +++ b/src/Services/Ordering/Ordering.Infrastructure/OrderingContext.cs @@ -27,7 +27,7 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure private readonly IMediator _mediator; private IDbContextTransaction _currentTransaction; - private OrderingContext(DbContextOptions options) : base(options) { } + public OrderingContext(DbContextOptions options) : base(options) { } public IDbContextTransaction GetCurrentTransaction() => _currentTransaction; diff --git a/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs b/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs index 4aaf738af..1047d6c7e 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs +++ b/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs @@ -33,15 +33,16 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositor public async Task GetAsync(int orderId) { - var order = await _context.Orders.FindAsync(orderId); + var order = await _context + .Orders + .Include(x => x.Address) + .FirstOrDefaultAsync(o => o.Id == orderId); if (order != null) { await _context.Entry(order) .Collection(i => i.OrderItems).LoadAsync(); await _context.Entry(order) .Reference(i => i.OrderStatus).LoadAsync(); - await _context.Entry(order) - .Reference(i => i.Address).LoadAsync(); } return order; From fe0fd36e0fd8bdf2fddd4245bce4ef0f8c9d6774 Mon Sep 17 00:00:00 2001 From: Erik Pique Date: Mon, 19 Aug 2019 09:24:58 +0200 Subject: [PATCH 060/113] add grpc basket --- docker-compose.override.yml | 6 + .../Controllers/BasketController.cs | 7 +- .../aggregator/Controllers/OrderController.cs | 2 +- .../Mobile.Bff.Shopping/aggregator/Dockerfile | 4 +- .../Filters/AuthorizeCheckOperationFilter.cs | 19 +-- ...ttpClientAuthorizationDelegatingHandler.cs | 13 +- .../Mobile.Shopping.HttpAggregator.csproj | 39 ++---- .../Mobile.Bff.Shopping/aggregator/Program.cs | 41 +++++++ .../aggregator/Services/BasketService.cs | 113 ++++++++++++++++-- .../aggregator/Services/CatalogService.cs | 31 +++-- .../aggregator/Services/IBasketService.cs | 2 +- .../Mobile.Bff.Shopping/aggregator/Startup.cs | 79 ++++++------ .../aggregator/appsettings.json | 5 + .../aggregator/appsettings.localhost.json | 15 +++ .../Basket/Basket.API/Basket.API.csproj | 9 ++ .../Basket/Basket.API/Grpc/BasketService.cs | 100 ++++++++++++++++ .../Repositories/RedisBasketRepository.cs | 2 +- src/Services/Basket/Basket.API/Program.cs | 27 ++++- .../Basket/Basket.API/Proto/basket.proto | 38 ++++++ src/Services/Basket/Basket.API/Startup.cs | 42 +++++-- .../Basket/Basket.API/appsettings.json | 5 + src/_build/dependencies.props | 1 + 22 files changed, 476 insertions(+), 124 deletions(-) create mode 100644 src/Services/Basket/Basket.API/Grpc/BasketService.cs create mode 100644 src/Services/Basket/Basket.API/Proto/basket.proto diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 60f2efb45..97379a4b0 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -219,6 +219,7 @@ services: - MarketingUrlHC=http://marketing.api/hc - PaymentUrlHC=http://payment.api/hc - LocationUrlHC=http://locations.api/hc + - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 ports: - "5200:80" volumes: @@ -235,6 +236,7 @@ services: - MarketingUrlHC=http://marketing.api/hc - PaymentUrlHC=http://payment.api/hc - LocationUrlHC=http://locations.api/hc + - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 ports: - "5201:80" volumes: @@ -251,6 +253,7 @@ services: - MarketingUrlHC=http://marketing.api/hc - PaymentUrlHC=http://payment.api/hc - LocationUrlHC=http://locations.api/hc + - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 ports: - "5202:80" volumes: @@ -267,6 +270,7 @@ services: - MarketingUrlHC=http://marketing.api/hc - PaymentUrlHC=http://payment.api/hc - LocationUrlHC=http://locations.api/hc + - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 ports: - "5203:80" volumes: @@ -286,6 +290,7 @@ services: - MarketingUrlHC=http://marketing.api/hc - PaymentUrlHC=http://payment.api/hc - LocationUrlHC=http://locations.api/hc + - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 ports: - "5120:80" @@ -303,6 +308,7 @@ services: - MarketingUrlHC=http://marketing.api/hc - PaymentUrlHC=http://payment.api/hc - LocationUrlHC=http://locations.api/hc + - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 ports: - "5121:80" diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/BasketController.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/BasketController.cs index a2c0d1fea..65b07239a 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/BasketController.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/BasketController.cs @@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services; using System; -using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; @@ -36,7 +35,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Controllers } // Retrieve the current basket - var basket = await _basket.GetByIdAsync(data.BuyerId) ?? new BasketData(data.BuyerId); + var basket = await _basket.GetById(data.BuyerId) ?? new BasketData(data.BuyerId); var catalogItems = await _catalog.GetCatalogItemsAsync(data.Items.Select(x => x.ProductId)); @@ -76,7 +75,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Controllers } // Retrieve the current basket - var currentBasket = await _basket.GetByIdAsync(data.BasketId); + var currentBasket = await _basket.GetById(data.BasketId); if (currentBasket == null) { return BadRequest($"Basket with id {data.BasketId} not found."); @@ -118,7 +117,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Controllers //item.PictureUri = // Step 2: Get current basket status - var currentBasket = (await _basket.GetByIdAsync(data.BasketId)) ?? new BasketData(data.BasketId); + var currentBasket = (await _basket.GetById(data.BasketId)) ?? new BasketData(data.BasketId); // Step 3: Merge current status with new product currentBasket.Items.Add(new BasketDataItem() { diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/OrderController.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/OrderController.cs index a4b33c6cb..ac359b4b5 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/OrderController.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/OrderController.cs @@ -32,7 +32,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Controllers return BadRequest("Need a valid basketid"); } // Get the basket data and build a order draft based on it - var basket = await _basketService.GetByIdAsync(basketId); + var basket = await _basketService.GetById(basketId); if (basket == null) { diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile index 9b03eccbd..3d89c9b27 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs index 21997360b..3b8298bfe 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs @@ -1,7 +1,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Filters { using Microsoft.AspNetCore.Authorization; - using Swashbuckle.AspNetCore.Swagger; + using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using System.Linq; @@ -10,7 +10,7 @@ { public class AuthorizeCheckOperationFilter : IOperationFilter { - public void Apply(Operation operation, OperationFilterContext context) + public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || @@ -18,14 +18,19 @@ if (!hasAuthorize) return; - operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); + operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" }); - operation.Security = new List>> + var oAuthScheme = new OpenApiSecurityScheme { - new Dictionary> + Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } + }; + + operation.Security = new List + { + new OpenApiSecurityRequirement { - { "oauth2", new [] { "Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator" } } + [ oAuthScheme ] = new [] { "Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator" } } }; } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Infrastructure/HttpClientAuthorizationDelegatingHandler.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Infrastructure/HttpClientAuthorizationDelegatingHandler.cs index 967a8c826..4562139df 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Infrastructure/HttpClientAuthorizationDelegatingHandler.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Infrastructure/HttpClientAuthorizationDelegatingHandler.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; @@ -8,18 +9,22 @@ using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastructure { - public class HttpClientAuthorizationDelegatingHandler - : DelegatingHandler + public class HttpClientAuthorizationDelegatingHandler : DelegatingHandler { private readonly IHttpContextAccessor _httpContextAccesor; + private readonly ILogger _logger; - public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccesor) + public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccesor, ILogger logger) { _httpContextAccesor = httpContextAccesor; + _logger = logger; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + request.Version = new System.Version(2, 0); + request.Method = HttpMethod.Get; + var authorizationHeader = _httpContextAccesor.HttpContext .Request.Headers["Authorization"]; @@ -35,6 +40,8 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastruct request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); } + _logger.LogInformation("@@@@@@@@@@@@@@@@@ {@request}", request); + return await base.SendAsync(request, cancellationToken); } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj index 57efd4a9f..ca8768a66 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj @@ -1,4 +1,4 @@ - - - - - netcoreapp2.2 - Mobile.Shopping.HttpAggregator - Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator - ..\..\..\docker-compose.dcproj - $(LangVersion) - - + - - - - - - - - - - - - - - - - - + + diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs index 5d1840192..0dc91cbc0 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs @@ -1,13 +1,21 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Configuration; using Serilog; +using System.IO; +using System.Net; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator { public class Program { + private static IConfiguration _configuration; + public static void Main(string[] args) { + _configuration = GetConfiguration(); + BuildWebHost(args).Run(); } @@ -24,6 +32,20 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator ReloadOnChange = false }); }) + .ConfigureKestrel(options => + { + var ports = GetDefinedPorts(_configuration); + + options.Listen(IPAddress.Any, ports.httpPort, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http1AndHttp2; + }); + + options.Listen(IPAddress.Any, ports.grpcPort, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http2; + }); + }) .UseStartup() .UseSerilog((builderContext, config) => { @@ -33,5 +55,24 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator .WriteTo.Console(); }) .Build(); + + private static IConfiguration GetConfiguration() + { + var builder = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) + .AddEnvironmentVariables(); + + var config = builder.Build(); + + return builder.Build(); + } + + private static (int httpPort, int grpcPort) GetDefinedPorts(IConfiguration config) + { + var grpcPort = config.GetValue("GRPC_PORT", 5001); + var port = config.GetValue("PORT", 80); + return (port, grpcPort); + } } } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs index 5186fe361..657e3cd54 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs @@ -1,41 +1,130 @@ -using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; +using grpc; +using Grpc.Net.Client; +using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Newtonsoft.Json; +using System; +using System.Linq; using System.Net.Http; using System.Threading.Tasks; +using static grpc.Basket; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services { public class BasketService : IBasketService { - private readonly HttpClient _httpClient; - private readonly ILogger _logger; private readonly UrlsConfig _urls; + private readonly ILogger _logger; - public BasketService(HttpClient httpClient, ILogger logger, IOptions config) + public BasketService(HttpClient httpClient, IOptions config, ILogger logger) { _httpClient = httpClient; - _logger = logger; _urls = config.Value; + _logger = logger; } - public async Task GetByIdAsync(string id) + public async Task GetById(string id) { - var data = await _httpClient.GetStringAsync(_urls.Basket + UrlsConfig.BasketOperations.GetItemById(id)); + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GetById @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Http2UnencryptedSupport disable @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + + _httpClient.BaseAddress = new Uri("http://localhost:5001"); + + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ {_httpClient.BaseAddress} @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", _httpClient.BaseAddress); + + var client = GrpcClient.Create(_httpClient); + + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ client create @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + + var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); + + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ call grpc server @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + + _logger.LogInformation("############## DATA: {@a}", response.Buyerid); + + //if (streaming.IsCompleted) + //{ + // _logger.LogInformation("############## DATA: {@a}", streaming.GetResult()); + //} + //var streaming = client.GetBasketById(new BasketRequest { Id = id }); - var basket = !string.IsNullOrEmpty(data) ? JsonConvert.DeserializeObject(data) : null; - return basket; + //var status = streaming.GetStatus(); + + //if (status.StatusCode == Grpc.Core.StatusCode.OK) + //{ + // return null; + //} + + return null; + //return MapToBasketData(response.ResponseStream); } public async Task UpdateAsync(BasketData currentBasket) { - var basketContent = new StringContent(JsonConvert.SerializeObject(currentBasket), System.Text.Encoding.UTF8, "application/json"); + _httpClient.BaseAddress = new Uri(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket()); + + var client = GrpcClient.Create(_httpClient); + var request = MapToCustomerBasketRequest(currentBasket); + + await client.UpdateBasketAsync(request); + } + + private BasketData MapToBasketData(CustomerBasketResponse customerBasketRequest) + { + if (customerBasketRequest == null) + { + return null; + } + + var map = new BasketData + { + BuyerId = customerBasketRequest.Buyerid + }; + + customerBasketRequest.Items.ToList().ForEach(item => map.Items.Add(new BasketDataItem + { + Id = item.Id, + OldUnitPrice = (decimal)item.Oldunitprice, + PictureUrl = item.Pictureurl, + ProductId = item.Productid, + ProductName = item.Productname, + Quantity = item.Quantity, + UnitPrice = (decimal)item.Unitprice + })); + + return map; + } + + private CustomerBasketRequest MapToCustomerBasketRequest(BasketData basketData) + { + if (basketData == null) + { + return null; + } + + var map = new CustomerBasketRequest + { + Buyerid = basketData.BuyerId + }; + + basketData.Items.ToList().ForEach(item => map.Items.Add(new BasketItemResponse + { + Id = item.Id, + Oldunitprice = (double)item.OldUnitPrice, + Pictureurl = item.PictureUrl, + Productid = item.ProductId, + Productname = item.ProductName, + Quantity = item.Quantity, + Unitprice = (double)item.UnitPrice + })); - var data = await _httpClient.PostAsync(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket(), basketContent); + return map; } } } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/CatalogService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/CatalogService.cs index 69bca2b39..fbcc8349b 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/CatalogService.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/CatalogService.cs @@ -1,33 +1,37 @@ -using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; +using CatalogApi; +using Grpc.Net.Client; +using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; +using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; +using static CatalogApi.Catalog; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services { public class CatalogService : ICatalogService { private readonly HttpClient _httpClient; - private readonly ILogger _logger; private readonly UrlsConfig _urls; - public CatalogService(HttpClient httpClient, ILogger logger, IOptions config) + public CatalogService(HttpClient httpClient, IOptions config) { _httpClient = httpClient; - _logger = logger; _urls = config.Value; } public async Task GetCatalogItemAsync(int id) { - var stringContent = await _httpClient.GetStringAsync(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id)); - var catalogItem = JsonConvert.DeserializeObject(stringContent); + _httpClient.BaseAddress = new Uri(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id)); - return catalogItem; + var client = GrpcClient.Create(_httpClient); + var request = new CatalogItemRequest { Id = id }; + var response = await client.GetItemByIdAsync(request); + + return MapToCatalogItemResponse(response); } public async Task> GetCatalogItemsAsync(IEnumerable ids) @@ -37,5 +41,16 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services return catalogItems; } + + private CatalogItem MapToCatalogItemResponse(CatalogItemResponse catalogItemResponse) + { + return new CatalogItem + { + Id = catalogItemResponse.Id, + Name = catalogItemResponse.Name, + PictureUri = catalogItemResponse.PictureUri, + Price = (decimal)catalogItemResponse.Price + }; + } } } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/IBasketService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/IBasketService.cs index ad49e1adb..d7a390c75 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/IBasketService.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/IBasketService.cs @@ -5,7 +5,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services { public interface IBasketService { - Task GetByIdAsync(string id); + Task GetById(string id); Task UpdateAsync(BasketData currentBasket); diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index c60cb787a..2a9d0b341 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Filters.Basket.API.Infrastructure.Filters; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastructure; @@ -14,9 +13,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Models; using Polly; using Polly.Extensions.Http; -using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; @@ -63,19 +62,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator app.UsePathBase(pathBase); } - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - - app.UseCors("CorsPolicy"); - if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); @@ -86,15 +72,31 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator app.UseHsts(); } - app.UseAuthentication(); + app.UseCors("CorsPolicy"); app.UseHttpsRedirection(); - app.UseMvc(); + app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + }); app.UseSwagger().UseSwaggerUI(c => { c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1"); - c.OAuthClientId("Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregatorwaggerui"); + c.OAuthClientId("mobileshoppingaggswaggerui"); c.OAuthClientSecret(string.Empty); c.OAuthRealm(string.Empty); c.OAuthAppName("Purchase BFF Swagger UI"); @@ -109,29 +111,32 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator services.AddOptions(); services.Configure(configuration.GetSection("urls")); - services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + services.AddControllers() + .AddNewtonsoftJson(); services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info + options.SwaggerDoc("v1", new OpenApiInfo { Title = "Shopping Aggregator for Mobile Clients", Version = "v1", - Description = "Shopping Aggregator for Mobile Clients", - TermsOfService = "Terms Of Service" + Description = "Shopping Aggregator for Mobile Clients" }); - - options.AddSecurityDefinition("oauth2", new OAuth2Scheme + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { - Type = "oauth2", - Flow = "implicit", - AuthorizationUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize", - TokenUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/token", - Scopes = new Dictionary() + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() { - { "mobileshoppingagg", "Shopping Aggregator for Mobile Clients" } + Implicit = new OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() + { + { "mobileshoppingagg", "Shopping Aggregator for Mobile Clients" } + } + } } }); @@ -152,7 +157,8 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator } public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration) { - JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); + JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); + var identityUrl = configuration.GetValue("urls:identity"); services.AddAuthentication(options => @@ -166,15 +172,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator options.Authority = identityUrl; options.RequireHttpsMetadata = false; options.Audience = "mobileshoppingagg"; - options.Events = new JwtBearerEvents() - { - OnAuthenticationFailed = async ctx => - { - }, - OnTokenValidated = async ctx => - { - } - }; }); return services; diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.json b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.json index 26bb0ac7a..95b8bad4c 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.json +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.json @@ -1,4 +1,9 @@ { + "Kestrel": { + "EndpointDefaults": { + "Protocols": "Http2" + } + }, "Logging": { "IncludeScopes": false, "Debug": { diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json index 57b5e894d..91bbf5f87 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json @@ -4,5 +4,20 @@ "catalog": "http://localhost:55101", "orders": "http://localhost:55102", "identity": "http://localhost:55105" + }, + "IdentityUrlExternal": "http://localhost:5105", + "IdentityUrl": "http://localhost:5105", + "Logging": { + "IncludeScopes": false, + "Debug": { + "LogLevel": { + "Default": "Debug" + } + }, + "Console": { + "LogLevel": { + "Default": "Debug" + } + } } } diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index 5281f9107..78cd14b2a 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -21,6 +21,9 @@ + + + @@ -39,6 +42,12 @@ + + + + + + diff --git a/src/Services/Basket/Basket.API/Grpc/BasketService.cs b/src/Services/Basket/Basket.API/Grpc/BasketService.cs new file mode 100644 index 000000000..f6bd42ce7 --- /dev/null +++ b/src/Services/Basket/Basket.API/Grpc/BasketService.cs @@ -0,0 +1,100 @@ +using Grpc.Core; +using Microsoft.eShopOnContainers.Services.Basket.API.Model; +using Microsoft.Extensions.Logging; +using System.Linq; +using System.Threading.Tasks; + +namespace grpc +{ + public class BasketService : Basket.BasketBase + { + private readonly IBasketRepository _repository; + private readonly ILogger _logger; + + public BasketService(IBasketRepository repository, ILogger logger) + { + _repository = repository; + _logger = logger; + } + + public override async Task GetBasketById(BasketRequest request, ServerCallContext context) + { + _logger.LogInformation($"Begin grpc call from method {context.Method} for basket id {request.Id}"); + + var data = await _repository.GetBasketAsync(request.Id); + + if (data != null) + { + context.Status = new Status(StatusCode.OK, $"Basket with id {request.Id} do exist"); + + return MapToCustomerBasketResponse(data); + } + else + { + context.Status = new Status(StatusCode.NotFound, $"Basket with id {request.Id} do not exist"); + } + + return null; + } + + public override async Task UpdateBasket(CustomerBasketRequest request, ServerCallContext context) + { + _logger.LogInformation($"Begin grpc call BasketService.UpdateBasketAsync for buyer id {request.Buyerid}"); + + var customerBasket = MapToCustomerBasket(request); + + var response = await _repository.UpdateBasketAsync(customerBasket); + + if (response != null) + { + return MapToCustomerBasketResponse(response); + } + + context.Status = new Status(StatusCode.NotFound, $"Basket with buyer id {request.Buyerid} do not exist"); + + return null; + } + + private CustomerBasketResponse MapToCustomerBasketResponse(CustomerBasket customerBasket) + { + var response = new CustomerBasketResponse + { + Buyerid = customerBasket.BuyerId + }; + + customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse + { + Id = item.Id, + Oldunitprice = (double)item.OldUnitPrice, + Pictureurl = item.PictureUrl, + Productid = item.ProductId, + Productname = item.ProductName, + Quantity = item.Quantity, + Unitprice = (double)item.UnitPrice + })); + + return response; + } + + private CustomerBasket MapToCustomerBasket(CustomerBasketRequest customerBasketRequest) + { + var response = new CustomerBasket + { + BuyerId = customerBasketRequest.Buyerid + }; + + customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem + { + Id = item.Id, + OldUnitPrice = (decimal)item.Oldunitprice, + PictureUrl = item.Pictureurl, + ProductId = item.Productid, + ProductName = item.Productname, + Quantity = item.Quantity, + UnitPrice = (decimal)item.Unitprice + })); + + return response; + } + } +} diff --git a/src/Services/Basket/Basket.API/Infrastructure/Repositories/RedisBasketRepository.cs b/src/Services/Basket/Basket.API/Infrastructure/Repositories/RedisBasketRepository.cs index 6653f5ed1..93adcc023 100644 --- a/src/Services/Basket/Basket.API/Infrastructure/Repositories/RedisBasketRepository.cs +++ b/src/Services/Basket/Basket.API/Infrastructure/Repositories/RedisBasketRepository.cs @@ -28,7 +28,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Infrastructure.Reposit public IEnumerable GetUsers() { - var server = GetServer(); + var server = GetServer(); var data = server.Keys(); return data?.Select(k => k.ToString()); diff --git a/src/Services/Basket/Basket.API/Program.cs b/src/Services/Basket/Basket.API/Program.cs index 40cc0eebc..caf3d581b 100644 --- a/src/Services/Basket/Basket.API/Program.cs +++ b/src/Services/Basket/Basket.API/Program.cs @@ -2,11 +2,12 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; using Serilog; using System; using System.IO; +using System.Net; namespace Microsoft.eShopOnContainers.Services.Basket.API { @@ -45,8 +46,21 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API private static IWebHost BuildWebHost(IConfiguration configuration, string[] args) => WebHost.CreateDefaultBuilder(args) .CaptureStartupErrors(false) - .UseFailing(options => - options.ConfigPath = "/Failing") + .ConfigureKestrel(options => + { + var ports = GetDefinedPorts(configuration); + + options.Listen(IPAddress.Any, ports.httpPort, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http1AndHttp2; + }); + + options.Listen(IPAddress.Any, ports.grpcPort, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http2; + }); + }) + .UseFailing(options => options.ConfigPath = "/Failing") .UseStartup() .UseApplicationInsights() .UseContentRoot(Directory.GetCurrentDirectory()) @@ -88,5 +102,12 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API return builder.Build(); } + + private static (int httpPort, int grpcPort) GetDefinedPorts(IConfiguration config) + { + var grpcPort = config.GetValue("GRPC_PORT", 5001); + var port = config.GetValue("PORT", 80); + return (port, grpcPort); + } } } diff --git a/src/Services/Basket/Basket.API/Proto/basket.proto b/src/Services/Basket/Basket.API/Proto/basket.proto new file mode 100644 index 000000000..9b69effad --- /dev/null +++ b/src/Services/Basket/Basket.API/Proto/basket.proto @@ -0,0 +1,38 @@ +syntax = "proto3"; + +option csharp_namespace = "grpc"; + +package BasketApi; + +service Basket { + rpc GetBasketById(BasketRequest) returns (CustomerBasketResponse) { + option (google.api.http) = { + get: "/GetBasketById" + }; + } + rpc UpdateBasket(CustomerBasketRequest) returns (CustomerBasketResponse) {} +} + +message BasketRequest { + string id = 1; +} + +message CustomerBasketRequest { + string buyerid = 1; + repeated BasketItemResponse items = 2; +} + +message CustomerBasketResponse { + string buyerid = 1; + repeated BasketItemResponse items = 2; +} + +message BasketItemResponse { + string id = 1; + string productid = 2; + string productname = 3; + double unitprice = 4; + double oldunitprice = 5; + int32 quantity = 6; + string pictureurl = 7; +} diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index 2533f31e5..0176ea936 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -4,6 +4,7 @@ using Basket.API.Infrastructure.Filters; using Basket.API.Infrastructure.Middlewares; using Basket.API.IntegrationEvents.EventHandling; using Basket.API.IntegrationEvents.Events; +using grpc; using HealthChecks.UI.Client; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; @@ -32,6 +33,7 @@ using StackExchange.Redis; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; +using System.IO; namespace Microsoft.eShopOnContainers.Services.Basket.API { @@ -47,6 +49,11 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API // This method gets called by the runtime. Use this method to add services to the container. public virtual IServiceProvider ConfigureServices(IServiceCollection services) { + services.AddGrpc(options => + { + options.EnableDetailedErrors = true; + }); + RegisterAppInsights(services); services.AddControllers(options => @@ -84,10 +91,9 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API } } }); - + options.OperationFilter(); }); - ConfigureAuthService(services); @@ -192,6 +198,14 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UsePathBase(pathBase); } + app.UseSwagger() + .UseSwaggerUI(setup => + { + setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); + setup.OAuthClientId("basketswaggerui"); + setup.OAuthAppName("Basket Swagger UI"); + }); + app.UseRouting(); ConfigureAuth(app); @@ -202,6 +216,21 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API { endpoints.MapDefaultControllerRoute(); endpoints.MapControllers(); + endpoints.MapGet("/_proto/", async ctx => + { + ctx.Response.ContentType = "text/plain"; + using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read); + using var sr = new StreamReader(fs); + while (!sr.EndOfStream) + { + var line = await sr.ReadLineAsync(); + if (line != "/* >>" || line != "<< */") + { + await ctx.Response.WriteAsync(line); + } + } + }); + endpoints.MapGrpcService(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -212,15 +241,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API Predicate = r => r.Name.Contains("self") }); }); - - app.UseSwagger() - .UseSwaggerUI(setup => - { - setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); - setup.OAuthClientId("basketswaggerui"); - setup.OAuthAppName("Basket Swagger UI"); - }); - ConfigureEventBus(app); } diff --git a/src/Services/Basket/Basket.API/appsettings.json b/src/Services/Basket/Basket.API/appsettings.json index 37d5b08d6..a5b723116 100644 --- a/src/Services/Basket/Basket.API/appsettings.json +++ b/src/Services/Basket/Basket.API/appsettings.json @@ -11,6 +11,11 @@ } } }, + "Kestrel": { + "EndpointDefaults": { + "Protocols": "Http2" + } + }, "SubscriptionClientName": "Basket", "ApplicationInsights": { "InstrumentationKey": "" diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 44651cb53..e7941d51b 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -19,6 +19,7 @@ 0.1.22-pre1 3.9.0-rc1 1.22.0 + 0.1.22-pre2 3.0.0-preview7.19362.4 1.7.9 From e58429ac2a60950044bdfd1834f5d18941b7d5f7 Mon Sep 17 00:00:00 2001 From: ericuss Date: Mon, 26 Aug 2019 13:57:43 +0200 Subject: [PATCH 061/113] first approach --- docker-compose.override.yml | 1 + eShopOnContainers.sln | 107 +++++++++--------- .../Clients.Grpc.Caller.csproj | 16 +++ src/Clients/Clients.Grpc.Caller/Program.cs | 37 ++++++ .../Clients.Grpc.Caller/Protos/basket.proto | 34 ++++++ .../Basket/Basket.API/Basket.API.csproj | 6 +- .../Basket/Basket.API/Grpc/BasketService.cs | 89 +++++++++------ src/Services/Basket/Basket.API/Program.cs | 2 +- .../Basket/Basket.API/Proto/basket.proto | 10 +- src/Services/Basket/Basket.API/Startup.cs | 103 ++++++++++------- .../TestHttpResponseTrailersFeature.cs | 10 ++ src/_build/dependencies.props | 6 +- 12 files changed, 284 insertions(+), 137 deletions(-) create mode 100644 src/Clients/Clients.Grpc.Caller/Clients.Grpc.Caller.csproj create mode 100644 src/Clients/Clients.Grpc.Caller/Program.cs create mode 100644 src/Clients/Clients.Grpc.Caller/Protos/basket.proto create mode 100644 src/Services/Basket/Basket.API/TestHttpResponseTrailersFeature.cs diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 97379a4b0..4428a9330 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -72,6 +72,7 @@ services: ports: - "5103:80" + - "5580:5001" catalog.api: environment: diff --git a/eShopOnContainers.sln b/eShopOnContainers.sln index 232331854..658eb26d7 100644 --- a/eShopOnContainers.sln +++ b/eShopOnContainers.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27130.2024 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29123.88 MinimumVisualStudioVersion = 10.0.40219.1 Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{FEA0C318-FFED-4D39-8781-265718CA43DD}" EndProject @@ -163,6 +163,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Devspaces.Support", "Devspa EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Devspaces.Support", "src\BuildingBlocks\Devspaces.Support\Devspaces.Support.csproj", "{CB6D01A4-E597-4348-9570-FC8DB03B4267}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Clients", "Clients", "{8449B293-5949-4832-8612-6BCE2962BCB1}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Clients.Grpc.Caller", "src\Clients\Clients.Grpc.Caller\Clients.Grpc.Caller.csproj", "{7C8FA264-ED49-4ACA-9629-FCE5462B30AB}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Ad-Hoc|Any CPU = Ad-Hoc|Any CPU @@ -1369,54 +1373,6 @@ Global {A7337243-33B8-463A-87AD-944B75EFD820}.Release|x86.ActiveCfg = Release|x86 {A7337243-33B8-463A-87AD-944B75EFD820}.Release|x86.Build.0 = Release|x86 {A7337243-33B8-463A-87AD-944B75EFD820}.Release|x86.Deploy.0 = Release|x86 - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|ARM.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|ARM.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|iPhone.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|iPhoneSimulator.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|x64.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|x64.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|x86.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Ad-Hoc|x86.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|Any CPU.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|Any CPU.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|ARM.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|ARM.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|iPhone.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|iPhone.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|iPhoneSimulator.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|iPhoneSimulator.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|x64.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|x64.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|x86.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.AppStore|x86.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|Any CPU.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|ARM.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|ARM.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|iPhone.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|iPhone.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|x64.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|x64.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|x86.ActiveCfg = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Debug|x86.Build.0 = Debug|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|Any CPU.ActiveCfg = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|Any CPU.Build.0 = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|ARM.ActiveCfg = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|ARM.Build.0 = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|iPhone.ActiveCfg = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|iPhone.Build.0 = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|iPhoneSimulator.Build.0 = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|x64.ActiveCfg = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|x64.Build.0 = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|x86.ActiveCfg = Release|Any CPU - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480}.Release|x86.Build.0 = Release|Any CPU {9F00E62F-E180-4A9C-8794-98A72AFAC2DB}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU {9F00E62F-E180-4A9C-8794-98A72AFAC2DB}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU {9F00E62F-E180-4A9C-8794-98A72AFAC2DB}.Ad-Hoc|ARM.ActiveCfg = Debug|Any CPU @@ -2089,6 +2045,54 @@ Global {CB6D01A4-E597-4348-9570-FC8DB03B4267}.Release|x64.Build.0 = Release|Any CPU {CB6D01A4-E597-4348-9570-FC8DB03B4267}.Release|x86.ActiveCfg = Release|Any CPU {CB6D01A4-E597-4348-9570-FC8DB03B4267}.Release|x86.Build.0 = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|ARM.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|ARM.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|iPhone.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|iPhoneSimulator.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|x64.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|x64.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|x86.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Ad-Hoc|x86.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|Any CPU.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|Any CPU.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|ARM.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|ARM.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|iPhone.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|iPhone.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|iPhoneSimulator.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|x64.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|x64.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|x86.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.AppStore|x86.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|ARM.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|ARM.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|iPhone.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|iPhone.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|x64.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|x64.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|x86.ActiveCfg = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Debug|x86.Build.0 = Debug|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|Any CPU.Build.0 = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|ARM.ActiveCfg = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|ARM.Build.0 = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|iPhone.ActiveCfg = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|iPhone.Build.0 = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|iPhoneSimulator.Build.0 = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|x64.ActiveCfg = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|x64.Build.0 = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|x86.ActiveCfg = Release|Any CPU + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -2136,7 +2140,6 @@ Global {A289A7F0-ACD8-42AE-87B6-AB1AFD310BF1} = {0AAED9FF-3260-43BB-B586-9AAF1E010A90} {B68C2B56-7581-46AE-B55D-D25DDFD3BFE3} = {0AAED9FF-3260-43BB-B586-9AAF1E010A90} {A7337243-33B8-463A-87AD-944B75EFD820} = {0AAED9FF-3260-43BB-B586-9AAF1E010A90} - {16CDE5D2-2DDE-4AF2-B902-AD9CC42DE480} = {0BD0DB92-2D98-44D9-9AC0-C59186D59B0B} {9F00E62F-E180-4A9C-8794-98A72AFAC2DB} = {7BA332A2-189D-4D03-9935-FDFF81C42496} {63417272-1E6A-406A-AD11-C738558D89C0} = {7BA332A2-189D-4D03-9935-FDFF81C42496} {56E0E455-731E-41CB-AF46-C1A70F8A140B} = {2F0DEF71-84AC-4212-86D4-E36E8896BDBF} @@ -2163,6 +2166,8 @@ Global {E39BD762-BC86-459D-B818-B6BF2D9F1352} = {424BC53E-17EA-4E12-BC07-64BAA927ABCB} {ABBA561B-499B-48C0-8299-85D41E6E9E98} = {DB0EFB20-B024-4E5E-A75C-52143C131D25} {CB6D01A4-E597-4348-9570-FC8DB03B4267} = {ABBA561B-499B-48C0-8299-85D41E6E9E98} + {8449B293-5949-4832-8612-6BCE2962BCB1} = {932D8224-11F6-4D07-B109-DA28AD288A63} + {7C8FA264-ED49-4ACA-9629-FCE5462B30AB} = {8449B293-5949-4832-8612-6BCE2962BCB1} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {25728519-5F0F-4973-8A64-0A81EB4EA8D9} diff --git a/src/Clients/Clients.Grpc.Caller/Clients.Grpc.Caller.csproj b/src/Clients/Clients.Grpc.Caller/Clients.Grpc.Caller.csproj new file mode 100644 index 000000000..379eb2de1 --- /dev/null +++ b/src/Clients/Clients.Grpc.Caller/Clients.Grpc.Caller.csproj @@ -0,0 +1,16 @@ + + + + Exe + netcoreapp3.0 + + + + + + + + + + + diff --git a/src/Clients/Clients.Grpc.Caller/Program.cs b/src/Clients/Clients.Grpc.Caller/Program.cs new file mode 100644 index 000000000..32ce7905e --- /dev/null +++ b/src/Clients/Clients.Grpc.Caller/Program.cs @@ -0,0 +1,37 @@ +using System; +using System.Net.Http; +using System.Threading.Tasks; +using Grpc.Net.Client; +using GrpcBasket; +namespace Clients.Grpc.Caller +{ + class Program + { + static async Task Main(string[] args) + { + Console.WriteLine("Starting..."); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + + using (var httpClientHandler = new HttpClientHandler()) + { + httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + using (var httpClient = new HttpClient(httpClientHandler)) + { + // Make your request... + // var httpClient = new HttpClient(); + // The port number(5001) must match the port of the gRPC server. + //httpClient.BaseAddress = new Uri("http://localhost:5103"); + httpClient.BaseAddress = new Uri("http://localhost:5580"); + //httpClient.DefaultRequestVersion = Version.Parse("2.0"); + var client = GrpcClient.Create(httpClient); + var reply = await client.GetBasketByIdAsync( + new BasketRequest { Id = "11" }); + Console.WriteLine("Greeting: " + reply.Buyerid); + Console.WriteLine("Press any key to exit..."); + Console.ReadKey(); + } + } + } + } +} diff --git a/src/Clients/Clients.Grpc.Caller/Protos/basket.proto b/src/Clients/Clients.Grpc.Caller/Protos/basket.proto new file mode 100644 index 000000000..1fc22bc99 --- /dev/null +++ b/src/Clients/Clients.Grpc.Caller/Protos/basket.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +option csharp_namespace = "GrpcBasket"; + +package BasketApi; + +service Basket { + rpc GetBasketById(BasketRequest) returns (CustomerBasketResponse); + rpc UpdateBasket(CustomerBasketRequest) returns (CustomerBasketResponse); +} + +message BasketRequest { + string id = 1; +} + +message CustomerBasketRequest { + string buyerid = 1; + repeated BasketItemResponse items = 2; +} + +message CustomerBasketResponse { + string buyerid = 1; + repeated BasketItemResponse items = 2; +} + +message BasketItemResponse { + string id = 1; + string productid = 2; + string productname = 3; + double unitprice = 4; + double oldunitprice = 5; + int32 quantity = 6; + string pictureurl = 7; +} \ No newline at end of file diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index 78cd14b2a..4ba0e19b4 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -27,11 +27,11 @@ - + - - + + diff --git a/src/Services/Basket/Basket.API/Grpc/BasketService.cs b/src/Services/Basket/Basket.API/Grpc/BasketService.cs index f6bd42ce7..a77ae080e 100644 --- a/src/Services/Basket/Basket.API/Grpc/BasketService.cs +++ b/src/Services/Basket/Basket.API/Grpc/BasketService.cs @@ -1,10 +1,12 @@ using Grpc.Core; +using Microsoft.AspNetCore.Authorization; using Microsoft.eShopOnContainers.Services.Basket.API.Model; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading.Tasks; +using GrpcBasket; -namespace grpc +namespace GrpcBasket { public class BasketService : Basket.BasketBase { @@ -17,24 +19,47 @@ namespace grpc _logger = logger; } - public override async Task GetBasketById(BasketRequest request, ServerCallContext context) + [AllowAnonymous] + public override Task GetBasketById(BasketRequest request, ServerCallContext context) { _logger.LogInformation($"Begin grpc call from method {context.Method} for basket id {request.Id}"); - var data = await _repository.GetBasketAsync(request.Id); + //context.ResponseTrailers.Add("grpc-status", "0"); + //context.Status = Status.DefaultSuccess; - if (data != null) + return Task.FromResult(new CustomerBasketResponse { - context.Status = new Status(StatusCode.OK, $"Basket with id {request.Id} do exist"); + Buyerid = "55" + }); - return MapToCustomerBasketResponse(data); - } - else - { - context.Status = new Status(StatusCode.NotFound, $"Basket with id {request.Id} do not exist"); - } - return null; + // if (!context.Response.SupportsTrailers()) + // { + // var headers = new HeaderDictionary(); + // headers.Add("grpc-status", "0"); + + // Log.Logger.Information("Custom middleware headers {@headers}", headers); + // context.Features.Set(new TestHttpResponseTrailersFeature + // { + // Trailers = headers + // }); + // } + + // return next(); + // var data = await _repository.GetBasketAsync(request.Id); + + // if (data != null) + // { + // context.Status = new Status(StatusCode.OK, $"Basket with id {request.Id} do exist"); + + // return MapToCustomerBasketResponse(data); + // } + // else + // { + // context.Status = new Status(StatusCode.NotFound, $"Basket with id {request.Id} do not exist"); + // } + + // return new CustomerBasketResponse(); } public override async Task UpdateBasket(CustomerBasketRequest request, ServerCallContext context) @@ -62,16 +87,16 @@ namespace grpc Buyerid = customerBasket.BuyerId }; - customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse - { - Id = item.Id, - Oldunitprice = (double)item.OldUnitPrice, - Pictureurl = item.PictureUrl, - Productid = item.ProductId, - Productname = item.ProductName, - Quantity = item.Quantity, - Unitprice = (double)item.UnitPrice - })); + // customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse + // { + // Id = item.Id, + // Oldunitprice = (double)item.OldUnitPrice, + // Pictureurl = item.PictureUrl, + // Productid = item.ProductId, + // Productname = item.ProductName, + // Quantity = item.Quantity, + // Unitprice = (double)item.UnitPrice + // })); return response; } @@ -83,16 +108,16 @@ namespace grpc BuyerId = customerBasketRequest.Buyerid }; - customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem - { - Id = item.Id, - OldUnitPrice = (decimal)item.Oldunitprice, - PictureUrl = item.Pictureurl, - ProductId = item.Productid, - ProductName = item.Productname, - Quantity = item.Quantity, - UnitPrice = (decimal)item.Unitprice - })); + // customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem + // { + // Id = item.Id, + // OldUnitPrice = (decimal)item.Oldunitprice, + // PictureUrl = item.Pictureurl, + // ProductId = item.Productid, + // ProductName = item.Productname, + // Quantity = item.Quantity, + // UnitPrice = (decimal)item.Unitprice + // })); return response; } diff --git a/src/Services/Basket/Basket.API/Program.cs b/src/Services/Basket/Basket.API/Program.cs index caf3d581b..de1b54c2b 100644 --- a/src/Services/Basket/Basket.API/Program.cs +++ b/src/Services/Basket/Basket.API/Program.cs @@ -49,7 +49,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API .ConfigureKestrel(options => { var ports = GetDefinedPorts(configuration); - options.Listen(IPAddress.Any, ports.httpPort, listenOptions => { listenOptions.Protocols = HttpProtocols.Http1AndHttp2; @@ -59,6 +58,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API { listenOptions.Protocols = HttpProtocols.Http2; }); + }) .UseFailing(options => options.ConfigPath = "/Failing") .UseStartup() diff --git a/src/Services/Basket/Basket.API/Proto/basket.proto b/src/Services/Basket/Basket.API/Proto/basket.proto index 9b69effad..0ba9315df 100644 --- a/src/Services/Basket/Basket.API/Proto/basket.proto +++ b/src/Services/Basket/Basket.API/Proto/basket.proto @@ -1,15 +1,11 @@ syntax = "proto3"; -option csharp_namespace = "grpc"; +option csharp_namespace = "GrpcBasket"; package BasketApi; service Basket { - rpc GetBasketById(BasketRequest) returns (CustomerBasketResponse) { - option (google.api.http) = { - get: "/GetBasketById" - }; - } + rpc GetBasketById(BasketRequest) returns (CustomerBasketResponse) {} rpc UpdateBasket(CustomerBasketRequest) returns (CustomerBasketResponse) {} } @@ -19,12 +15,10 @@ message BasketRequest { message CustomerBasketRequest { string buyerid = 1; - repeated BasketItemResponse items = 2; } message CustomerBasketResponse { string buyerid = 1; - repeated BasketItemResponse items = 2; } message BasketItemResponse { diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index 0176ea936..c38fb66b7 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -4,7 +4,6 @@ using Basket.API.Infrastructure.Filters; using Basket.API.Infrastructure.Middlewares; using Basket.API.IntegrationEvents.EventHandling; using Basket.API.IntegrationEvents.Events; -using grpc; using HealthChecks.UI.Client; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; @@ -34,6 +33,9 @@ using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.IO; +using GrpcBasket; +using Microsoft.AspNetCore.Http.Features; +using Serilog; namespace Microsoft.eShopOnContainers.Services.Basket.API { @@ -198,39 +200,62 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UsePathBase(pathBase); } - app.UseSwagger() - .UseSwaggerUI(setup => - { - setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); - setup.OAuthClientId("basketswaggerui"); - setup.OAuthAppName("Basket Swagger UI"); - }); + + //app.Use((context, next) => + //{ + // Log.Logger.Information("Custom middleware to avoid trailers"); + // Log.Logger.Information("Custom middleware context.Response {@context.Response}", context.Response); + // Log.Logger.Information("Custom middleware context.Response.SupportsTrailers {context.Response.SupportsTrailers}", context.Response.SupportsTrailers()); + // if (!context.Response.SupportsTrailers()) + // { + // var headers = new HeaderDictionary(); + // headers.Add("grpc-status", "0"); + + // Log.Logger.Information("Custom middleware headers {@headers}", headers); + // context.Features.Set(new TestHttpResponseTrailersFeature + // { + // Trailers = headers + // }); + // } + + // return next(); + + + //}); + + //app.UseSwagger() + // .UseSwaggerUI(setup => + // { + // setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); + // setup.OAuthClientId("basketswaggerui"); + // setup.OAuthAppName("Basket Swagger UI"); + // }); app.UseRouting(); - ConfigureAuth(app); + // ConfigureAuth(app); - app.UseStaticFiles(); + // app.UseStaticFiles(); app.UseCors("CorsPolicy"); app.UseEndpoints(endpoints => { + endpoints.MapGrpcService(); endpoints.MapDefaultControllerRoute(); endpoints.MapControllers(); - endpoints.MapGet("/_proto/", async ctx => - { - ctx.Response.ContentType = "text/plain"; - using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read); - using var sr = new StreamReader(fs); - while (!sr.EndOfStream) - { - var line = await sr.ReadLineAsync(); - if (line != "/* >>" || line != "<< */") - { - await ctx.Response.WriteAsync(line); - } - } - }); - endpoints.MapGrpcService(); + // endpoints.MapGet("/_proto/", async ctx => + // { + // ctx.Response.ContentType = "text/plain"; + // using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read); + // using var sr = new StreamReader(fs); + // while (!sr.EndOfStream) + // { + // var line = await sr.ReadLineAsync(); + // if (line != "/* >>" || line != "<< */") + // { + // await ctx.Response.WriteAsync(line); + // } + // } + // }); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -254,21 +279,21 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API private void ConfigureAuthService(IServiceCollection services) { // prevent from mapping "sub" claim to nameidentifier. - JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); + // JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); - var identityUrl = Configuration.GetValue("IdentityUrl"); + // var identityUrl = Configuration.GetValue("IdentityUrl"); - services.AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + // services.AddAuthentication(options => + // { + // options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + // options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - }).AddJwtBearer(options => - { - options.Authority = identityUrl; - options.RequireHttpsMetadata = false; - options.Audience = "basket"; - }); + // }).AddJwtBearer(options => + // { + // options.Authority = identityUrl; + // options.RequireHttpsMetadata = false; + // options.Audience = "basket"; + // }); } protected virtual void ConfigureAuth(IApplicationBuilder app) @@ -278,8 +303,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UseMiddleware(); } - app.UseAuthentication(); - app.UseAuthorization(); + // app.UseAuthentication(); + // app.UseAuthorization(); } private void RegisterEventBus(IServiceCollection services) diff --git a/src/Services/Basket/Basket.API/TestHttpResponseTrailersFeature.cs b/src/Services/Basket/Basket.API/TestHttpResponseTrailersFeature.cs new file mode 100644 index 000000000..7cab5a07b --- /dev/null +++ b/src/Services/Basket/Basket.API/TestHttpResponseTrailersFeature.cs @@ -0,0 +1,10 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; + +namespace Microsoft.eShopOnContainers.Services.Basket.API +{ + internal class TestHttpResponseTrailersFeature : IHttpResponseTrailersFeature + { + public IHeaderDictionary Trailers { get; set; } + } +} \ No newline at end of file diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index e7941d51b..1905ccd41 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -16,9 +16,9 @@ - 0.1.22-pre1 - 3.9.0-rc1 - 1.22.0 + 0.1.22-pre3 + 3.9.1 + 2.23.0 0.1.22-pre2 3.0.0-preview7.19362.4 From 9b1c690c9e36d11f19e3ee78792f5636414e397d Mon Sep 17 00:00:00 2001 From: ericuss Date: Mon, 26 Aug 2019 14:52:57 +0200 Subject: [PATCH 062/113] restore options and grpc calling from console app it's working --- src/Clients/Clients.Grpc.Caller/Program.cs | 19 +++- .../Basket/Basket.API/Basket.API.csproj | 6 +- .../Basket/Basket.API/Grpc/BasketService.cs | 84 ++++++-------- .../Basket/Basket.API/Proto/basket.proto | 2 + src/Services/Basket/Basket.API/Startup.cs | 105 +++++++----------- 5 files changed, 93 insertions(+), 123 deletions(-) diff --git a/src/Clients/Clients.Grpc.Caller/Program.cs b/src/Clients/Clients.Grpc.Caller/Program.cs index 32ce7905e..5a671ac6e 100644 --- a/src/Clients/Clients.Grpc.Caller/Program.cs +++ b/src/Clients/Clients.Grpc.Caller/Program.cs @@ -1,6 +1,7 @@ using System; using System.Net.Http; using System.Threading.Tasks; +using Grpc.Core; using Grpc.Net.Client; using GrpcBasket; namespace Clients.Grpc.Caller @@ -25,9 +26,21 @@ namespace Clients.Grpc.Caller httpClient.BaseAddress = new Uri("http://localhost:5580"); //httpClient.DefaultRequestVersion = Version.Parse("2.0"); var client = GrpcClient.Create(httpClient); - var reply = await client.GetBasketByIdAsync( - new BasketRequest { Id = "11" }); - Console.WriteLine("Greeting: " + reply.Buyerid); + + try + { + var reply = await client.GetBasketByIdAsync( + new BasketRequest { Id = "4f71a02f-4738-43a9-8c81-7652877e7102" }); + Console.WriteLine("Greeting: " + reply.Buyerid); + Console.WriteLine("Greeting: " + reply.Items); + + } + //catch(Grpc) + catch (RpcException e) + { + Console.WriteLine($"Error calling via grpc: {e.Status} - {e.Message}"); + } + Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index 4ba0e19b4..78cd14b2a 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -27,11 +27,11 @@ - + - - + + diff --git a/src/Services/Basket/Basket.API/Grpc/BasketService.cs b/src/Services/Basket/Basket.API/Grpc/BasketService.cs index a77ae080e..e92190c73 100644 --- a/src/Services/Basket/Basket.API/Grpc/BasketService.cs +++ b/src/Services/Basket/Basket.API/Grpc/BasketService.cs @@ -20,46 +20,24 @@ namespace GrpcBasket } [AllowAnonymous] - public override Task GetBasketById(BasketRequest request, ServerCallContext context) + public override async Task GetBasketById(BasketRequest request, ServerCallContext context) { _logger.LogInformation($"Begin grpc call from method {context.Method} for basket id {request.Id}"); - //context.ResponseTrailers.Add("grpc-status", "0"); - //context.Status = Status.DefaultSuccess; + var data = await _repository.GetBasketAsync(request.Id); - return Task.FromResult(new CustomerBasketResponse + if (data != null) { - Buyerid = "55" - }); + context.Status = new Status(StatusCode.OK, $"Basket with id {request.Id} do exist"); + return MapToCustomerBasketResponse(data); + } + else + { + context.Status = new Status(StatusCode.NotFound, $"Basket with id {request.Id} do not exist"); + } - // if (!context.Response.SupportsTrailers()) - // { - // var headers = new HeaderDictionary(); - // headers.Add("grpc-status", "0"); - - // Log.Logger.Information("Custom middleware headers {@headers}", headers); - // context.Features.Set(new TestHttpResponseTrailersFeature - // { - // Trailers = headers - // }); - // } - - // return next(); - // var data = await _repository.GetBasketAsync(request.Id); - - // if (data != null) - // { - // context.Status = new Status(StatusCode.OK, $"Basket with id {request.Id} do exist"); - - // return MapToCustomerBasketResponse(data); - // } - // else - // { - // context.Status = new Status(StatusCode.NotFound, $"Basket with id {request.Id} do not exist"); - // } - - // return new CustomerBasketResponse(); + return new CustomerBasketResponse(); } public override async Task UpdateBasket(CustomerBasketRequest request, ServerCallContext context) @@ -87,16 +65,16 @@ namespace GrpcBasket Buyerid = customerBasket.BuyerId }; - // customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse - // { - // Id = item.Id, - // Oldunitprice = (double)item.OldUnitPrice, - // Pictureurl = item.PictureUrl, - // Productid = item.ProductId, - // Productname = item.ProductName, - // Quantity = item.Quantity, - // Unitprice = (double)item.UnitPrice - // })); + customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse + { + Id = item.Id, + Oldunitprice = (double)item.OldUnitPrice, + Pictureurl = item.PictureUrl, + Productid = item.ProductId, + Productname = item.ProductName, + Quantity = item.Quantity, + Unitprice = (double)item.UnitPrice + })); return response; } @@ -108,16 +86,16 @@ namespace GrpcBasket BuyerId = customerBasketRequest.Buyerid }; - // customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem - // { - // Id = item.Id, - // OldUnitPrice = (decimal)item.Oldunitprice, - // PictureUrl = item.Pictureurl, - // ProductId = item.Productid, - // ProductName = item.Productname, - // Quantity = item.Quantity, - // UnitPrice = (decimal)item.Unitprice - // })); + customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem + { + Id = item.Id, + OldUnitPrice = (decimal)item.Oldunitprice, + PictureUrl = item.Pictureurl, + ProductId = item.Productid, + ProductName = item.Productname, + Quantity = item.Quantity, + UnitPrice = (decimal)item.Unitprice + })); return response; } diff --git a/src/Services/Basket/Basket.API/Proto/basket.proto b/src/Services/Basket/Basket.API/Proto/basket.proto index 0ba9315df..b332d8427 100644 --- a/src/Services/Basket/Basket.API/Proto/basket.proto +++ b/src/Services/Basket/Basket.API/Proto/basket.proto @@ -15,10 +15,12 @@ message BasketRequest { message CustomerBasketRequest { string buyerid = 1; + repeated BasketItemResponse items = 2; } message CustomerBasketResponse { string buyerid = 1; + repeated BasketItemResponse items = 2; } message BasketItemResponse { diff --git a/src/Services/Basket/Basket.API/Startup.cs b/src/Services/Basket/Basket.API/Startup.cs index c38fb66b7..d9554bcb8 100644 --- a/src/Services/Basket/Basket.API/Startup.cs +++ b/src/Services/Basket/Basket.API/Startup.cs @@ -200,41 +200,18 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UsePathBase(pathBase); } - - //app.Use((context, next) => - //{ - // Log.Logger.Information("Custom middleware to avoid trailers"); - // Log.Logger.Information("Custom middleware context.Response {@context.Response}", context.Response); - // Log.Logger.Information("Custom middleware context.Response.SupportsTrailers {context.Response.SupportsTrailers}", context.Response.SupportsTrailers()); - // if (!context.Response.SupportsTrailers()) - // { - // var headers = new HeaderDictionary(); - // headers.Add("grpc-status", "0"); - - // Log.Logger.Information("Custom middleware headers {@headers}", headers); - // context.Features.Set(new TestHttpResponseTrailersFeature - // { - // Trailers = headers - // }); - // } - - // return next(); - - - //}); - - //app.UseSwagger() - // .UseSwaggerUI(setup => - // { - // setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); - // setup.OAuthClientId("basketswaggerui"); - // setup.OAuthAppName("Basket Swagger UI"); - // }); + app.UseSwagger() + .UseSwaggerUI(setup => + { + setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1"); + setup.OAuthClientId("basketswaggerui"); + setup.OAuthAppName("Basket Swagger UI"); + }); app.UseRouting(); - // ConfigureAuth(app); + ConfigureAuth(app); - // app.UseStaticFiles(); + app.UseStaticFiles(); app.UseCors("CorsPolicy"); app.UseEndpoints(endpoints => @@ -242,20 +219,20 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API endpoints.MapGrpcService(); endpoints.MapDefaultControllerRoute(); endpoints.MapControllers(); - // endpoints.MapGet("/_proto/", async ctx => - // { - // ctx.Response.ContentType = "text/plain"; - // using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read); - // using var sr = new StreamReader(fs); - // while (!sr.EndOfStream) - // { - // var line = await sr.ReadLineAsync(); - // if (line != "/* >>" || line != "<< */") - // { - // await ctx.Response.WriteAsync(line); - // } - // } - // }); + endpoints.MapGet("/_proto/", async ctx => + { + ctx.Response.ContentType = "text/plain"; + using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read); + using var sr = new StreamReader(fs); + while (!sr.EndOfStream) + { + var line = await sr.ReadLineAsync(); + if (line != "/* >>" || line != "<< */") + { + await ctx.Response.WriteAsync(line); + } + } + }); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, @@ -278,22 +255,22 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API private void ConfigureAuthService(IServiceCollection services) { - // prevent from mapping "sub" claim to nameidentifier. - // JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); - - // var identityUrl = Configuration.GetValue("IdentityUrl"); - - // services.AddAuthentication(options => - // { - // options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - // options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - - // }).AddJwtBearer(options => - // { - // options.Authority = identityUrl; - // options.RequireHttpsMetadata = false; - // options.Audience = "basket"; - // }); + // prevent from mapping "sub" claim to nameidentifier. + JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); + + var identityUrl = Configuration.GetValue("IdentityUrl"); + + services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + + }).AddJwtBearer(options => + { + options.Authority = identityUrl; + options.RequireHttpsMetadata = false; + options.Audience = "basket"; + }); } protected virtual void ConfigureAuth(IApplicationBuilder app) @@ -303,8 +280,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API app.UseMiddleware(); } - // app.UseAuthentication(); - // app.UseAuthorization(); + app.UseAuthentication(); + app.UseAuthorization(); } private void RegisterEventBus(IServiceCollection services) From 016089fb5fa66570a985841a31cba4673edb38ec Mon Sep 17 00:00:00 2001 From: ericuss Date: Tue, 27 Aug 2019 09:40:31 +0200 Subject: [PATCH 063/113] Partial checkin --- .../aggregator/Services/BasketService.cs | 60 ++++++++++-------- .../Mobile.Bff.Shopping/aggregator/Startup.cs | 28 +++++---- .../Controllers/BasketController.cs | 6 ++ .../aggregator/Protos/basket.api | 34 ++++++++++ .../aggregator/Services/BasketService.cs | 62 ++++++++++++++++++- .../Web.Bff.Shopping/aggregator/Startup.cs | 5 +- .../Web.Shopping.HttpAggregator.csproj | 7 +++ .../Identity.API/Configuration/Config.cs | 3 +- src/_build/dependencies.props | 1 + 9 files changed, 163 insertions(+), 43 deletions(-) create mode 100644 src/ApiGateways/Web.Bff.Shopping/aggregator/Protos/basket.api diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs index 657e3cd54..44e13dd91 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs @@ -1,5 +1,4 @@ -using grpc; -using Grpc.Net.Client; +using Grpc.Net.Client; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models; using Microsoft.Extensions.Logging; @@ -8,7 +7,8 @@ using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; -using static grpc.Basket; +using GrpcBasket; +using Grpc.Core; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services { @@ -27,49 +27,57 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services public async Task GetById(string id) { + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GetById @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Http2UnencryptedSupport disable @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); - - _httpClient.BaseAddress = new Uri("http://localhost:5001"); - - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ {_httpClient.BaseAddress} @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", _httpClient.BaseAddress); + using (var httpClientHandler = new HttpClientHandler()) + { + httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + using (var httpClient = new HttpClient(httpClientHandler)) + { + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Http2UnencryptedSupport disable @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); - var client = GrpcClient.Create(_httpClient); + httpClient.BaseAddress = new Uri("http://localhost:5580"); - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ client create @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ {httpClient.BaseAddress} @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ " + httpClient.BaseAddress, httpClient.BaseAddress); - var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); + var client = GrpcClient.Create(httpClient); - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ call grpc server @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ client create @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); - _logger.LogInformation("############## DATA: {@a}", response.Buyerid); + try + { - //if (streaming.IsCompleted) - //{ - // _logger.LogInformation("############## DATA: {@a}", streaming.GetResult()); - //} - //var streaming = client.GetBasketById(new BasketRequest { Id = id }); + var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ call grpc server @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + _logger.LogInformation("############## DATA: {@a}", response.Buyerid); + _logger.LogInformation("############## DATA:response {@response}", response); - //var status = streaming.GetStatus(); + return MapToBasketData(response); + } + catch (RpcException e) + { + _logger.LogError($"Error calling via grpc: {e.Status} - {e.Message}"); + } + } + } - //if (status.StatusCode == Grpc.Core.StatusCode.OK) - //{ - // return null; - //} + return null; // temp + // var data = await _apiClient.GetStringAsync(_urls.Basket + UrlsConfig.BasketOperations.GetItemById(id)); + // var basket = !string.IsNullOrEmpty(data) ? JsonConvert.DeserializeObject(data) : null; - return null; - //return MapToBasketData(response.ResponseStream); + // return basket; } public async Task UpdateAsync(BasketData currentBasket) { _httpClient.BaseAddress = new Uri(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket()); - var client = GrpcClient.Create(_httpClient); + var client = GrpcClient.Create(_httpClient); var request = MapToCustomerBasketRequest(currentBasket); await client.UpdateBasketAsync(request); diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index 2a9d0b341..8d7f7dbbe 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -74,6 +74,17 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator app.UseCors("CorsPolicy"); app.UseHttpsRedirection(); + + app.UseSwagger().UseSwaggerUI(c => + { + c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1"); + + c.OAuthClientId("mobileshoppingaggswaggerui"); + c.OAuthClientSecret(string.Empty); + c.OAuthRealm(string.Empty); + c.OAuthAppName("Purchase BFF Swagger UI"); + }); + app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); @@ -91,16 +102,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator Predicate = r => r.Name.Contains("self") }); }); - - app.UseSwagger().UseSwaggerUI(c => - { - c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1"); - - c.OAuthClientId("mobileshoppingaggswaggerui"); - c.OAuthClientSecret(string.Empty); - c.OAuthRealm(string.Empty); - c.OAuthAppName("Purchase BFF Swagger UI"); - }); } } @@ -130,8 +131,11 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator { Implicit = new OpenApiOAuthFlow() { - AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), - TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), + // AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + // TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), + + AuthorizationUrl = new Uri($"http://localhost:5105/connect/authorize"), + TokenUrl = new Uri($"http://localhost:5105/connect/token"), Scopes = new Dictionary() { { "mobileshoppingagg", "Shopping Aggregator for Mobile Clients" } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs index 851368af1..2fefb9d8a 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; +using Serilog; namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers { @@ -30,13 +31,18 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers [ProducesResponseType(typeof(BasketData), (int)HttpStatusCode.OK)] public async Task> UpdateAllBasketAsync([FromBody] UpdateBasketRequest data) { + Log.Information("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ UpdateAllBasketAsync @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + if (data.Items == null || !data.Items.Any()) { return BadRequest("Need to pass at least one basket line"); } // Retrieve the current basket + Log.Information("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GetByIdAsync @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + var basket = await _basket.GetByIdAsync(data.BuyerId) ?? new BasketData(data.BuyerId); + Log.Information("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ basket @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); var catalogItems = await _catalog.GetCatalogItemsAsync(data.Items.Select(x => x.ProductId)); diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Protos/basket.api b/src/ApiGateways/Web.Bff.Shopping/aggregator/Protos/basket.api new file mode 100644 index 000000000..1fc22bc99 --- /dev/null +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Protos/basket.api @@ -0,0 +1,34 @@ +syntax = "proto3"; + +option csharp_namespace = "GrpcBasket"; + +package BasketApi; + +service Basket { + rpc GetBasketById(BasketRequest) returns (CustomerBasketResponse); + rpc UpdateBasket(CustomerBasketRequest) returns (CustomerBasketResponse); +} + +message BasketRequest { + string id = 1; +} + +message CustomerBasketRequest { + string buyerid = 1; + repeated BasketItemResponse items = 2; +} + +message CustomerBasketResponse { + string buyerid = 1; + repeated BasketItemResponse items = 2; +} + +message BasketItemResponse { + string id = 1; + string productid = 2; + string productname = 3; + double unitprice = 4; + double oldunitprice = 5; + int32 quantity = 6; + string pictureurl = 7; +} \ No newline at end of file diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs index d0fb5c008..92b96dec5 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs @@ -23,10 +23,66 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services public async Task GetByIdAsync(string id) { - var data = await _apiClient.GetStringAsync(_urls.Basket + UrlsConfig.BasketOperations.GetItemById(id)); - var basket = !string.IsNullOrEmpty(data) ? JsonConvert.DeserializeObject(data) : null; - return basket; + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GetById @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + using (var httpClientHandler = new HttpClientHandler()) + { + httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + using (var httpClient = new HttpClient(httpClientHandler)) + { + + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Http2UnencryptedSupport disable @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + + httpClient.BaseAddress = new Uri("http://localhost:5580"); + + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ {httpClient.BaseAddress} @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", httpClient.BaseAddress); + + var client = GrpcClient.Create(httpClient); + + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ client create @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + + try{ + + var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); + _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ call grpc server @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + + _logger.LogInformation("############## DATA: {@a}", response.Buyerid); + _logger.LogInformation("############## DATA:response {@response}", response); + } + catch (RpcException e) + { + Console.WriteLine($"Error calling via grpc: {e.Status} - {e.Message}"); + _logger.logError($"Error calling via grpc: {e.Status} - {e.Message}"); + + } + + + //if (streaming.IsCompleted) + //{ + // _logger.LogInformation("############## DATA: {@a}", streaming.GetResult()); + //} + //var streaming = client.GetBasketById(new BasketRequest { Id = id }); + + + //var status = streaming.GetStatus(); + + //if (status.StatusCode == Grpc.Core.StatusCode.OK) + //{ + // return null; + //} + + return response; + + } + } + + // var data = await _apiClient.GetStringAsync(_urls.Basket + UrlsConfig.BasketOperations.GetItemById(id)); + // var basket = !string.IsNullOrEmpty(data) ? JsonConvert.DeserializeObject(data) : null; + + // return basket; } public async Task UpdateAsync(BasketData currentBasket) diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index 9b144db48..7c18f10ec 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -94,6 +94,8 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator { c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1"); //c.ConfigureOAuth2("Microsoft.eShopOnContainers.Web.Shopping.HttpAggregatorwaggerui", "", "", "Purchase BFF Swagger UI"); + c.OAuthClientId("webshoppingaggswaggerui"); + c.OAuthAppName("web shopping bff Swagger UI"); }); } } @@ -157,7 +159,8 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator TokenUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/token", Scopes = new Dictionary() { - { "webshoppingagg", "Shopping Aggregator for Web Clients" } + { "webshoppingagg", "Shopping Aggregator for Web Clients" }, + { "basket", "basket api" } } }); diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj index ef610d572..ed51b4860 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj @@ -55,6 +55,13 @@ + + + + + + + diff --git a/src/Services/Identity/Identity.API/Configuration/Config.cs b/src/Services/Identity/Identity.API/Configuration/Config.cs index dcb3a8c7a..04a9aa043 100644 --- a/src/Services/Identity/Identity.API/Configuration/Config.cs +++ b/src/Services/Identity/Identity.API/Configuration/Config.cs @@ -284,7 +284,8 @@ namespace Microsoft.eShopOnContainers.Services.Identity.API.Configuration AllowedScopes = { - "webshoppingagg" + "webshoppingagg", + "basket" } }, new Client diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 1905ccd41..c16619251 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -17,6 +17,7 @@ 0.1.22-pre3 + 0.1.22-pre3 3.9.1 2.23.0 0.1.22-pre2 From 3f61eb0ef93c4c2ad45238f4268dbf9516d7d543 Mon Sep 17 00:00:00 2001 From: ericuss Date: Tue, 27 Aug 2019 14:07:39 +0200 Subject: [PATCH 064/113] fix grpc call from mobile bff to basket.api and add ordering, in ordering controller --- docker-compose.override.yml | 5 +- .../aggregator/Config/UrlsConfig.cs | 2 + .../aggregator/Controllers/OrderController.cs | 8 +- ...ttpClientAuthorizationDelegatingHandler.cs | 2 - .../Mobile.Shopping.HttpAggregator.csproj | 5 +- .../aggregator/Models/BasketData.cs | 3 +- .../aggregator/Models/OrderData.cs | 4 +- .../aggregator/Models/OrderItemData.cs | 7 +- .../Models/UpdateBasketItemsRequest.cs | 5 +- .../aggregator/Models/UpdateBasketRequest.cs | 5 +- .../aggregator/Services/BasketService.cs | 22 +--- .../aggregator/Services/IOrderingService.cs | 10 ++ .../aggregator/Services/OrderingService.cs | 113 ++++++++++++++++++ .../Mobile.Bff.Shopping/aggregator/Startup.cs | 16 ++- .../aggregator/appsettings.localhost.json | 4 +- .../Ordering.API/Grpc/OrderingService.cs | 92 ++++++++++++++ .../Ordering/Ordering.API/Ordering.API.csproj | 12 +- src/Services/Ordering/Ordering.API/Program.cs | 22 ++++ .../Ordering.API/Proto/ordering.proto | 39 ++++++ src/Services/Ordering/Ordering.API/Startup.cs | 28 ++++- 20 files changed, 350 insertions(+), 54 deletions(-) create mode 100644 src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/IOrderingService.cs create mode 100644 src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/OrderingService.cs create mode 100644 src/Services/Ordering/Ordering.API/Grpc/OrderingService.cs create mode 100644 src/Services/Ordering/Ordering.API/Proto/ordering.proto diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 4428a9330..5c1a9082c 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -115,6 +115,7 @@ services: - Serilog__MinimumLevel__Override__Ordering.API=Verbose ports: - "5102:80" + - "5581:5001" ordering.backgroundtasks: environment: @@ -284,6 +285,8 @@ services: - urls__catalog=http://catalog.api - urls__orders=http://ordering.api - urls__identity=http://identity.api + - urls__grpcBasket=http://10.0.75.1:5580 + - urls__grpcOrdering=http://10.0.75.1:5581 - CatalogUrlHC=http://catalog.api/hc - OrderingUrlHC=http://ordering.api/hc - IdentityUrlHC=http://identity.api/hc @@ -291,7 +294,7 @@ services: - MarketingUrlHC=http://marketing.api/hc - PaymentUrlHC=http://payment.api/hc - LocationUrlHC=http://locations.api/hc - - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 + - IdentityUrlExternal=http://10.0.75.1:5105 ports: - "5120:80" diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Config/UrlsConfig.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Config/UrlsConfig.cs index e920fbbb2..7fd7cb5f3 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Config/UrlsConfig.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Config/UrlsConfig.cs @@ -27,5 +27,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config public string Basket { get; set; } public string Catalog { get; set; } public string Orders { get; set; } + public string GrpcBasket { get; set; } + public string GrpcOrdering { get; set; } } } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/OrderController.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/OrderController.cs index ac359b4b5..8bacc80d4 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/OrderController.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Controllers/OrderController.cs @@ -13,12 +13,12 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Controllers public class OrderController : ControllerBase { private readonly IBasketService _basketService; - private readonly IOrderApiClient _orderClient; + private readonly IOrderingService _orderingService; - public OrderController(IBasketService basketService, IOrderApiClient orderClient) + public OrderController(IBasketService basketService, IOrderingService orderingService) { _basketService = basketService; - _orderClient = orderClient; + _orderingService = orderingService; } [Route("draft/{basketId}")] @@ -39,7 +39,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Controllers return BadRequest($"No basket found for id {basketId}"); } - return await _orderClient.GetOrderDraftFromBasketAsync(basket); + return await _orderingService.GetOrderDraftAsync(basket); } } } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Infrastructure/HttpClientAuthorizationDelegatingHandler.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Infrastructure/HttpClientAuthorizationDelegatingHandler.cs index 4562139df..bfc705b5c 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Infrastructure/HttpClientAuthorizationDelegatingHandler.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Infrastructure/HttpClientAuthorizationDelegatingHandler.cs @@ -40,8 +40,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastruct request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); } - _logger.LogInformation("@@@@@@@@@@@@@@@@@ {@request}", request); - return await base.SendAsync(request, cancellationToken); } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj index ca8768a66..40060ea29 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj @@ -20,7 +20,7 @@ - + @@ -34,10 +34,11 @@ - + + diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/BasketData.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/BasketData.cs index 302f6bd32..e2888f92e 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/BasketData.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/BasketData.cs @@ -6,7 +6,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models { public string BuyerId { get; set; } - public List Items { get; set; } + public List Items { get; set; } = new List(); public BasketData() { @@ -16,7 +16,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models public BasketData(string buyerId) { BuyerId = buyerId; - Items = new List(); } } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/OrderData.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/OrderData.cs index e87cc18f0..e63b453a4 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/OrderData.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/OrderData.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models { @@ -28,6 +26,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models public string Buyer { get; set; } - public List OrderItems { get; } = new List(); + public List OrderItems { get; } = new List(); } } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/OrderItemData.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/OrderItemData.cs index b0179e470..023cf20e5 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/OrderItemData.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/OrderItemData.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models +namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models { public class OrderItemData { diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/UpdateBasketItemsRequest.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/UpdateBasketItemsRequest.cs index 43cc81b89..35b3e76c0 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/UpdateBasketItemsRequest.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/UpdateBasketItemsRequest.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System.Collections.Generic; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models { diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/UpdateBasketRequest.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/UpdateBasketRequest.cs index cb22bf55f..b377921be 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/UpdateBasketRequest.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/UpdateBasketRequest.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System.Collections.Generic; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models { diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs index 44e13dd91..fa1fc9ffe 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs @@ -27,9 +27,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services public async Task GetById(string id) { - - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GetById @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); @@ -38,24 +35,21 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; using (var httpClient = new HttpClient(httpClientHandler)) { - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Http2UnencryptedSupport disable @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + //httpClient.BaseAddress = new Uri("http://10.0.75.1:5580"); + httpClient.BaseAddress = new Uri(_urls.GrpcBasket); - httpClient.BaseAddress = new Uri("http://localhost:5580"); - - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ {httpClient.BaseAddress} @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ " + httpClient.BaseAddress, httpClient.BaseAddress); + _logger.LogDebug("Creating grpc client for basket {@httpClient.BaseAddress} ", httpClient.BaseAddress); var client = GrpcClient.Create(httpClient); - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ client create @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + _logger.LogDebug("grpc client created, request = {@id}", id); try { var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ call grpc server @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); - _logger.LogInformation("############## DATA: {@a}", response.Buyerid); - _logger.LogInformation("############## DATA:response {@response}", response); + _logger.LogDebug("grpc response {@response}", response); return MapToBasketData(response); } @@ -66,11 +60,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services } } - return null; // temp - // var data = await _apiClient.GetStringAsync(_urls.Basket + UrlsConfig.BasketOperations.GetItemById(id)); - // var basket = !string.IsNullOrEmpty(data) ? JsonConvert.DeserializeObject(data) : null; - - // return basket; + return null; } public async Task UpdateAsync(BasketData currentBasket) diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/IOrderingService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/IOrderingService.cs new file mode 100644 index 000000000..5518a4bbf --- /dev/null +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/IOrderingService.cs @@ -0,0 +1,10 @@ +using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models; +using System.Threading.Tasks; + +namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services +{ + public interface IOrderingService + { + Task GetOrderDraftAsync(BasketData basketData); + } +} \ No newline at end of file diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/OrderingService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/OrderingService.cs new file mode 100644 index 000000000..f1e56c2ef --- /dev/null +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/OrderingService.cs @@ -0,0 +1,113 @@ +using Grpc.Net.Client; +using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; +using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; +using GrpcOrdering; +using Grpc.Core; + +namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services +{ + public class OrderingService : IOrderingService + { + private readonly HttpClient _httpClient; + private readonly UrlsConfig _urls; + private readonly ILogger _logger; + + public OrderingService(HttpClient httpClient, IOptions config, ILogger logger) + { + _httpClient = httpClient; + _urls = config.Value; + _logger = logger; + } + + public async Task GetOrderDraftAsync(BasketData basketData) + { + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + + using (var httpClientHandler = new HttpClientHandler()) + { + httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + using (var httpClient = new HttpClient(httpClientHandler)) + { + httpClient.BaseAddress = new Uri(_urls.GrpcOrdering); + + _logger.LogDebug(" Creating grpc client for ordering {@httpClient.BaseAddress}", httpClient.BaseAddress); + + var client = GrpcClient.Create(httpClient); + + _logger.LogDebug(" grpc client created, basketData={@basketData}", basketData); + + try + { + + var command = MapToOrderDraftCommand(basketData); + var response = await client.CreateOrderDraftFromBasketDataAsync(command); + + _logger.LogDebug(" grpc response: {@response}", response); + + return MapToResponse(response); + } + catch (RpcException e) + { + _logger.LogError($"Error calling via grpc to ordering: {e.Status} - {e.Message}"); + } + } + } + + return null; + } + + private OrderData MapToResponse(GrpcOrdering.OrderDraftDTO orderDraft) + { + if (orderDraft == null) + { + return null; + } + + var data = new OrderData + { + Total = (decimal)orderDraft.Total, + }; + + orderDraft.OrderItems.ToList().ForEach(o => data.OrderItems.Add(new OrderItemData + { + Discount = (decimal)o.Discount, + PictureUrl = o.PictureUrl, + ProductId = o.ProductId, + ProductName = o.ProductName, + UnitPrice = (decimal)o.UnitPrice, + Units = o.Units, + })); + + return data; + } + + private CreateOrderDraftCommand MapToOrderDraftCommand(BasketData basketData) + { + var command = new CreateOrderDraftCommand + { + BuyerId = basketData.BuyerId, + }; + + basketData.Items.ForEach(i => command.Items.Add(new BasketItem + { + Id = i.Id, + OldUnitPrice = (double)i.OldUnitPrice, + PictureUrl = i.PictureUrl, + ProductId = i.ProductId, + ProductName = i.ProductName, + Quantity = i.Quantity, + UnitPrice = (double)i.UnitPrice, + })); + + return command; + } + + } +} diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs index 8d7f7dbbe..f08514177 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs @@ -131,11 +131,9 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator { Implicit = new OpenApiOAuthFlow() { - // AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), - // TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), - - AuthorizationUrl = new Uri($"http://localhost:5105/connect/authorize"), - TokenUrl = new Uri($"http://localhost:5105/connect/token"), + AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), + Scopes = new Dictionary() { { "mobileshoppingagg", "Shopping Aggregator for Mobile Clients" } @@ -188,7 +186,8 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator services.AddSingleton(); //register http services - services.AddHttpClient() + services + .AddHttpClient() .AddHttpMessageHandler() .AddPolicyHandler(GetRetryPolicy()) .AddPolicyHandler(GetCircuitBreakerPolicy()) @@ -204,6 +203,11 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator .AddPolicyHandler(GetCircuitBreakerPolicy()) .AddDevspacesSupport(); + services.AddHttpClient() + .AddPolicyHandler(GetRetryPolicy()) + .AddPolicyHandler(GetCircuitBreakerPolicy()) + .AddDevspacesSupport(); + return services; } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json index 91bbf5f87..f14ca24b9 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json @@ -3,7 +3,9 @@ "basket": "http://localhost:55105", "catalog": "http://localhost:55101", "orders": "http://localhost:55102", - "identity": "http://localhost:55105" + "identity": "http://localhost:55105", + "grpcBasket": "http://localhost:5580", + "grpcOrdering": "http://localhost:5581" }, "IdentityUrlExternal": "http://localhost:5105", "IdentityUrl": "http://localhost:5105", diff --git a/src/Services/Ordering/Ordering.API/Grpc/OrderingService.cs b/src/Services/Ordering/Ordering.API/Grpc/OrderingService.cs new file mode 100644 index 000000000..af59420e7 --- /dev/null +++ b/src/Services/Ordering/Ordering.API/Grpc/OrderingService.cs @@ -0,0 +1,92 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.Logging; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands; +using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Extensions; +using MediatR; +using Grpc.Core; +using AppCommand = Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands; +using ApiModels = Ordering.API.Application.Models; +using Google.Protobuf.Collections; +using System.Collections.Generic; + +namespace GrpcOrdering +{ + public class OrderingService : OrderingGrpc.OrderingGrpcBase + { + private readonly IMediator _mediator; + private readonly ILogger _logger; + + public OrderingService(IMediator mediator, ILogger logger) + { + _mediator = mediator; + _logger = logger; + } + + public override async Task CreateOrderDraftFromBasketData(CreateOrderDraftCommand createOrderDraftCommand, ServerCallContext context) + { + _logger.LogInformation($"Begin grpc call from method {context.Method} for ordering get order draft {createOrderDraftCommand}"); + _logger.LogInformation( + "----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})", + createOrderDraftCommand.GetGenericTypeName(), + nameof(createOrderDraftCommand.BuyerId), + createOrderDraftCommand.BuyerId, + createOrderDraftCommand); + + var command = new AppCommand.CreateOrderDraftCommand( + createOrderDraftCommand.BuyerId, + this.MapBasketItems(createOrderDraftCommand.Items)); + + + var data = await _mediator.Send(command); + + if (data != null) + { + context.Status = new Status(StatusCode.OK, $" ordering get order draft {createOrderDraftCommand} do exist"); + + return this.MapResponse(data); + } + else + { + context.Status = new Status(StatusCode.NotFound, $" ordering get order draft {createOrderDraftCommand} do not exist"); + } + + return new OrderDraftDTO(); + } + + public OrderDraftDTO MapResponse(AppCommand.OrderDraftDTO order) + { + var result = new OrderDraftDTO() + { + Total = (double)order.Total, + }; + + order.OrderItems.ToList().ForEach(i => result.OrderItems.Add(new OrderItemDTO() + { + Discount = (double)i.Discount, + PictureUrl = i.PictureUrl, + ProductId = i.ProductId, + ProductName = i.ProductName, + UnitPrice = (double)i.UnitPrice, + Units = i.Units, + })); + + return result; + } + + public IEnumerable MapBasketItems(RepeatedField items) + { + return items.Select(x => new ApiModels.BasketItem() + { + Id = x.Id, + ProductId = x.ProductId, + ProductName = x.ProductName, + UnitPrice = (decimal)x.UnitPrice, + OldUnitPrice = (decimal)x.OldUnitPrice, + Quantity = x.Quantity, + PictureUrl = x.PictureUrl, + }); + } + } +} diff --git a/src/Services/Ordering/Ordering.API/Ordering.API.csproj b/src/Services/Ordering/Ordering.API/Ordering.API.csproj index 1b3c36daa..fdd681eab 100644 --- a/src/Services/Ordering/Ordering.API/Ordering.API.csproj +++ b/src/Services/Ordering/Ordering.API/Ordering.API.csproj @@ -19,6 +19,13 @@ + + + + + + + @@ -30,7 +37,10 @@ - + + + + diff --git a/src/Services/Ordering/Ordering.API/Program.cs b/src/Services/Ordering/Ordering.API/Program.cs index 50f53360c..899871b3d 100644 --- a/src/Services/Ordering/Ordering.API/Program.cs +++ b/src/Services/Ordering/Ordering.API/Program.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF; using Microsoft.eShopOnContainers.Services.Ordering.API.Infrastructure; using Microsoft.eShopOnContainers.Services.Ordering.Infrastructure; @@ -10,6 +11,7 @@ using Microsoft.Extensions.Options; using Serilog; using System; using System.IO; +using System.Net; namespace Microsoft.eShopOnContainers.Services.Ordering.API { @@ -61,6 +63,20 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API private static IWebHost BuildWebHost(IConfiguration configuration, string[] args) => WebHost.CreateDefaultBuilder(args) .CaptureStartupErrors(false) + .ConfigureKestrel(options => + { + var ports = GetDefinedPorts(configuration); + options.Listen(IPAddress.Any, ports.httpPort, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http1AndHttp2; + }); + + options.Listen(IPAddress.Any, ports.grpcPort, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http2; + }); + + }) .UseStartup() .UseApplicationInsights() .UseContentRoot(Directory.GetCurrentDirectory()) @@ -102,5 +118,11 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API return builder.Build(); } + private static (int httpPort, int grpcPort) GetDefinedPorts(IConfiguration config) + { + var grpcPort = config.GetValue("GRPC_PORT", 5001); + var port = config.GetValue("PORT", 80); + return (port, grpcPort); + } } } \ No newline at end of file diff --git a/src/Services/Ordering/Ordering.API/Proto/ordering.proto b/src/Services/Ordering/Ordering.API/Proto/ordering.proto new file mode 100644 index 000000000..988f3465b --- /dev/null +++ b/src/Services/Ordering/Ordering.API/Proto/ordering.proto @@ -0,0 +1,39 @@ +syntax = "proto3"; + +option csharp_namespace = "GrpcOrdering"; + +package OrderingApi; + +service OrderingGrpc { + rpc CreateOrderDraftFromBasketData(CreateOrderDraftCommand) returns (OrderDraftDTO) {} +} + +message CreateOrderDraftCommand { + string buyerId = 1; + repeated BasketItem items = 2; +} + + +message BasketItem { + string id = 1; + string productId = 2; + string productName = 3; + double unitPrice = 4; + double oldUnitPrice = 5; + int32 quantity = 6; + string pictureUrl = 7; +} + +message OrderDraftDTO { + double total = 1; + repeated OrderItemDTO orderItems = 2; +} +message OrderItemDTO { + int32 productId = 1; + string productName = 2; + double unitPrice = 3; + double discount = 4; + int32 units = 5; + string pictureUrl = 6; +} + diff --git a/src/Services/Ordering/Ordering.API/Startup.cs b/src/Services/Ordering/Ordering.API/Startup.cs index fca490f28..09f4c379b 100644 --- a/src/Services/Ordering/Ordering.API/Startup.cs +++ b/src/Services/Ordering/Ordering.API/Startup.cs @@ -7,12 +7,14 @@ using global::Ordering.API.Application.IntegrationEvents.Events; using global::Ordering.API.Infrastructure.Filters; using global::Ordering.API.Infrastructure.Middlewares; + using GrpcOrdering; using HealthChecks.UI.Client; using Infrastructure.AutofacModules; using Infrastructure.Filters; using Infrastructure.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; + using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.ServiceBus; using Microsoft.EntityFrameworkCore; @@ -34,6 +36,7 @@ using System.Collections.Generic; using System.Data.Common; using System.IdentityModel.Tokens.Jwt; + using System.IO; using System.Reflection; public class Startup @@ -47,7 +50,13 @@ public virtual IServiceProvider ConfigureServices(IServiceCollection services) { - services.AddApplicationInsights(Configuration) + services + .AddGrpc(options => + { + options.EnableDetailedErrors = true; + }) + .Services + .AddApplicationInsights(Configuration) .AddCustomMvc() .AddHealthChecks(Configuration) .AddCustomDbContext(Configuration) @@ -68,7 +77,7 @@ } - public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { //loggerFactory.AddAzureWebAppDiagnostics(); //loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); @@ -87,8 +96,23 @@ app.UseEndpoints(endpoints => { + endpoints.MapGrpcService(); endpoints.MapDefaultControllerRoute(); endpoints.MapControllers(); + endpoints.MapGet("/_proto/", async ctx => + { + ctx.Response.ContentType = "text/plain"; + using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read); + using var sr = new StreamReader(fs); + while (!sr.EndOfStream) + { + var line = await sr.ReadLineAsync(); + if (line != "/* >>" || line != "<< */") + { + await ctx.Response.WriteAsync(line); + } + } + }); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, From e415f2a767a71a4455cd2b81c95a54baff96537b Mon Sep 17 00:00:00 2001 From: ericuss Date: Tue, 27 Aug 2019 15:08:39 +0200 Subject: [PATCH 065/113] migrate web bff to 3.0 and apply grcp in order controller --- docker-compose.override.yml | 4 +- .../Mobile.Shopping.HttpAggregator.csproj | 2 +- .../Mobile.Bff.Shopping/aggregator/Program.cs | 21 --- .../aggregator/Config/UrlsConfig.cs | 2 + .../Controllers/BasketController.cs | 12 +- .../aggregator/Controllers/OrderController.cs | 10 +- .../Web.Bff.Shopping/aggregator/Dockerfile | 4 +- .../Filters/AuthorizeCheckOperationFilter.cs | 19 ++- .../aggregator/Models/BasketData.cs | 3 +- .../Web.Bff.Shopping/aggregator/Program.cs | 1 + .../aggregator/Protos/basket.api | 34 ----- .../aggregator/Services/BasketService.cs | 126 +++++++++++------- .../aggregator/Services/IBasketService.cs | 2 +- .../aggregator/Services/IOrderingService.cs | 10 ++ .../aggregator/Services/OrderingService.cs | 113 ++++++++++++++++ .../Web.Bff.Shopping/aggregator/Startup.cs | 105 ++++++++------- .../Web.Shopping.HttpAggregator.csproj | 36 +++-- .../aggregator/appsettings.localhost.json | 4 +- src/_build/dependencies.props | 1 + 19 files changed, 321 insertions(+), 188 deletions(-) delete mode 100644 src/ApiGateways/Web.Bff.Shopping/aggregator/Protos/basket.api create mode 100644 src/ApiGateways/Web.Bff.Shopping/aggregator/Services/IOrderingService.cs create mode 100644 src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 5c1a9082c..1719fc18d 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -272,7 +272,7 @@ services: - MarketingUrlHC=http://marketing.api/hc - PaymentUrlHC=http://payment.api/hc - LocationUrlHC=http://locations.api/hc - - IdentityUrlExternal=http://${ESHOP_EXTERNAL_DNS_NAME_OR_IP}:5105 + - IdentityUrlExternal=http://10.0.75.1:5105 ports: - "5203:80" volumes: @@ -305,6 +305,8 @@ services: - urls__catalog=http://catalog.api - urls__orders=http://ordering.api - urls__identity=http://identity.api + - urls__grpcBasket=http://10.0.75.1:5580 + - urls__grpcOrdering=http://10.0.75.1:5581 - CatalogUrlHC=http://catalog.api/hc - OrderingUrlHC=http://ordering.api/hc - IdentityUrlHC=http://identity.api/hc diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj index 40060ea29..80886821d 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj @@ -19,7 +19,7 @@ - + diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs index 0dc91cbc0..f536ec19a 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Program.cs @@ -32,20 +32,6 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator ReloadOnChange = false }); }) - .ConfigureKestrel(options => - { - var ports = GetDefinedPorts(_configuration); - - options.Listen(IPAddress.Any, ports.httpPort, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http1AndHttp2; - }); - - options.Listen(IPAddress.Any, ports.grpcPort, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http2; - }); - }) .UseStartup() .UseSerilog((builderContext, config) => { @@ -67,12 +53,5 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator return builder.Build(); } - - private static (int httpPort, int grpcPort) GetDefinedPorts(IConfiguration config) - { - var grpcPort = config.GetValue("GRPC_PORT", 5001); - var port = config.GetValue("PORT", 80); - return (port, grpcPort); - } } } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Config/UrlsConfig.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Config/UrlsConfig.cs index 6bf502fdc..0f7a13483 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Config/UrlsConfig.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Config/UrlsConfig.cs @@ -29,5 +29,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Config public string Basket { get; set; } public string Catalog { get; set; } public string Orders { get; set; } + public string GrpcBasket { get; set; } + public string GrpcOrdering { get; set; } } } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs index 2fefb9d8a..a3be37611 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs @@ -31,7 +31,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers [ProducesResponseType(typeof(BasketData), (int)HttpStatusCode.OK)] public async Task> UpdateAllBasketAsync([FromBody] UpdateBasketRequest data) { - Log.Information("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ UpdateAllBasketAsync @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + Log.Debug("UpdateAllBasketAsync"); if (data.Items == null || !data.Items.Any()) { @@ -41,10 +41,12 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers // Retrieve the current basket Log.Information("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GetByIdAsync @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); - var basket = await _basket.GetByIdAsync(data.BuyerId) ?? new BasketData(data.BuyerId); - Log.Information("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ basket @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + var basket = await _basket.GetById(data.BuyerId) ?? new BasketData(data.BuyerId); + + Log.Debug("get basket by id response={@response}", basket); var catalogItems = await _catalog.GetCatalogItemsAsync(data.Items.Select(x => x.ProductId)); + Log.Debug("get catalog items response={@response}", catalogItems); foreach (var bitem in data.Items) { @@ -82,7 +84,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers } // Retrieve the current basket - var currentBasket = await _basket.GetByIdAsync(data.BasketId); + var currentBasket = await _basket.GetById(data.BasketId); if (currentBasket == null) { return BadRequest($"Basket with id {data.BasketId} not found."); @@ -122,7 +124,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers //item.PictureUri = // Step 2: Get current basket status - var currentBasket = (await _basket.GetByIdAsync(data.BasketId)) ?? new BasketData(data.BasketId); + var currentBasket = (await _basket.GetById(data.BasketId)) ?? new BasketData(data.BasketId); // Step 3: Search if exist product into basket var product = currentBasket.Items.SingleOrDefault(i => i.ProductId == item.Id.ToString()); diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/OrderController.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/OrderController.cs index de3e4cc55..4b88c45b6 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/OrderController.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/OrderController.cs @@ -16,11 +16,11 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers public class OrderController : ControllerBase { private readonly IBasketService _basketService; - private readonly IOrderApiClient _orderClient; - public OrderController(IBasketService basketService, IOrderApiClient orderClient) + private readonly IOrderingService _orderingService; + public OrderController(IBasketService basketService, IOrderingService orderingService) { _basketService = basketService; - _orderClient = orderClient; + _orderingService = orderingService; } [Route("draft/{basketId}")] @@ -34,14 +34,14 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers return BadRequest("Need a valid basketid"); } // Get the basket data and build a order draft based on it - var basket = await _basketService.GetByIdAsync(basketId); + var basket = await _basketService.GetById(basketId); if (basket == null) { return BadRequest($"No basket found for id {basketId}"); } - return await _orderClient.GetOrderDraftFromBasketAsync(basket); + return await _orderingService.GetOrderDraftAsync(basket); } } } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile b/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile index fbce2f0ab..2a3b551a2 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base +FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY scripts scripts/ diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs index e93ec157c..45c191104 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Filters/AuthorizeCheckOperationFilter.cs @@ -1,7 +1,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Filters { using Microsoft.AspNetCore.Authorization; - using Swashbuckle.AspNetCore.Swagger; + using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using System.Linq; @@ -10,7 +10,7 @@ { public class AuthorizeCheckOperationFilter : IOperationFilter { - public void Apply(Operation operation, OperationFilterContext context) + public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any() || @@ -18,14 +18,19 @@ if (!hasAuthorize) return; - operation.Responses.TryAdd("401", new Response { Description = "Unauthorized" }); - operation.Responses.TryAdd("403", new Response { Description = "Forbidden" }); + operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); + operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" }); - operation.Security = new List>> + var oAuthScheme = new OpenApiSecurityScheme { - new Dictionary> + Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } + }; + + operation.Security = new List + { + new OpenApiSecurityRequirement { - { "oauth2", new [] { "Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator" } } + [ oAuthScheme ] = new [] { "Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator" } } }; } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/BasketData.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/BasketData.cs index d29afb5c6..34c170e08 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/BasketData.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Models/BasketData.cs @@ -6,7 +6,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models { public string BuyerId { get; set; } - public List Items { get; set; } + public List Items { get; set; } = new List(); public BasketData() { @@ -16,7 +16,6 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models public BasketData(string buyerId) { BuyerId = buyerId; - Items = new List(); } } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Program.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Program.cs index 6589719fa..b601d67f2 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Program.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Program.cs @@ -33,5 +33,6 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator .WriteTo.Console(); }) .Build(); + } } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Protos/basket.api b/src/ApiGateways/Web.Bff.Shopping/aggregator/Protos/basket.api deleted file mode 100644 index 1fc22bc99..000000000 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Protos/basket.api +++ /dev/null @@ -1,34 +0,0 @@ -syntax = "proto3"; - -option csharp_namespace = "GrpcBasket"; - -package BasketApi; - -service Basket { - rpc GetBasketById(BasketRequest) returns (CustomerBasketResponse); - rpc UpdateBasket(CustomerBasketRequest) returns (CustomerBasketResponse); -} - -message BasketRequest { - string id = 1; -} - -message CustomerBasketRequest { - string buyerid = 1; - repeated BasketItemResponse items = 2; -} - -message CustomerBasketResponse { - string buyerid = 1; - repeated BasketItemResponse items = 2; -} - -message BasketItemResponse { - string id = 1; - string productid = 2; - string productname = 3; - double unitprice = 4; - double oldunitprice = 5; - int32 quantity = 6; - string pictureurl = 7; -} \ No newline at end of file diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs index 92b96dec5..3e68816c1 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs @@ -5,91 +5,125 @@ using Microsoft.Extensions.Options; using Newtonsoft.Json; using System.Net.Http; using System.Threading.Tasks; +using Grpc.Net.Client; +using System; +using System.Linq; +using GrpcBasket; +using Grpc.Core; namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services { public class BasketService : IBasketService { - private readonly HttpClient _apiClient; - private readonly ILogger _logger; + private readonly HttpClient _httpClient; private readonly UrlsConfig _urls; + private readonly ILogger _logger; - public BasketService(HttpClient httpClient,ILogger logger, IOptions config) + public BasketService(HttpClient httpClient, IOptions config, ILogger logger) { - _apiClient = httpClient; - _logger = logger; + _httpClient = httpClient; _urls = config.Value; + _logger = logger; } - public async Task GetByIdAsync(string id) + public async Task GetById(string id) { - - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GetById @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - using (var httpClientHandler = new HttpClientHandler()) + + using (var httpClientHandler = new HttpClientHandler()) { httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; using (var httpClient = new HttpClient(httpClientHandler)) { + //httpClient.BaseAddress = new Uri("http://10.0.75.1:5580"); + httpClient.BaseAddress = new Uri(_urls.GrpcBasket); - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Http2UnencryptedSupport disable @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); - - httpClient.BaseAddress = new Uri("http://localhost:5580"); + _logger.LogDebug("Creating grpc client for basket {@httpClient.BaseAddress} ", httpClient.BaseAddress); - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ {httpClient.BaseAddress} @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", httpClient.BaseAddress); + var client = GrpcClient.Create(httpClient); - var client = GrpcClient.Create(httpClient); + _logger.LogDebug("grpc client created, request = {@id}", id); - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ client create @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + try + { - try{ + var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); - var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); - _logger.LogInformation("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ call grpc server @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + _logger.LogDebug("grpc response {@response}", response); - _logger.LogInformation("############## DATA: {@a}", response.Buyerid); - _logger.LogInformation("############## DATA:response {@response}", response); + return MapToBasketData(response); } catch (RpcException e) { - Console.WriteLine($"Error calling via grpc: {e.Status} - {e.Message}"); - _logger.logError($"Error calling via grpc: {e.Status} - {e.Message}"); - - } - - - //if (streaming.IsCompleted) - //{ - // _logger.LogInformation("############## DATA: {@a}", streaming.GetResult()); - //} - //var streaming = client.GetBasketById(new BasketRequest { Id = id }); + _logger.LogError($"Error calling via grpc: {e.Status} - {e.Message}"); + } + } + } + return null; + } - //var status = streaming.GetStatus(); + public async Task UpdateAsync(BasketData currentBasket) + { + _httpClient.BaseAddress = new Uri(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket()); - //if (status.StatusCode == Grpc.Core.StatusCode.OK) - //{ - // return null; - //} + var client = GrpcClient.Create(_httpClient); + var request = MapToCustomerBasketRequest(currentBasket); - return response; + await client.UpdateBasketAsync(request); + } - } - } + private BasketData MapToBasketData(CustomerBasketResponse customerBasketRequest) + { + if (customerBasketRequest == null) + { + return null; + } - // var data = await _apiClient.GetStringAsync(_urls.Basket + UrlsConfig.BasketOperations.GetItemById(id)); - // var basket = !string.IsNullOrEmpty(data) ? JsonConvert.DeserializeObject(data) : null; + var map = new BasketData + { + BuyerId = customerBasketRequest.Buyerid + }; - // return basket; + customerBasketRequest.Items.ToList().ForEach(item => map.Items.Add(new BasketDataItem + { + Id = item.Id, + OldUnitPrice = (decimal)item.Oldunitprice, + PictureUrl = item.Pictureurl, + ProductId = item.Productid, + ProductName = item.Productname, + Quantity = item.Quantity, + UnitPrice = (decimal)item.Unitprice + })); + + return map; } - public async Task UpdateAsync(BasketData currentBasket) + private CustomerBasketRequest MapToCustomerBasketRequest(BasketData basketData) { - var basketContent = new StringContent(JsonConvert.SerializeObject(currentBasket), System.Text.Encoding.UTF8, "application/json"); + if (basketData == null) + { + return null; + } - await _apiClient.PostAsync(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket(), basketContent); + var map = new CustomerBasketRequest + { + Buyerid = basketData.BuyerId + }; + + basketData.Items.ToList().ForEach(item => map.Items.Add(new BasketItemResponse + { + Id = item.Id, + Oldunitprice = (double)item.OldUnitPrice, + Pictureurl = item.PictureUrl, + Productid = item.ProductId, + Productname = item.ProductName, + Quantity = item.Quantity, + Unitprice = (double)item.UnitPrice + })); + + return map; } } } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/IBasketService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/IBasketService.cs index 046ef753d..fba539b7a 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/IBasketService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/IBasketService.cs @@ -5,7 +5,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services { public interface IBasketService { - Task GetByIdAsync(string id); + Task GetById(string id); Task UpdateAsync(BasketData currentBasket); } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/IOrderingService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/IOrderingService.cs new file mode 100644 index 000000000..a20520747 --- /dev/null +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/IOrderingService.cs @@ -0,0 +1,10 @@ +using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models; +using System.Threading.Tasks; + +namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services +{ + public interface IOrderingService + { + Task GetOrderDraftAsync(BasketData basketData); + } +} \ No newline at end of file diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs new file mode 100644 index 000000000..bba3b851c --- /dev/null +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs @@ -0,0 +1,113 @@ +using Grpc.Net.Client; +using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Config; +using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; +using GrpcOrdering; +using Grpc.Core; + +namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services +{ + public class OrderingService : IOrderingService + { + private readonly HttpClient _httpClient; + private readonly UrlsConfig _urls; + private readonly ILogger _logger; + + public OrderingService(HttpClient httpClient, IOptions config, ILogger logger) + { + _httpClient = httpClient; + _urls = config.Value; + _logger = logger; + } + + public async Task GetOrderDraftAsync(BasketData basketData) + { + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + + using (var httpClientHandler = new HttpClientHandler()) + { + httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + using (var httpClient = new HttpClient(httpClientHandler)) + { + httpClient.BaseAddress = new Uri(_urls.GrpcOrdering); + + _logger.LogDebug(" Creating grpc client for ordering {@httpClient.BaseAddress}", httpClient.BaseAddress); + + var client = GrpcClient.Create(httpClient); + + _logger.LogDebug(" grpc client created, basketData={@basketData}", basketData); + + try + { + + var command = MapToOrderDraftCommand(basketData); + var response = await client.CreateOrderDraftFromBasketDataAsync(command); + + _logger.LogDebug(" grpc response: {@response}", response); + + return MapToResponse(response); + } + catch (RpcException e) + { + _logger.LogError($"Error calling via grpc to ordering: {e.Status} - {e.Message}"); + } + } + } + + return null; + } + + private OrderData MapToResponse(GrpcOrdering.OrderDraftDTO orderDraft) + { + if (orderDraft == null) + { + return null; + } + + var data = new OrderData + { + Total = (decimal)orderDraft.Total, + }; + + orderDraft.OrderItems.ToList().ForEach(o => data.OrderItems.Add(new OrderItemData + { + Discount = (decimal)o.Discount, + PictureUrl = o.PictureUrl, + ProductId = o.ProductId, + ProductName = o.ProductName, + UnitPrice = (decimal)o.UnitPrice, + Units = o.Units, + })); + + return data; + } + + private CreateOrderDraftCommand MapToOrderDraftCommand(BasketData basketData) + { + var command = new CreateOrderDraftCommand + { + BuyerId = basketData.BuyerId, + }; + + basketData.Items.ForEach(i => command.Items.Add(new BasketItem + { + Id = i.Id, + OldUnitPrice = (double)i.OldUnitPrice, + PictureUrl = i.PictureUrl, + ProductId = i.ProductId, + ProductName = i.ProductName, + Quantity = i.Quantity, + UnitPrice = (double)i.UnitPrice, + })); + + return command; + } + + } +} diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index 7c18f10ec..9613fe462 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -14,6 +14,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Models; using Polly; using Polly.Extensions.Http; using Swashbuckle.AspNetCore.Swagger; @@ -62,19 +63,6 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator app.UsePathBase(pathBase); } - app.UseHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - - app.UseHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - - app.UseCors("CorsPolicy"); - if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); @@ -85,18 +73,37 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator app.UseHsts(); } - app.UseAuthentication(); + app.UseCors("CorsPolicy"); app.UseHttpsRedirection(); - app.UseMvc(); - app.UseSwagger() - .UseSwaggerUI(c => + app.UseSwagger().UseSwaggerUI(c => + { + c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1"); + + c.OAuthClientId("webshoppingaggswaggerui"); + c.OAuthClientSecret(string.Empty); + c.OAuthRealm(string.Empty); + c.OAuthAppName("web shopping bff Swagger UI"); + }); + + app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + endpoints.MapControllers(); + endpoints.MapHealthChecks("/hc", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions { - c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1"); - //c.ConfigureOAuth2("Microsoft.eShopOnContainers.Web.Shopping.HttpAggregatorwaggerui", "", "", "Purchase BFF Swagger UI"); - c.OAuthClientId("webshoppingaggswaggerui"); - c.OAuthAppName("web shopping bff Swagger UI"); + Predicate = r => r.Name.Contains("self") }); + }); } } @@ -104,29 +111,20 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator { public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration) { - JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); + JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); + var identityUrl = configuration.GetValue("urls:identity"); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - }).AddJwtBearer(options => + }) + .AddJwtBearer(options => { options.Authority = identityUrl; options.RequireHttpsMetadata = false; options.Audience = "webshoppingagg"; - options.Events = new JwtBearerEvents() - { - OnAuthenticationFailed = async ctx => - { - int i = 0; - }, - OnTokenValidated = async ctx => - { - int i = 0; - } - }; }); return services; @@ -137,30 +135,35 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator services.AddOptions(); services.Configure(configuration.GetSection("urls")); - services.AddMvc() - .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + services.AddControllers() + .AddNewtonsoftJson(); services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); - options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info + + options.SwaggerDoc("v1", new OpenApiInfo { - Title = "Shopping Aggregator for Web Clients", + Title = "Shopping Aggregator for Mobile Clients", Version = "v1", - Description = "Shopping Aggregator for Web Clients", - TermsOfService = "Terms Of Service" + Description = "Shopping Aggregator for Mobile Clients" }); - options.AddSecurityDefinition("oauth2", new OAuth2Scheme + options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { - Type = "oauth2", - Flow = "implicit", - AuthorizationUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize", - TokenUrl = $"{configuration.GetValue("IdentityUrlExternal")}/connect/token", - Scopes = new Dictionary() + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows() { - { "webshoppingagg", "Shopping Aggregator for Web Clients" }, - { "basket", "basket api" } + Implicit = new OpenApiOAuthFlow() + { + AuthorizationUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/authorize"), + TokenUrl = new Uri($"{configuration.GetValue("IdentityUrlExternal")}/connect/token"), + + Scopes = new Dictionary() + { + { "webshoppingagg", "Shopping Aggregator for Web Clients" } + } + } } }); @@ -204,6 +207,12 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator .AddPolicyHandler(GetCircuitBreakerPolicy()) .AddDevspacesSupport(); + services.AddHttpClient() + .AddHttpMessageHandler() + .AddPolicyHandler(GetRetryPolicy()) + .AddPolicyHandler(GetCircuitBreakerPolicy()) + .AddDevspacesSupport(); + return services; } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj index ed51b4860..b712ad270 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj @@ -33,10 +33,12 @@ - netcoreapp2.2 + $(NetCoreTargetVersion) Web.Shopping.HttpAggregator Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator ..\..\..\docker-compose.dcproj + false + true $(LangVersion) @@ -45,26 +47,32 @@ - - - - - - - - - - - - + + + - + + + + + + + + + + + + + + + + diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/appsettings.localhost.json b/src/ApiGateways/Web.Bff.Shopping/aggregator/appsettings.localhost.json index 57b5e894d..ad33f3414 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/appsettings.localhost.json +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/appsettings.localhost.json @@ -3,6 +3,8 @@ "basket": "http://localhost:55105", "catalog": "http://localhost:55101", "orders": "http://localhost:55102", - "identity": "http://localhost:55105" + "identity": "http://localhost:55105", + "grpcBasket": "http://localhost:5580", + "grpcOrdering": "http://localhost:5581" } } diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index c16619251..16cf2f2b5 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -19,6 +19,7 @@ 0.1.22-pre3 0.1.22-pre3 3.9.1 + 1.22.0 2.23.0 0.1.22-pre2 From 67af71d2ce4f6e9944430f12616794f4aa1a0c38 Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 28 Aug 2019 09:13:02 +0200 Subject: [PATCH 066/113] Add proto to catalog --- docker-compose.override.yml | 1 + .../aggregator/Config/UrlsConfig.cs | 2 + .../aggregator/Services/CatalogService.cs | 36 +++++- .../aggregator/Services/OrderingService.cs | 6 +- .../aggregator/appsettings.localhost.json | 1 + .../Catalog.API/Grpc/CatalogService.cs | 119 +++++++++++++++++- src/Services/Catalog/Catalog.API/Program.cs | 2 +- .../Catalog/Catalog.API/Proto/catalog.proto | 25 +++- 8 files changed, 178 insertions(+), 14 deletions(-) diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 1719fc18d..a8fce70ba 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -306,6 +306,7 @@ services: - urls__orders=http://ordering.api - urls__identity=http://identity.api - urls__grpcBasket=http://10.0.75.1:5580 + - urls__grpcCatalog=http://10.0.75.1:9101 - urls__grpcOrdering=http://10.0.75.1:5581 - CatalogUrlHC=http://catalog.api/hc - OrderingUrlHC=http://ordering.api/hc diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Config/UrlsConfig.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Config/UrlsConfig.cs index 0f7a13483..dccccab35 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Config/UrlsConfig.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Config/UrlsConfig.cs @@ -11,6 +11,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Config { // grpc call under REST must go trough port 80 public static string GetItemById(int id) => $"/api/v1/catalog/items/{id}"; + public static string GetItemById(string ids) => $"/api/v1/catalog/items/ids/{string.Join(',', ids)}"; // REST call standard must go through port 5000 public static string GetItemsById(IEnumerable ids) => $":5000/api/v1/catalog/items?ids={string.Join(',', ids)}"; } @@ -30,6 +31,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Config public string Catalog { get; set; } public string Orders { get; set; } public string GrpcBasket { get; set; } + public string GrpcCatalog { get; set; } public string GrpcOrdering { get; set; } } } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs index 4c98c031e..663baa1cf 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs @@ -6,6 +6,11 @@ using Newtonsoft.Json; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; +using CatalogApi; +using Grpc.Net.Client; +using System; +using static CatalogApi.Catalog; +using System.Linq; namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services { @@ -24,17 +29,38 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services public async Task GetCatalogItemAsync(int id) { - var uri=_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id); - var stringContent = await _httpClient.GetStringAsync(uri); + _httpClient.BaseAddress = new Uri(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id)); - return JsonConvert.DeserializeObject(stringContent); + var client = GrpcClient.Create(_httpClient); + var request = new CatalogItemRequest { Id = id }; + var response = await client.GetItemByIdAsync(request); + + return MapToCatalogItemResponse(response); } public async Task> GetCatalogItemsAsync(IEnumerable ids) { - var stringContent = await _httpClient.GetStringAsync(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemsById(ids)); + _httpClient.BaseAddress = new Uri(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemsById(ids)); + + var client = GrpcClient.Create(_httpClient); + var request = new CatalogItemsRequest { Ids = string.Join(",", ids), PageIndex = 1, PageSize = 10 }; + var response = await client.GetItemsByIdsAsync(request); + return response.Data.Select(this.MapToCatalogItemResponse); + //var stringContent = await _httpClient.GetStringAsync(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemsById(ids)); + //var catalogItems = JsonConvert.DeserializeObject(stringContent); - return JsonConvert.DeserializeObject(stringContent); + //return catalogItems; + } + + private CatalogItem MapToCatalogItemResponse(CatalogItemResponse catalogItemResponse) + { + return new CatalogItem + { + Id = catalogItemResponse.Id, + Name = catalogItemResponse.Name, + PictureUri = catalogItemResponse.PictureUri, + Price = (decimal)catalogItemResponse.Price + }; } } } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs index bba3b851c..1814e2d10 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs @@ -45,13 +45,12 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services try { - var command = MapToOrderDraftCommand(basketData); var response = await client.CreateOrderDraftFromBasketDataAsync(command); _logger.LogDebug(" grpc response: {@response}", response); - return MapToResponse(response); + return MapToResponse(response, basketData); } catch (RpcException e) { @@ -63,7 +62,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services return null; } - private OrderData MapToResponse(GrpcOrdering.OrderDraftDTO orderDraft) + private OrderData MapToResponse(GrpcOrdering.OrderDraftDTO orderDraft, BasketData basketData) { if (orderDraft == null) { @@ -72,6 +71,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services var data = new OrderData { + Buyer = basketData.BuyerId, Total = (decimal)orderDraft.Total, }; diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/appsettings.localhost.json b/src/ApiGateways/Web.Bff.Shopping/aggregator/appsettings.localhost.json index ad33f3414..57c5afc34 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/appsettings.localhost.json +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/appsettings.localhost.json @@ -5,6 +5,7 @@ "orders": "http://localhost:55102", "identity": "http://localhost:55105", "grpcBasket": "http://localhost:5580", + "grpcCatalog": "http://localhost:81", "grpcOrdering": "http://localhost:5581" } } diff --git a/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs b/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs index 97f40240f..b25d3b103 100644 --- a/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs +++ b/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs @@ -8,6 +8,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Catalog.API; using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure; using Microsoft.eShopOnContainers.Services.Catalog.API.Model; +using Microsoft.eShopOnContainers.Services.Catalog.API.ViewModel; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using static CatalogApi.Catalog; @@ -26,10 +27,10 @@ namespace Catalog.API.Grpc _logger = logger; } - public override async Task GetItemById(CatalogItemRequest request, ServerCallContext context) + public override async Task GetItemById(CatalogItemRequest request, ServerCallContext context) { _logger.LogInformation($"Begin grpc call CatalogService.GetItemById for product id {request.Id}"); - if (request.Id <=0) + if (request.Id <= 0) { context.Status = new Status(StatusCode.FailedPrecondition, $"Id must be > 0 (received {request.Id})"); return null; @@ -60,5 +61,119 @@ namespace Catalog.API.Grpc context.Status = new Status(StatusCode.NotFound, $"Product with id {request.Id} do not exist"); return null; } + + public override async Task GetItemsByIds(CatalogItemsRequest request, ServerCallContext context) + { + if (!string.IsNullOrEmpty(request.Ids)) + { + var items = await GetItemsByIdsAsync(request.Ids); + + if (!items.Any()) + { + context.Status = new Status(StatusCode.NotFound, $"ids value invalid. Must be comma-separated list of numbers"); + } + context.Status = new Status(StatusCode.OK, string.Empty); + return this.MapToResponse(items); + } + + var totalItems = await _catalogContext.CatalogItems + .LongCountAsync(); + + var itemsOnPage = await _catalogContext.CatalogItems + .OrderBy(c => c.Name) + .Skip(request.PageSize * request.PageIndex) + .Take(request.PageSize) + .ToListAsync(); + + /* The "awesome" fix for testing Devspaces */ + + /* + foreach (var pr in itemsOnPage) { + pr.Name = "Awesome " + pr.Name; + } + + */ + + itemsOnPage = ChangeUriPlaceholder(itemsOnPage); + + var model = this.MapToResponse(itemsOnPage, totalItems, request.PageIndex, request.PageSize); + context.Status = new Status(StatusCode.OK, string.Empty); + + return model; + } + + private PaginatedItemsResponse MapToResponse(List items) + { + return this.MapToResponse(items, items.Count(), 1, items.Count()); + } + + private PaginatedItemsResponse MapToResponse(List items, long count, int pageIndex, int pageSize) + { + var result = new PaginatedItemsResponse() + { + Count = count, + PageIndex = pageIndex, + PageSize = pageSize, + }; + + items.ForEach(i => result.Data.Add(new CatalogItemResponse() + { + AvailableStock = i.AvailableStock, + Description = i.Description, + Id = i.Id, + MaxStockThreshold = i.MaxStockThreshold, + Name = i.Name, + OnReorder = i.OnReorder, + PictureFileName = i.PictureFileName, + PictureUri = i.PictureUri, + RestockThreshold = i.RestockThreshold, + CatalogBrand = new CatalogApi.CatalogBrand() + { + Id = i.CatalogBrand.Id, + Name = i.CatalogBrand.Brand, + }, + CatalogType = new CatalogApi.CatalogType() + { + Id = i.CatalogType.Id, + Type = i.CatalogType.Type, + }, + Price = (double)i.Price, + })); + + return result; + } + + + private async Task> GetItemsByIdsAsync(string ids) + { + var numIds = ids.Split(',').Select(id => (Ok: int.TryParse(id, out int x), Value: x)); + + if (!numIds.All(nid => nid.Ok)) + { + return new List(); + } + + var idsToSelect = numIds + .Select(id => id.Value); + + var items = await _catalogContext.CatalogItems.Where(ci => idsToSelect.Contains(ci.Id)).ToListAsync(); + + items = ChangeUriPlaceholder(items); + + return items; + } + + private List ChangeUriPlaceholder(List items) + { + var baseUri = _settings.PicBaseUrl; + var azureStorageEnabled = _settings.AzureStorageEnabled; + + foreach (var item in items) + { + item.FillProductUrl(baseUri, azureStorageEnabled: azureStorageEnabled); + } + + return items; + } } } diff --git a/src/Services/Catalog/Catalog.API/Program.cs b/src/Services/Catalog/Catalog.API/Program.cs index d28ee5a54..f3198e7bd 100644 --- a/src/Services/Catalog/Catalog.API/Program.cs +++ b/src/Services/Catalog/Catalog.API/Program.cs @@ -105,7 +105,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API private static (int httpPort, int grpcPort) GetDefinedPorts(IConfiguration config) { - var grpcPort = config.GetValue("GRPC_PORT", 5001); + var grpcPort = config.GetValue("GRPC_PORT", 81); var port = config.GetValue("PORT", 80); return (port, grpcPort); } diff --git a/src/Services/Catalog/Catalog.API/Proto/catalog.proto b/src/Services/Catalog/Catalog.API/Proto/catalog.proto index 09d9c6e38..adeeb4b26 100644 --- a/src/Services/Catalog/Catalog.API/Proto/catalog.proto +++ b/src/Services/Catalog/Catalog.API/Proto/catalog.proto @@ -10,6 +10,11 @@ package CatalogApi; message CatalogItemRequest { int32 id = 1; } +message CatalogItemsRequest { + string ids = 1; + int32 pageSize = 2; + int32 pageIndex = 3; +} message CatalogItemResponse { int32 id = 1; @@ -36,12 +41,26 @@ message CatalogType { string type = 2; } +message PaginatedItemsResponse { + int32 pageIndex = 1; + int32 pageSize = 2; + int64 count = 3; + repeated CatalogItemResponse data = 4; +} + service Catalog { rpc GetItemById (CatalogItemRequest) returns (CatalogItemResponse) { - /* >> + /* >> option (google.api.http) = { get: "/api/v1/catalog/items/{id}" }; -<< */ - } + << */ + } + rpc GetItemsByIds (CatalogItemsRequest) returns (PaginatedItemsResponse) { + /* >> + option (google.api.http) = { + get: "/api/v1/catalog/items/ids/{ids}" + }; + << */ + } } \ No newline at end of file From 11fe3fc42c9c6254b35cd588c6700865e5c1f424 Mon Sep 17 00:00:00 2001 From: eiximenis Date: Wed, 28 Aug 2019 10:30:55 +0200 Subject: [PATCH 067/113] Moved some files to ./src/ --- .../docker-compose-external.override.yml | 0 .../docker-compose-external.yml | 0 .../docker-compose-tests.override.yml | 0 .../docker-compose-tests.yml | 20 ++--- .../docker-compose-windows.prod.yml | 0 .../docker-compose.dcproj | 0 .../docker-compose.elk.yml | 0 .../docker-compose.nobuild.yml | 0 .../docker-compose.override.windows.yml | 0 .../docker-compose.override.yml | 10 +-- .../docker-compose.prod.yml | 8 +- .../docker-compose.windows.yml | 0 docker-compose.yml => src/docker-compose.yml | 40 ++++----- .../eShopOnContainers-ServicesAndWebApps.sln | 84 +++++++++---------- 14 files changed, 81 insertions(+), 81 deletions(-) rename docker-compose-external.override.yml => src/docker-compose-external.override.yml (100%) rename docker-compose-external.yml => src/docker-compose-external.yml (100%) rename docker-compose-tests.override.yml => src/docker-compose-tests.override.yml (100%) rename docker-compose-tests.yml => src/docker-compose-tests.yml (82%) rename docker-compose-windows.prod.yml => src/docker-compose-windows.prod.yml (100%) rename docker-compose.dcproj => src/docker-compose.dcproj (100%) rename docker-compose.elk.yml => src/docker-compose.elk.yml (100%) rename docker-compose.nobuild.yml => src/docker-compose.nobuild.yml (100%) rename docker-compose.override.windows.yml => src/docker-compose.override.windows.yml (100%) rename docker-compose.override.yml => src/docker-compose.override.yml (97%) rename docker-compose.prod.yml => src/docker-compose.prod.yml (98%) rename docker-compose.windows.yml => src/docker-compose.windows.yml (100%) rename docker-compose.yml => src/docker-compose.yml (78%) rename eShopOnContainers-ServicesAndWebApps.sln => src/eShopOnContainers-ServicesAndWebApps.sln (96%) diff --git a/docker-compose-external.override.yml b/src/docker-compose-external.override.yml similarity index 100% rename from docker-compose-external.override.yml rename to src/docker-compose-external.override.yml diff --git a/docker-compose-external.yml b/src/docker-compose-external.yml similarity index 100% rename from docker-compose-external.yml rename to src/docker-compose-external.yml diff --git a/docker-compose-tests.override.yml b/src/docker-compose-tests.override.yml similarity index 100% rename from docker-compose-tests.override.yml rename to src/docker-compose-tests.override.yml diff --git a/docker-compose-tests.yml b/src/docker-compose-tests.yml similarity index 82% rename from docker-compose-tests.yml rename to src/docker-compose-tests.yml index 7794d1a0e..440e3e5c0 100644 --- a/docker-compose-tests.yml +++ b/src/docker-compose-tests.yml @@ -17,7 +17,7 @@ services: image: ${REGISTRY:-eshop}/identity-api-test:${TAG:-latest} build: context: . - dockerfile: src/Services/Identity/Identity.API/Dockerfile + dockerfile: Services/Identity/Identity.API/Dockerfile depends_on: - sql-data-test @@ -25,7 +25,7 @@ services: image: ${REGISTRY:-eshop}/basket-api-test:${TAG:-latest} build: context: . - dockerfile: src/Services/Basket/Basket.API/Dockerfile + dockerfile: Services/Basket/Basket.API/Dockerfile target: functionaltest depends_on: - basket-data-test @@ -38,7 +38,7 @@ services: image: ${REGISTRY:-eshop}/basket-api-test:${TAG:-latest} build: context: . - dockerfile: src/Services/Basket/Basket.API/Dockerfile + dockerfile: Services/Basket/Basket.API/Dockerfile target: unittest depends_on: - basket-data-test @@ -51,7 +51,7 @@ services: image: ${REGISTRY:-eshop}/catalog-api-test:${TAG:-latest} build: context: . - dockerfile: src/Services/Catalog/Catalog.API/Dockerfile + dockerfile: Services/Catalog/Catalog.API/Dockerfile target: functionaltest depends_on: - sql-data-test @@ -63,7 +63,7 @@ services: image: ${REGISTRY:-eshop}/catalog-api-test:${TAG:-latest} build: context: . - dockerfile: src/Services/Catalog/Catalog.API/Dockerfile + dockerfile: Services/Catalog/Catalog.API/Dockerfile target: unittest depends_on: - sql-data-test @@ -75,7 +75,7 @@ services: image: ${REGISTRY:-eshop}/ordering-api-test:${TAG:-latest} build: context: . - dockerfile: src/Services/Ordering/Ordering.API/Dockerfile + dockerfile: Services/Ordering/Ordering.API/Dockerfile target: functionaltest depends_on: - sql-data-test @@ -87,7 +87,7 @@ services: image: ${REGISTRY:-eshop}/ordering-api-test:${TAG:-latest} build: context: . - dockerfile: src/Services/Ordering/Ordering.API/Dockerfile + dockerfile: Services/Ordering/Ordering.API/Dockerfile target: unittest depends_on: - sql-data-test @@ -99,7 +99,7 @@ services: image: ${REGISTRY:-eshop}/marketing-api-test:${TAG:-latest} build: context: . - dockerfile: src/Services/Marketing/Marketing.API/Dockerfile + dockerfile: Services/Marketing/Marketing.API/Dockerfile target: functionaltest depends_on: - sql-data-test @@ -113,7 +113,7 @@ services: image: ${REGISTRY:-eshop}/payment-api-test:${TAG:-latest} build: context: . - dockerfile: src/Services/Payment/Payment.API/Dockerfile + dockerfile: Services/Payment/Payment.API/Dockerfile depends_on: - rabbitmq-test @@ -121,7 +121,7 @@ services: image: ${REGISTRY:-eshop}/locations-api-test:${TAG:-latest} build: context: . - dockerfile: src/Services/Location/Locations.API/Dockerfile + dockerfile: Services/Location/Locations.API/Dockerfile target: functionaltest depends_on: - nosql-data-test diff --git a/docker-compose-windows.prod.yml b/src/docker-compose-windows.prod.yml similarity index 100% rename from docker-compose-windows.prod.yml rename to src/docker-compose-windows.prod.yml diff --git a/docker-compose.dcproj b/src/docker-compose.dcproj similarity index 100% rename from docker-compose.dcproj rename to src/docker-compose.dcproj diff --git a/docker-compose.elk.yml b/src/docker-compose.elk.yml similarity index 100% rename from docker-compose.elk.yml rename to src/docker-compose.elk.yml diff --git a/docker-compose.nobuild.yml b/src/docker-compose.nobuild.yml similarity index 100% rename from docker-compose.nobuild.yml rename to src/docker-compose.nobuild.yml diff --git a/docker-compose.override.windows.yml b/src/docker-compose.override.windows.yml similarity index 100% rename from docker-compose.override.windows.yml rename to src/docker-compose.override.windows.yml diff --git a/docker-compose.override.yml b/src/docker-compose.override.yml similarity index 97% rename from docker-compose.override.yml rename to src/docker-compose.override.yml index a8fce70ba..fb4d2b6b7 100644 --- a/docker-compose.override.yml +++ b/src/docker-compose.override.yml @@ -225,7 +225,7 @@ services: ports: - "5200:80" volumes: - - ./src/ApiGateways/Mobile.Bff.Shopping/apigw:${ESHOP_OCELOT_VOLUME_SPEC:-/app/configuration} + - ./ApiGateways/Mobile.Bff.Shopping/apigw:${ESHOP_OCELOT_VOLUME_SPEC:-/app/configuration} mobilemarketingapigw: environment: @@ -242,7 +242,7 @@ services: ports: - "5201:80" volumes: - - ./src/ApiGateways/Mobile.Bff.Marketing/apigw:${ESHOP_OCELOT_VOLUME_SPEC:-/app/configuration} + - ./ApiGateways/Mobile.Bff.Marketing/apigw:${ESHOP_OCELOT_VOLUME_SPEC:-/app/configuration} webshoppingapigw: environment: @@ -259,7 +259,7 @@ services: ports: - "5202:80" volumes: - - ./src/ApiGateways/Web.Bff.Shopping/apigw:${ESHOP_OCELOT_VOLUME_SPEC:-/app/configuration} + - ./ApiGateways/Web.Bff.Shopping/apigw:${ESHOP_OCELOT_VOLUME_SPEC:-/app/configuration} webmarketingapigw: environment: @@ -276,7 +276,7 @@ services: ports: - "5203:80" volumes: - - ./src/ApiGateways/Web.Bff.Marketing/apigw:${ESHOP_OCELOT_VOLUME_SPEC:-/app/configuration} + - ./ApiGateways/Web.Bff.Marketing/apigw:${ESHOP_OCELOT_VOLUME_SPEC:-/app/configuration} mobileshoppingagg: environment: @@ -424,6 +424,6 @@ services: envoy: volumes: - - ./src/ApiGateways/Envoy/config:/etc/envoy + - ./ApiGateways/Envoy/config:/etc/envoy ports: - "51051:51051" \ No newline at end of file diff --git a/docker-compose.prod.yml b/src/docker-compose.prod.yml similarity index 98% rename from docker-compose.prod.yml rename to src/docker-compose.prod.yml index aed216ef9..de88fd718 100644 --- a/docker-compose.prod.yml +++ b/src/docker-compose.prod.yml @@ -249,7 +249,7 @@ services: - "5200:80" # Important: In a production environment your should remove the external port (5200) kept here for microservice debugging purposes. # The API Gateway redirects and access through the internal port (80). volumes: - - ./src/ApiGateways/Mobile.Bff.Shopping/apigw:/app/configuration + - ./ApiGateways/Mobile.Bff.Shopping/apigw:/app/configuration mobilemarketingapigw: environment: @@ -259,7 +259,7 @@ services: - "5201:80" # Important: In a production environment your should remove the external port (5201) kept here for microservice debugging purposes. # The API Gateway redirects and access through the internal port (80). volumes: - - ./src/ApiGateways/Mobile.Bff.Marketing/apigw:/app/configuration + - ./ApiGateways/Mobile.Bff.Marketing/apigw:/app/configuration webshoppingapigw: environment: @@ -269,7 +269,7 @@ services: - "5202:80" # Important: In a production environment your should remove the external port (5202) kept here for microservice debugging purposes. # The API Gateway redirects and access through the internal port (80). volumes: - - ./src/ApiGateways/Web.Bff.Shopping/apigw:/app/configuration + - ./ApiGateways/Web.Bff.Shopping/apigw:/app/configuration webmarketingapigw: environment: @@ -279,7 +279,7 @@ services: - "5203:80" # Important: In a production environment your should remove the external port (5203) kept here for microservice debugging purposes. # The API Gateway redirects and access through the internal port (80). volumes: - - ./src/ApiGateways/Web.Bff.Marketing/apigw:/app/configuration + - ./ApiGateways/Web.Bff.Marketing/apigw:/app/configuration mobileshoppingagg: environment: diff --git a/docker-compose.windows.yml b/src/docker-compose.windows.yml similarity index 100% rename from docker-compose.windows.yml rename to src/docker-compose.windows.yml diff --git a/docker-compose.yml b/src/docker-compose.yml similarity index 78% rename from docker-compose.yml rename to src/docker-compose.yml index 243fbf2c6..7322fe63a 100644 --- a/docker-compose.yml +++ b/src/docker-compose.yml @@ -21,7 +21,7 @@ services: image: ${REGISTRY:-eshop}/identity.api:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Services/Identity/Identity.API/Dockerfile + dockerfile: Services/Identity/Identity.API/Dockerfile depends_on: - sql.data @@ -29,7 +29,7 @@ services: image: ${REGISTRY:-eshop}/basket.api:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Services/Basket/Basket.API/Dockerfile + dockerfile: Services/Basket/Basket.API/Dockerfile depends_on: - basket.data - identity.api @@ -39,7 +39,7 @@ services: image: ${REGISTRY:-eshop}/catalog.api:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Services/Catalog/Catalog.API/Dockerfile + dockerfile: Services/Catalog/Catalog.API/Dockerfile depends_on: - sql.data - rabbitmq @@ -48,7 +48,7 @@ services: image: ${REGISTRY:-eshop}/ordering.api:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Services/Ordering/Ordering.API/Dockerfile + dockerfile: Services/Ordering/Ordering.API/Dockerfile depends_on: - sql.data - rabbitmq @@ -57,7 +57,7 @@ services: image: ${REGISTRY:-eshop}/ordering.backgroundtasks:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile + dockerfile: Services/Ordering/Ordering.BackgroundTasks/Dockerfile depends_on: - sql.data - rabbitmq @@ -66,7 +66,7 @@ services: image: ${REGISTRY:-eshop}/marketing.api:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Services/Marketing/Marketing.API/Dockerfile + dockerfile: Services/Marketing/Marketing.API/Dockerfile depends_on: - sql.data - nosql.data @@ -77,7 +77,7 @@ services: image: ${REGISTRY:-eshop}/payment.api:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Services/Payment/Payment.API/Dockerfile + dockerfile: Services/Payment/Payment.API/Dockerfile depends_on: - rabbitmq @@ -85,7 +85,7 @@ services: image: ${REGISTRY:-eshop}/locations.api:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Services/Location/Locations.API/Dockerfile + dockerfile: Services/Location/Locations.API/Dockerfile depends_on: - nosql.data - rabbitmq @@ -94,7 +94,7 @@ services: image: ${REGISTRY:-eshop}/webhooks.api:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Services/Webhooks/Webhooks.API/Dockerfile + dockerfile: Services/Webhooks/Webhooks.API/Dockerfile depends_on: - sql.data @@ -102,7 +102,7 @@ services: image: ${REGISTRY:-eshop}/ocelotapigw:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/ApiGateways/ApiGw-Base/Dockerfile + dockerfile: ApiGateways/ApiGw-Base/Dockerfile depends_on: - nosql.data - sql.data @@ -117,7 +117,7 @@ services: image: ${REGISTRY:-eshop}/ocelotapigw:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/ApiGateways/ApiGw-Base/Dockerfile + dockerfile: ApiGateways/ApiGw-Base/Dockerfile depends_on: - nosql.data - sql.data @@ -132,7 +132,7 @@ services: image: ${REGISTRY:-eshop}/ocelotapigw:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/ApiGateways/ApiGw-Base/Dockerfile + dockerfile: ApiGateways/ApiGw-Base/Dockerfile depends_on: - nosql.data - sql.data @@ -147,7 +147,7 @@ services: image: ${REGISTRY:-eshop}/ocelotapigw:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/ApiGateways/ApiGw-Base/Dockerfile + dockerfile: ApiGateways/ApiGw-Base/Dockerfile depends_on: - nosql.data - sql.data @@ -162,7 +162,7 @@ services: image: ${REGISTRY:-eshop}/mobileshoppingagg:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile + dockerfile: ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile depends_on: - nosql.data - sql.data @@ -177,7 +177,7 @@ services: image: ${REGISTRY:-eshop}/webshoppingagg:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile + dockerfile: ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile depends_on: - nosql.data - sql.data @@ -192,7 +192,7 @@ services: image: ${REGISTRY:-eshop}/ordering.signalrhub:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Services/Ordering/Ordering.SignalrHub/Dockerfile + dockerfile: Services/Ordering/Ordering.SignalrHub/Dockerfile depends_on: - nosql.data - sql.data @@ -207,13 +207,13 @@ services: image: ${REGISTRY:-eshop}/webstatus:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Web/WebStatus/Dockerfile + dockerfile: Web/WebStatus/Dockerfile webspa: image: ${REGISTRY:-eshop}/webspa:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Web/WebSPA/Dockerfile + dockerfile: Web/WebSPA/Dockerfile args: NODE_IMAGE: ${NODE_IMAGE:-node:8.11} # depends_on: @@ -225,7 +225,7 @@ services: image: ${REGISTRY:-eshop}/webmvc:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Web/WebMVC/Dockerfile + dockerfile: Web/WebMVC/Dockerfile depends_on: - webshoppingagg - webshoppingapigw @@ -235,7 +235,7 @@ services: image: ${REGISTRY:-eshop}/webhooks.client:${PLATFORM:-linux}-${TAG:-latest} build: context: . - dockerfile: src/Web/WebhookClient/Dockerfile + dockerfile: Web/WebhookClient/Dockerfile depends_on: - webhooks.api diff --git a/eShopOnContainers-ServicesAndWebApps.sln b/src/eShopOnContainers-ServicesAndWebApps.sln similarity index 96% rename from eShopOnContainers-ServicesAndWebApps.sln rename to src/eShopOnContainers-ServicesAndWebApps.sln index 52f49f96c..9ba773aa5 100644 --- a/eShopOnContainers-ServicesAndWebApps.sln +++ b/src/eShopOnContainers-ServicesAndWebApps.sln @@ -30,47 +30,47 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ServicesTests", "ServicesTe EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Identity", "Identity", "{24CD3B53-141E-4A07-9B0D-796641E1CF78}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basket.API", "src\Services\Basket\Basket.API\Basket.API.csproj", "{2110CBB0-3B38-4EE4-A743-DF6968D80D90}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basket.API", "Services\Basket\Basket.API\Basket.API.csproj", "{2110CBB0-3B38-4EE4-A743-DF6968D80D90}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Catalog.API", "src\Services\Catalog\Catalog.API\Catalog.API.csproj", "{42681D9D-750A-4DF7-BD9F-9292CFD5C253}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Catalog.API", "Services\Catalog\Catalog.API\Catalog.API.csproj", "{42681D9D-750A-4DF7-BD9F-9292CFD5C253}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.API", "src\Services\Ordering\Ordering.API\Ordering.API.csproj", "{231226CE-690B-4979-8870-9A79D80928E2}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.API", "Services\Ordering\Ordering.API\Ordering.API.csproj", "{231226CE-690B-4979-8870-9A79D80928E2}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.Domain", "src\Services\Ordering\Ordering.Domain\Ordering.Domain.csproj", "{F5598DCB-6DDE-4661-AD9D-A55612DA7E76}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.Domain", "Services\Ordering\Ordering.Domain\Ordering.Domain.csproj", "{F5598DCB-6DDE-4661-AD9D-A55612DA7E76}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebMVC", "src\Web\WebMVC\WebMVC.csproj", "{F0333D8E-0B27-42B7-B2C6-78F3657624E2}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebMVC", "Web\WebMVC\WebMVC.csproj", "{F0333D8E-0B27-42B7-B2C6-78F3657624E2}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.Infrastructure", "src\Services\Ordering\Ordering.Infrastructure\Ordering.Infrastructure.csproj", "{95F1F07C-4D92-4742-BD07-E5B805AAB651}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.Infrastructure", "Services\Ordering\Ordering.Infrastructure\Ordering.Infrastructure.csproj", "{95F1F07C-4D92-4742-BD07-E5B805AAB651}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Identity.API", "src\Services\Identity\Identity.API\Identity.API.csproj", "{A579E108-5445-403D-A407-339AC4D1611B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Identity.API", "Services\Identity\Identity.API\Identity.API.csproj", "{A579E108-5445-403D-A407-339AC4D1611B}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebSPA", "src\Web\WebSPA\WebSPA.csproj", "{F16E3C6A-1C94-4EAB-BE91-099618060B68}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebSPA", "Web\WebSPA\WebSPA.csproj", "{F16E3C6A-1C94-4EAB-BE91-099618060B68}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "BuildingBlocks", "BuildingBlocks", "{DB0EFB20-B024-4E5E-A75C-52143C131D25}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "EventBus", "EventBus", "{807BB76E-B2BB-47A2-A57B-3D1B20FF5E7F}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventBus", "src\BuildingBlocks\EventBus\EventBus\EventBus.csproj", "{0044B293-1DCC-4224-B948-00CF6DC7F510}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventBus", "BuildingBlocks\EventBus\EventBus\EventBus.csproj", "{0044B293-1DCC-4224-B948-00CF6DC7F510}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventBusRabbitMQ", "src\BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj", "{8088F3FC-6787-45FA-A924-816EC81CBFAC}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventBusRabbitMQ", "BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj", "{8088F3FC-6787-45FA-A924-816EC81CBFAC}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegrationEventLogEF", "src\BuildingBlocks\EventBus\IntegrationEventLogEF\IntegrationEventLogEF.csproj", "{9EE28E45-1533-472B-8267-56C48855BA0E}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegrationEventLogEF", "BuildingBlocks\EventBus\IntegrationEventLogEF\IntegrationEventLogEF.csproj", "{9EE28E45-1533-472B-8267-56C48855BA0E}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebStatus", "src\Web\WebStatus\WebStatus.csproj", "{C0A7918D-B4F2-4E7F-8DE2-1E5279EF079F}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebStatus", "Web\WebStatus\WebStatus.csproj", "{C0A7918D-B4F2-4E7F-8DE2-1E5279EF079F}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Location", "Location", "{41139F64-4046-4F16-96B7-D941D96FA9C6}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Locations.API", "src\Services\Location\Locations.API\Locations.API.csproj", "{E7581357-FC34-474C-B8F5-307EE3CE05EF}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Locations.API", "Services\Location\Locations.API\Locations.API.csproj", "{E7581357-FC34-474C-B8F5-307EE3CE05EF}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Marketing", "Marketing", "{A5260DE0-1FDD-467E-9CC1-A028AB081CEE}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Marketing.API", "src\Services\Marketing\Marketing.API\Marketing.API.csproj", "{DF395F85-B010-465D-857A-7EBCC512C0C2}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Marketing.API", "Services\Marketing\Marketing.API\Marketing.API.csproj", "{DF395F85-B010-465D-857A-7EBCC512C0C2}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventBusServiceBus", "src\BuildingBlocks\EventBus\EventBusServiceBus\EventBusServiceBus.csproj", "{69AF10D3-AA76-4FF7-B187-EC7E8CC5F5B8}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventBusServiceBus", "BuildingBlocks\EventBus\EventBusServiceBus\EventBusServiceBus.csproj", "{69AF10D3-AA76-4FF7-B187-EC7E8CC5F5B8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "WebHost", "WebHost", "{1815B651-941C-466B-AE33-D1D7EEB8F77F}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebHost.Customization", "src\BuildingBlocks\WebHostCustomization\WebHost.Customization\WebHost.Customization.csproj", "{15F4B3AA-89B6-4A0D-9051-414305974781}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebHost.Customization", "BuildingBlocks\WebHostCustomization\WebHost.Customization\WebHost.Customization.csproj", "{15F4B3AA-89B6-4A0D-9051-414305974781}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ApiGateways", "ApiGateways", "{77849D35-37D4-4802-81DC-9477B2775A40}" EndProject @@ -78,47 +78,47 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ApiGw-Base", "ApiGw-Base", EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Mobile.Bff.Marketing", "Mobile.Bff.Marketing", "{DB813A36-11BA-41FE-B258-CA9A7152247B}" ProjectSection(SolutionItems) = preProject - src\ApiGateways\Mobile.Bff.Marketing\apigw\configuration.json = src\ApiGateways\Mobile.Bff.Marketing\apigw\configuration.json + ApiGateways\Mobile.Bff.Marketing\apigw\configuration.json = ApiGateways\Mobile.Bff.Marketing\apigw\configuration.json EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Mobile.Bff.Shopping", "Mobile.Bff.Shopping", "{0189E4FB-6E2B-4F2E-9B1D-5473D23FC6DB}" ProjectSection(SolutionItems) = preProject - src\ApiGateways\Mobile.Bff.Shopping\apigw\configuration.json = src\ApiGateways\Mobile.Bff.Shopping\apigw\configuration.json + ApiGateways\Mobile.Bff.Shopping\apigw\configuration.json = ApiGateways\Mobile.Bff.Shopping\apigw\configuration.json EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Web.Bff.Marketing", "Web.Bff.Marketing", "{F8F0921C-EE5D-4AED-A4D6-5BF5FAE02CB5}" ProjectSection(SolutionItems) = preProject - src\ApiGateways\Web.Bff.Marketing\apigw\configuration.json = src\ApiGateways\Web.Bff.Marketing\apigw\configuration.json + ApiGateways\Web.Bff.Marketing\apigw\configuration.json = ApiGateways\Web.Bff.Marketing\apigw\configuration.json EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Web.Bff.Shopping", "Web.Bff.Shopping", "{28C0F5C8-4849-4035-80AB-45639424E73F}" ProjectSection(SolutionItems) = preProject - src\ApiGateways\Web.Bff.Shopping\apigw\configuration.json = src\ApiGateways\Web.Bff.Shopping\apigw\configuration.json + ApiGateways\Web.Bff.Shopping\apigw\configuration.json = ApiGateways\Web.Bff.Shopping\apigw\configuration.json EndProjectSection EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OcelotApiGw", "src\ApiGateways\ApiGw-Base\OcelotApiGw.csproj", "{3F79558C-485D-49E1-BD3E-E12538D3D308}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OcelotApiGw", "ApiGateways\ApiGw-Base\OcelotApiGw.csproj", "{3F79558C-485D-49E1-BD3E-E12538D3D308}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mobile.Shopping.HttpAggregator", "src\ApiGateways\Mobile.Bff.Shopping\aggregator\Mobile.Shopping.HttpAggregator.csproj", "{BEA37D6D-4CF2-4AE8-9575-72388E54FBD0}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mobile.Shopping.HttpAggregator", "ApiGateways\Mobile.Bff.Shopping\aggregator\Mobile.Shopping.HttpAggregator.csproj", "{BEA37D6D-4CF2-4AE8-9575-72388E54FBD0}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Web.Shopping.HttpAggregator", "src\ApiGateways\Web.Bff.Shopping\aggregator\Web.Shopping.HttpAggregator.csproj", "{AF0828DB-8BDD-411A-AEEF-B780FBB8D8C1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Web.Shopping.HttpAggregator", "ApiGateways\Web.Bff.Shopping\aggregator\Web.Shopping.HttpAggregator.csproj", "{AF0828DB-8BDD-411A-AEEF-B780FBB8D8C1}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.SignalrHub", "src\Services\Ordering\Ordering.SignalrHub\Ordering.SignalrHub.csproj", "{E1D2B260-4E7F-4A88-BC13-9910F7C44623}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.SignalrHub", "Services\Ordering\Ordering.SignalrHub\Ordering.SignalrHub.csproj", "{E1D2B260-4E7F-4A88-BC13-9910F7C44623}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basket.UnitTests", "src\Services\Basket\Basket.UnitTests\Basket.UnitTests.csproj", "{9D9CE4E4-1DD0-4961-861F-219731DE06CE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basket.UnitTests", "Services\Basket\Basket.UnitTests\Basket.UnitTests.csproj", "{9D9CE4E4-1DD0-4961-861F-219731DE06CE}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Catalog.UnitTests", "src\Services\Catalog\Catalog.UnitTests\Catalog.UnitTests.csproj", "{791961C7-3F3E-434E-B2BA-B4D6B5E222B0}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Catalog.UnitTests", "Services\Catalog\Catalog.UnitTests\Catalog.UnitTests.csproj", "{791961C7-3F3E-434E-B2BA-B4D6B5E222B0}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basket.FunctionalTests", "src\Services\Basket\Basket.FunctionalTests\Basket.FunctionalTests.csproj", "{3F6202D0-2842-4C2F-98E1-9462709EAFBE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basket.FunctionalTests", "Services\Basket\Basket.FunctionalTests\Basket.FunctionalTests.csproj", "{3F6202D0-2842-4C2F-98E1-9462709EAFBE}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.UnitTests", "src\Services\Ordering\Ordering.UnitTests\Ordering.UnitTests.csproj", "{B1182FD9-C245-4018-8412-C66F290C7F4C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.UnitTests", "Services\Ordering\Ordering.UnitTests\Ordering.UnitTests.csproj", "{B1182FD9-C245-4018-8412-C66F290C7F4C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Catalog.FunctionalTests", "src\Services\Catalog\Catalog.FunctionalTests\Catalog.FunctionalTests.csproj", "{38107691-A437-461D-A85C-ACD3AC7ACFAB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Catalog.FunctionalTests", "Services\Catalog\Catalog.FunctionalTests\Catalog.FunctionalTests.csproj", "{38107691-A437-461D-A85C-ACD3AC7ACFAB}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Locations.FunctionalTests", "src\Services\Location\Locations.FunctionalTests\Locations.FunctionalTests.csproj", "{16F463AA-9CF6-44DC-B18C-7310CCF663FF}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Locations.FunctionalTests", "Services\Location\Locations.FunctionalTests\Locations.FunctionalTests.csproj", "{16F463AA-9CF6-44DC-B18C-7310CCF663FF}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.FunctionalTests", "src\Services\Ordering\Ordering.FunctionalTests\Ordering.FunctionalTests.csproj", "{DA7D3E03-D0B6-4591-8143-779D3E9F3F30}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ordering.FunctionalTests", "Services\Ordering\Ordering.FunctionalTests\Ordering.FunctionalTests.csproj", "{DA7D3E03-D0B6-4591-8143-779D3E9F3F30}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Marketing.FunctionalTests", "src\Services\Marketing\Marketing.FunctionalTests\Marketing.FunctionalTests.csproj", "{94176D9B-9CAA-4762-8D12-1621E240EE34}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Marketing.FunctionalTests", "Services\Marketing\Marketing.FunctionalTests\Marketing.FunctionalTests.csproj", "{94176D9B-9CAA-4762-8D12-1621E240EE34}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoadTest", "test\ServicesTests\LoadTest\LoadTest.csproj", "{969E793C-C413-490E-9C9D-B2B46DA5AF32}" EndProject @@ -136,32 +136,32 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{120CABB3 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Payment", "Payment", "{C61C5CFE-4876-4A46-A96E-5BBF596A984A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Payment.API", "src\Services\Payment\Payment.API\Payment.API.csproj", "{0AB40131-8AD7-436F-9C6B-EDA59CFA3A84}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Payment.API", "Services\Payment\Payment.API\Payment.API.csproj", "{0AB40131-8AD7-436F-9C6B-EDA59CFA3A84}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Webhooks", "Webhooks", "{E0AA11C4-2873-461D-8F82-53392530FB7A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Webhooks.API", "src\Services\Webhooks\Webhooks.API\Webhooks.API.csproj", "{84E2016E-0435-44C6-8020-3D288AA38B2C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Webhooks.API", "Services\Webhooks\Webhooks.API\Webhooks.API.csproj", "{84E2016E-0435-44C6-8020-3D288AA38B2C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebhookClient", "src\Web\WebhookClient\WebhookClient.csproj", "{766D7E92-6AF0-476C-ADD5-282BF4D8C576}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebhookClient", "Web\WebhookClient\WebhookClient.csproj", "{766D7E92-6AF0-476C-ADD5-282BF4D8C576}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Devspace.Support", "Devspace.Support", "{68F5041D-51F2-4630-94B6-B49789F5E51A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Devspaces.Support", "src\BuildingBlocks\Devspaces.Support\Devspaces.Support.csproj", "{56C2EF0B-6BF2-41D9-BE07-6E6D08D06B35}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Devspaces.Support", "BuildingBlocks\Devspaces.Support\Devspaces.Support.csproj", "{56C2EF0B-6BF2-41D9-BE07-6E6D08D06B35}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Envoy", "Envoy", "{882A8F3A-C61F-4C44-86DD-A5A258714BF2}" ProjectSection(SolutionItems) = preProject - src\ApiGateways\Envoy\Dockerfile = src\ApiGateways\Envoy\Dockerfile + ApiGateways\Envoy\Dockerfile = ApiGateways\Envoy\Dockerfile EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "config", "config", "{3ABEEE8C-35E0-4185-9825-C44326151F5B}" ProjectSection(SolutionItems) = preProject - src\ApiGateways\Envoy\config\catalog.proto = src\ApiGateways\Envoy\config\catalog.proto - src\ApiGateways\Envoy\config\catalog.proto-descriptor.pb = src\ApiGateways\Envoy\config\catalog.proto-descriptor.pb - src\ApiGateways\Envoy\Dockerfile = src\ApiGateways\Envoy\Dockerfile - src\ApiGateways\Envoy\config\envoy.yaml = src\ApiGateways\Envoy\config\envoy.yaml + ApiGateways\Envoy\config\catalog.proto = ApiGateways\Envoy\config\catalog.proto + ApiGateways\Envoy\config\catalog.proto-descriptor.pb = ApiGateways\Envoy\config\catalog.proto-descriptor.pb + ApiGateways\Envoy\Dockerfile = ApiGateways\Envoy\Dockerfile + ApiGateways\Envoy\config\envoy.yaml = ApiGateways\Envoy\config\envoy.yaml EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ordering.BackgroundTasks", "src\Services\Ordering\Ordering.BackgroundTasks\Ordering.BackgroundTasks.csproj", "{D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ordering.BackgroundTasks", "Services\Ordering\Ordering.BackgroundTasks\Ordering.BackgroundTasks.csproj", "{D4DBA4A3-E4A5-4D9D-8ACF-F38F7D506191}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution From 011dc71a979202d043d02e441128db09054358f8 Mon Sep 17 00:00:00 2001 From: eiximenis Date: Wed, 28 Aug 2019 10:32:41 +0200 Subject: [PATCH 068/113] Moved .env to src --- .env => src/.env | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .env => src/.env (100%) diff --git a/.env b/src/.env similarity index 100% rename from .env rename to src/.env From 3fee58e6664a82941f322486808a0ae29aa636ba Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 28 Aug 2019 10:57:35 +0200 Subject: [PATCH 069/113] partial checkin --- .../aggregator/Services/BasketService.cs | 44 ++++++++++++-- .../aggregator/Services/CatalogService.cs | 37 +++++++++--- .../Catalog.API/Grpc/CatalogService.cs | 59 ++++++++++++------- .../Catalog/Catalog.API/Proto/catalog.proto | 8 +-- 4 files changed, 108 insertions(+), 40 deletions(-) diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs index 3e68816c1..2bfc30ce9 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs @@ -66,12 +66,48 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services public async Task UpdateAsync(BasketData currentBasket) { - _httpClient.BaseAddress = new Uri(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket()); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + + using (var httpClientHandler = new HttpClientHandler()) + { + httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + using (var httpClient = new HttpClient(httpClientHandler)) + { + httpClient.BaseAddress = new Uri(_urls.GrpcBasket); + + _logger.LogDebug("Creating grpc client for basket {@httpClient.BaseAddress} ", httpClient.BaseAddress); + + var client = GrpcClient.Create(httpClient); + + + try + { + + _logger.LogInformation("Grpc update basket currentBasket {@currentBasket}", currentBasket); + var request = MapToCustomerBasketRequest(currentBasket); + _logger.LogInformation("Grpc update basket request {@request}", request); + + await client.UpdateBasketAsync(request); + } + catch (RpcException e) + { + _logger.LogError($"Error calling via grpc: {e.Status} - {e.Message}"); + } + } + } + + + + + //_httpClient.BaseAddress = new Uri(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket()); - var client = GrpcClient.Create(_httpClient); - var request = MapToCustomerBasketRequest(currentBasket); + //var client = GrpcClient.Create(_httpClient); + //_logger.LogInformation("Grpc update basket currentBasket {@currentBasket}", currentBasket); + //var request = MapToCustomerBasketRequest(currentBasket); + //_logger.LogInformation("Grpc update basket request {@request}", request); - await client.UpdateBasketAsync(request); + //await client.UpdateBasketAsync(request); } private BasketData MapToBasketData(CustomerBasketResponse customerBasketRequest) diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs index 663baa1cf..9a1c393b0 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs @@ -11,6 +11,7 @@ using Grpc.Net.Client; using System; using static CatalogApi.Catalog; using System.Linq; +using Grpc.Core; namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services { @@ -40,16 +41,36 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services public async Task> GetCatalogItemsAsync(IEnumerable ids) { - _httpClient.BaseAddress = new Uri(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemsById(ids)); - var client = GrpcClient.Create(_httpClient); - var request = new CatalogItemsRequest { Ids = string.Join(",", ids), PageIndex = 1, PageSize = 10 }; - var response = await client.GetItemsByIdsAsync(request); - return response.Data.Select(this.MapToCatalogItemResponse); - //var stringContent = await _httpClient.GetStringAsync(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemsById(ids)); - //var catalogItems = JsonConvert.DeserializeObject(stringContent); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + + using (var httpClientHandler = new HttpClientHandler()) + { + httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + using (var httpClient = new HttpClient(httpClientHandler)) + { + httpClient.BaseAddress = new Uri(_urls.GrpcCatalog); + + _logger.LogInformation("Creating grpc client for CatalogClient {@httpClient.BaseAddress}, {@httpClient} ", httpClient.BaseAddress, httpClient); + + try + { + var client = GrpcClient.Create(httpClient); + var request = new CatalogItemsRequest { Ids = string.Join(",", ids), PageIndex = 1, PageSize = 10 }; + _logger.LogInformation("grpc client created, request = {@request}", request); + var response = await client.GetItemsByIdsAsync(request); + _logger.LogInformation("grpc response {@response}", response); + return response.Data.Select(this.MapToCatalogItemResponse); + } + catch (RpcException e) + { + _logger.LogError($"Error calling via grpc: {e.Status} - {e.Message}"); + } + } + } - //return catalogItems; + return null; } private CatalogItem MapToCatalogItemResponse(CatalogItemResponse catalogItemResponse) diff --git a/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs b/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs index b25d3b103..9c620a481 100644 --- a/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs +++ b/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs @@ -64,10 +64,12 @@ namespace Catalog.API.Grpc public override async Task GetItemsByIds(CatalogItemsRequest request, ServerCallContext context) { + _logger.LogInformation("---------- GetItemsByIds request {@request}", request); if (!string.IsNullOrEmpty(request.Ids)) { var items = await GetItemsByIdsAsync(request.Ids); + _logger.LogInformation("---------- GetItemsByIds items {@items}", items); if (!items.Any()) { context.Status = new Status(StatusCode.NotFound, $"ids value invalid. Must be comma-separated list of numbers"); @@ -76,15 +78,18 @@ namespace Catalog.API.Grpc return this.MapToResponse(items); } + _logger.LogInformation("---------- GetItemsByIds else"); var totalItems = await _catalogContext.CatalogItems .LongCountAsync(); + _logger.LogInformation("---------- GetItemsByIds totalItems {@totalItems}", totalItems); var itemsOnPage = await _catalogContext.CatalogItems .OrderBy(c => c.Name) .Skip(request.PageSize * request.PageIndex) .Take(request.PageSize) .ToListAsync(); + _logger.LogInformation("---------- GetItemsByIds itemsOnPage {@itemsOnPage}", itemsOnPage); /* The "awesome" fix for testing Devspaces */ /* @@ -95,8 +100,10 @@ namespace Catalog.API.Grpc */ itemsOnPage = ChangeUriPlaceholder(itemsOnPage); + _logger.LogInformation("---------- GetItemsByIds itemsOnPage2 {@itemsOnPage}", itemsOnPage); var model = this.MapToResponse(itemsOnPage, totalItems, request.PageIndex, request.PageSize); + _logger.LogInformation("---------- GetItemsByIds model {@model}", model); context.Status = new Status(StatusCode.OK, string.Empty); return model; @@ -116,29 +123,39 @@ namespace Catalog.API.Grpc PageSize = pageSize, }; - items.ForEach(i => result.Data.Add(new CatalogItemResponse() + items.ForEach(i => { - AvailableStock = i.AvailableStock, - Description = i.Description, - Id = i.Id, - MaxStockThreshold = i.MaxStockThreshold, - Name = i.Name, - OnReorder = i.OnReorder, - PictureFileName = i.PictureFileName, - PictureUri = i.PictureUri, - RestockThreshold = i.RestockThreshold, - CatalogBrand = new CatalogApi.CatalogBrand() + var brand = i.CatalogBrand == null + ? null + : new CatalogApi.CatalogBrand() + { + Id = i.CatalogBrand.Id, + Name = i.CatalogBrand.Brand, + }; + var catalogType = i.CatalogType == null + ? null + : new CatalogApi.CatalogType() + { + Id = i.CatalogType.Id, + Type = i.CatalogType.Type, + }; + + result.Data.Add(new CatalogItemResponse() { - Id = i.CatalogBrand.Id, - Name = i.CatalogBrand.Brand, - }, - CatalogType = new CatalogApi.CatalogType() - { - Id = i.CatalogType.Id, - Type = i.CatalogType.Type, - }, - Price = (double)i.Price, - })); + AvailableStock = i.AvailableStock, + Description = i.Description, + Id = i.Id, + MaxStockThreshold = i.MaxStockThreshold, + Name = i.Name, + OnReorder = i.OnReorder, + PictureFileName = i.PictureFileName, + PictureUri = i.PictureUri, + RestockThreshold = i.RestockThreshold, + CatalogBrand = brand, + CatalogType = catalogType, + Price = (double)i.Price, + }); + }); return result; } diff --git a/src/Services/Catalog/Catalog.API/Proto/catalog.proto b/src/Services/Catalog/Catalog.API/Proto/catalog.proto index adeeb4b26..fa83d45c4 100644 --- a/src/Services/Catalog/Catalog.API/Proto/catalog.proto +++ b/src/Services/Catalog/Catalog.API/Proto/catalog.proto @@ -56,11 +56,5 @@ service Catalog { }; << */ } - rpc GetItemsByIds (CatalogItemsRequest) returns (PaginatedItemsResponse) { - /* >> - option (google.api.http) = { - get: "/api/v1/catalog/items/ids/{ids}" - }; - << */ - } + rpc GetItemsByIds (CatalogItemsRequest) returns (PaginatedItemsResponse) {} } \ No newline at end of file From 260bfcbc4596a8ffc2668588882f6e287c085d53 Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 28 Aug 2019 11:30:14 +0200 Subject: [PATCH 070/113] web bff endpoint /api/v1/Basket working in grpc --- .../aggregator/Services/BasketService.cs | 60 +++++++++---------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs index 2bfc30ce9..4389c4383 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs @@ -96,18 +96,6 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services } } } - - - - - //_httpClient.BaseAddress = new Uri(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket()); - - //var client = GrpcClient.Create(_httpClient); - //_logger.LogInformation("Grpc update basket currentBasket {@currentBasket}", currentBasket); - //var request = MapToCustomerBasketRequest(currentBasket); - //_logger.LogInformation("Grpc update basket request {@request}", request); - - //await client.UpdateBasketAsync(request); } private BasketData MapToBasketData(CustomerBasketResponse customerBasketRequest) @@ -122,16 +110,22 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services BuyerId = customerBasketRequest.Buyerid }; - customerBasketRequest.Items.ToList().ForEach(item => map.Items.Add(new BasketDataItem + customerBasketRequest.Items.ToList().ForEach(item => { - Id = item.Id, - OldUnitPrice = (decimal)item.Oldunitprice, - PictureUrl = item.Pictureurl, - ProductId = item.Productid, - ProductName = item.Productname, - Quantity = item.Quantity, - UnitPrice = (decimal)item.Unitprice - })); + if (item.Id != null) + { + map.Items.Add(new BasketDataItem + { + Id = item.Id, + OldUnitPrice = (decimal)item.Oldunitprice, + PictureUrl = item.Pictureurl, + ProductId = item.Productid, + ProductName = item.Productname, + Quantity = item.Quantity, + UnitPrice = (decimal)item.Unitprice + }); + } + }); return map; } @@ -148,16 +142,22 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services Buyerid = basketData.BuyerId }; - basketData.Items.ToList().ForEach(item => map.Items.Add(new BasketItemResponse + basketData.Items.ToList().ForEach(item => { - Id = item.Id, - Oldunitprice = (double)item.OldUnitPrice, - Pictureurl = item.PictureUrl, - Productid = item.ProductId, - Productname = item.ProductName, - Quantity = item.Quantity, - Unitprice = (double)item.UnitPrice - })); + if (item.Id != null) + { + map.Items.Add(new BasketItemResponse + { + Id = item.Id, + Oldunitprice = (double)item.OldUnitPrice, + Pictureurl = item.PictureUrl, + Productid = item.ProductId, + Productname = item.ProductName, + Quantity = item.Quantity, + Unitprice = (double)item.UnitPrice + }); + } + }); return map; } From 311e1a2bfd8eb14c37da4ed45d3e1fd87343466d Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 28 Aug 2019 12:03:09 +0200 Subject: [PATCH 071/113] refactoring the grpc client --- .../Controllers/BasketController.cs | 2 - .../aggregator/Services/BasketService.cs | 93 ++++++++----------- .../aggregator/Services/GrpcCallerService.cs | 71 ++++++++++++++ .../Web.Bff.Shopping/aggregator/Startup.cs | 4 +- 4 files changed, 114 insertions(+), 56 deletions(-) create mode 100644 src/ApiGateways/Web.Bff.Shopping/aggregator/Services/GrpcCallerService.cs diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs index a3be37611..5905ae214 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs @@ -39,8 +39,6 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers } // Retrieve the current basket - Log.Information("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GetByIdAsync @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); - var basket = await _basket.GetById(data.BuyerId) ?? new BasketData(data.BuyerId); Log.Debug("get basket by id response={@response}", basket); diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs index 4389c4383..5274ddc49 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs @@ -28,74 +28,63 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services public async Task GetById(string id) { - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - - using (var httpClientHandler = new HttpClientHandler()) + return await GrpcCallerService.CallService(_urls.GrpcBasket, async httpClient => { - httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; - using (var httpClient = new HttpClient(httpClientHandler)) - { - //httpClient.BaseAddress = new Uri("http://10.0.75.1:5580"); - httpClient.BaseAddress = new Uri(_urls.GrpcBasket); - - _logger.LogDebug("Creating grpc client for basket {@httpClient.BaseAddress} ", httpClient.BaseAddress); + _logger.LogWarning("######################## grpc client created, request = {@id}", id); - var client = GrpcClient.Create(httpClient); - - _logger.LogDebug("grpc client created, request = {@id}", id); - - try - { + var client = GrpcClient.Create(httpClient); - var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); + _logger.LogDebug("grpc client created, request = {@id}", id); + var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); - _logger.LogDebug("grpc response {@response}", response); + _logger.LogDebug("grpc response {@response}", response); - return MapToBasketData(response); - } - catch (RpcException e) - { - _logger.LogError($"Error calling via grpc: {e.Status} - {e.Message}"); - } - } - } - - return null; + return MapToBasketData(response); + }); } public async Task UpdateAsync(BasketData currentBasket) { - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - - using (var httpClientHandler = new HttpClientHandler()) + await GrpcCallerService.CallService(_urls.GrpcBasket, async httpClient => { - httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; - using (var httpClient = new HttpClient(httpClientHandler)) - { - httpClient.BaseAddress = new Uri(_urls.GrpcBasket); + var client = GrpcClient.Create(httpClient); + _logger.LogDebug("Grpc update basket currentBasket {@currentBasket}", currentBasket); + var request = MapToCustomerBasketRequest(currentBasket); + _logger.LogDebug("Grpc update basket request {@request}", request); - _logger.LogDebug("Creating grpc client for basket {@httpClient.BaseAddress} ", httpClient.BaseAddress); + return client.UpdateBasketAsync(request); + }); - var client = GrpcClient.Create(httpClient); + //AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + //AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + //using (var httpClientHandler = new HttpClientHandler()) + //{ + // httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + // using (var httpClient = new HttpClient(httpClientHandler)) + // { + // httpClient.BaseAddress = new Uri(_urls.GrpcBasket); - try - { + // _logger.LogDebug("Creating grpc client for basket {@httpClient.BaseAddress} ", httpClient.BaseAddress); - _logger.LogInformation("Grpc update basket currentBasket {@currentBasket}", currentBasket); - var request = MapToCustomerBasketRequest(currentBasket); - _logger.LogInformation("Grpc update basket request {@request}", request); + // var client = GrpcClient.Create(httpClient); - await client.UpdateBasketAsync(request); - } - catch (RpcException e) - { - _logger.LogError($"Error calling via grpc: {e.Status} - {e.Message}"); - } - } - } + + // try + // { + + // _logger.LogDebug("Grpc update basket currentBasket {@currentBasket}", currentBasket); + // var request = MapToCustomerBasketRequest(currentBasket); + // _logger.LogDebug("Grpc update basket request {@request}", request); + + // await client.UpdateBasketAsync(request); + // } + // catch (RpcException e) + // { + // _logger.LogError($"Error calling via grpc: {e.Status} - {e.Message}"); + // } + // } + //} } private BasketData MapToBasketData(CustomerBasketResponse customerBasketRequest) diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/GrpcCallerService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/GrpcCallerService.cs new file mode 100644 index 000000000..7e0b61a2f --- /dev/null +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/GrpcCallerService.cs @@ -0,0 +1,71 @@ +using System.Net.Http; +using System.Threading.Tasks; +using System; +using Grpc.Core; +using Serilog; + +namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services +{ + public static class GrpcCallerService + { + public static Task CallService(string urlGrpc, Func> func) + { + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + + using (var httpClientHandler = new HttpClientHandler()) + { + httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + using (var httpClient = new HttpClient(httpClientHandler)) + { + httpClient.BaseAddress = new Uri(urlGrpc); + Log.Debug("Creating grpc client base address {@httpClient.BaseAddress} ", httpClient.BaseAddress); + + try + { + return func(httpClient); + } + catch (RpcException e) + { + Log.Error($"Error calling via grpc: {e.Status} - {e.Message}"); + } + } + } + + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", false); + + return default; + } + + public static Task CallService(string urlGrpc, Func func) + { + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + + using (var httpClientHandler = new HttpClientHandler()) + { + httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + using (var httpClient = new HttpClient(httpClientHandler)) + { + httpClient.BaseAddress = new Uri(urlGrpc); + Log.Debug("Creating grpc client base address {@httpClient.BaseAddress} ", httpClient.BaseAddress); + + try + { + return func(httpClient); + } + catch (RpcException e) + { + Log.Error($"Error calling via grpc: {e.Status} - {e.Message}"); + } + } + } + + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", false); + + return default; + } + } +} diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs index 9613fe462..e16c4197e 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Startup.cs @@ -144,9 +144,9 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator options.SwaggerDoc("v1", new OpenApiInfo { - Title = "Shopping Aggregator for Mobile Clients", + Title = "Shopping Aggregator for Web Clients", Version = "v1", - Description = "Shopping Aggregator for Mobile Clients" + Description = "Shopping Aggregator for Web Clients" }); options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme From 454525d517abf07276260ae29b34a1916014a12a Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 28 Aug 2019 12:34:34 +0200 Subject: [PATCH 072/113] refactored the grpc client --- .../aggregator/Services/BasketService.cs | 45 ++---------- .../aggregator/Services/CatalogService.cs | 39 +++-------- .../aggregator/Services/GrpcCallerService.cs | 70 ++++++++++--------- .../aggregator/Services/OrderingService.cs | 42 +++-------- 4 files changed, 58 insertions(+), 138 deletions(-) diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs index 5274ddc49..3875f3bdb 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs @@ -2,41 +2,35 @@ using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Newtonsoft.Json; -using System.Net.Http; using System.Threading.Tasks; using Grpc.Net.Client; -using System; using System.Linq; using GrpcBasket; -using Grpc.Core; +using System.Net.Http; namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services { public class BasketService : IBasketService { - private readonly HttpClient _httpClient; private readonly UrlsConfig _urls; + public readonly HttpClient _httpClient; private readonly ILogger _logger; public BasketService(HttpClient httpClient, IOptions config, ILogger logger) { - _httpClient = httpClient; _urls = config.Value; + _httpClient = httpClient; _logger = logger; } + public async Task GetById(string id) { return await GrpcCallerService.CallService(_urls.GrpcBasket, async httpClient => { - _logger.LogWarning("######################## grpc client created, request = {@id}", id); - var client = GrpcClient.Create(httpClient); - _logger.LogDebug("grpc client created, request = {@id}", id); var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); - _logger.LogDebug("grpc response {@response}", response); return MapToBasketData(response); @@ -54,37 +48,6 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services return client.UpdateBasketAsync(request); }); - - //AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); - //AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - - //using (var httpClientHandler = new HttpClientHandler()) - //{ - // httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; - // using (var httpClient = new HttpClient(httpClientHandler)) - // { - // httpClient.BaseAddress = new Uri(_urls.GrpcBasket); - - // _logger.LogDebug("Creating grpc client for basket {@httpClient.BaseAddress} ", httpClient.BaseAddress); - - // var client = GrpcClient.Create(httpClient); - - - // try - // { - - // _logger.LogDebug("Grpc update basket currentBasket {@currentBasket}", currentBasket); - // var request = MapToCustomerBasketRequest(currentBasket); - // _logger.LogDebug("Grpc update basket request {@request}", request); - - // await client.UpdateBasketAsync(request); - // } - // catch (RpcException e) - // { - // _logger.LogError($"Error calling via grpc: {e.Status} - {e.Message}"); - // } - // } - //} } private BasketData MapToBasketData(CustomerBasketResponse customerBasketRequest) diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs index 9a1c393b0..5e3e4e2f0 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs @@ -2,7 +2,6 @@ using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Newtonsoft.Json; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; @@ -11,7 +10,6 @@ using Grpc.Net.Client; using System; using static CatalogApi.Catalog; using System.Linq; -using Grpc.Core; namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services { @@ -41,36 +39,15 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services public async Task> GetCatalogItemsAsync(IEnumerable ids) { - - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - - using (var httpClientHandler = new HttpClientHandler()) + return await GrpcCallerService.CallService(_urls.GrpcCatalog, async httpClient => { - httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; - using (var httpClient = new HttpClient(httpClientHandler)) - { - httpClient.BaseAddress = new Uri(_urls.GrpcCatalog); - - _logger.LogInformation("Creating grpc client for CatalogClient {@httpClient.BaseAddress}, {@httpClient} ", httpClient.BaseAddress, httpClient); - - try - { - var client = GrpcClient.Create(httpClient); - var request = new CatalogItemsRequest { Ids = string.Join(",", ids), PageIndex = 1, PageSize = 10 }; - _logger.LogInformation("grpc client created, request = {@request}", request); - var response = await client.GetItemsByIdsAsync(request); - _logger.LogInformation("grpc response {@response}", response); - return response.Data.Select(this.MapToCatalogItemResponse); - } - catch (RpcException e) - { - _logger.LogError($"Error calling via grpc: {e.Status} - {e.Message}"); - } - } - } - - return null; + var client = GrpcClient.Create(httpClient); + var request = new CatalogItemsRequest { Ids = string.Join(",", ids), PageIndex = 1, PageSize = 10 }; + _logger.LogInformation("grpc client created, request = {@request}", request); + var response = await client.GetItemsByIdsAsync(request); + _logger.LogInformation("grpc response {@response}", response); + return response.Data.Select(this.MapToCatalogItemResponse); + }); } private CatalogItem MapToCatalogItemResponse(CatalogItemResponse catalogItemResponse) diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/GrpcCallerService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/GrpcCallerService.cs index 7e0b61a2f..6400c9797 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/GrpcCallerService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/GrpcCallerService.cs @@ -8,28 +8,30 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services { public static class GrpcCallerService { - public static Task CallService(string urlGrpc, Func> func) + public static async Task CallService(string urlGrpc, Func> func) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - using (var httpClientHandler = new HttpClientHandler()) + using var httpClientHandler = new HttpClientHandler { - httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; - using (var httpClient = new HttpClient(httpClientHandler)) - { - httpClient.BaseAddress = new Uri(urlGrpc); - Log.Debug("Creating grpc client base address {@httpClient.BaseAddress} ", httpClient.BaseAddress); + ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; } + }; - try - { - return func(httpClient); - } - catch (RpcException e) - { - Log.Error($"Error calling via grpc: {e.Status} - {e.Message}"); - } - } + using var httpClient = new HttpClient(httpClientHandler) + { + BaseAddress = new Uri(urlGrpc) + }; + + Log.Information("Creating grpc client base address urlGrpc ={@urlGrpc}, BaseAddress={@BaseAddress} ", urlGrpc, httpClient.BaseAddress); + + try + { + return await func(httpClient); + } + catch (RpcException e) + { + Log.Error($"Error calling via grpc: {e.Status} - {e.Message}"); } AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false); @@ -38,34 +40,34 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services return default; } - public static Task CallService(string urlGrpc, Func func) + public static async Task CallService(string urlGrpc, Func func) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - using (var httpClientHandler = new HttpClientHandler()) + using var httpClientHandler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; } + }; + + using var httpClient = new HttpClient(httpClientHandler) { - httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; - using (var httpClient = new HttpClient(httpClientHandler)) - { - httpClient.BaseAddress = new Uri(urlGrpc); - Log.Debug("Creating grpc client base address {@httpClient.BaseAddress} ", httpClient.BaseAddress); + BaseAddress = new Uri(urlGrpc) + }; + + Log.Debug("Creating grpc client base address {@httpClient.BaseAddress} ", httpClient.BaseAddress); - try - { - return func(httpClient); - } - catch (RpcException e) - { - Log.Error($"Error calling via grpc: {e.Status} - {e.Message}"); - } - } + try + { + await func(httpClient); + } + catch (RpcException e) + { + Log.Error($"Error calling via grpc: {e.Status} - {e.Message}"); } AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", false); - - return default; } } } diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs index 1814e2d10..6c2394353 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/OrderingService.cs @@ -14,52 +14,30 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services { public class OrderingService : IOrderingService { - private readonly HttpClient _httpClient; private readonly UrlsConfig _urls; private readonly ILogger _logger; + public readonly HttpClient _httpClient; public OrderingService(HttpClient httpClient, IOptions config, ILogger logger) { - _httpClient = httpClient; _urls = config.Value; + _httpClient = httpClient; _logger = logger; } public async Task GetOrderDraftAsync(BasketData basketData) { - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - - using (var httpClientHandler = new HttpClientHandler()) + return await GrpcCallerService.CallService(_urls.GrpcOrdering, async httpClient => { - httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; - using (var httpClient = new HttpClient(httpClientHandler)) - { - httpClient.BaseAddress = new Uri(_urls.GrpcOrdering); - - _logger.LogDebug(" Creating grpc client for ordering {@httpClient.BaseAddress}", httpClient.BaseAddress); - - var client = GrpcClient.Create(httpClient); + var client = GrpcClient.Create(httpClient); + _logger.LogDebug(" grpc client created, basketData={@basketData}", basketData); - _logger.LogDebug(" grpc client created, basketData={@basketData}", basketData); - - try - { - var command = MapToOrderDraftCommand(basketData); - var response = await client.CreateOrderDraftFromBasketDataAsync(command); - - _logger.LogDebug(" grpc response: {@response}", response); - - return MapToResponse(response, basketData); - } - catch (RpcException e) - { - _logger.LogError($"Error calling via grpc to ordering: {e.Status} - {e.Message}"); - } - } - } + var command = MapToOrderDraftCommand(basketData); + var response = await client.CreateOrderDraftFromBasketDataAsync(command); + _logger.LogDebug(" grpc response: {@response}", response); - return null; + return MapToResponse(response, basketData); + }); } private OrderData MapToResponse(GrpcOrdering.OrderDraftDTO orderDraft, BasketData basketData) From 870363861f526e05433eb4e9bccbac4b1b4882c3 Mon Sep 17 00:00:00 2001 From: eiximenis Date: Wed, 28 Aug 2019 14:11:29 +0200 Subject: [PATCH 073/113] Update Dockerfiles for use /src as build context root --- global.json | 1 - .dockerignore => src/.dockerignore | 0 .../Mobile.Bff.Shopping/aggregator/Dockerfile | 12 +++++------ .../Web.Bff.Shopping/aggregator/Dockerfile | 12 +++++------ NuGet.config => src/NuGet.config | 0 src/Services/Basket/Basket.API/Dockerfile | 16 +++++++-------- .../Basket/Basket.API/Dockerfile.develop | 12 +++++------ src/Services/Catalog/Catalog.API/Dockerfile | 20 +++++++++---------- .../Catalog/Catalog.API/Dockerfile.develop | 16 +++++++-------- src/Services/Identity/Identity.API/Dockerfile | 12 +++++------ .../Identity/Identity.API/Dockerfile.develop | 8 ++++---- .../Location/Locations.API/Dockerfile | 14 ++++++------- .../Location/Locations.API/Dockerfile.develop | 12 +++++------ .../Marketing/Marketing.API/Dockerfile | 14 ++++++------- .../Marketing.API/Dockerfile.develop | 14 ++++++------- src/Services/Ordering/Ordering.API/Dockerfile | 16 +++++++-------- .../Ordering/Ordering.API/Dockerfile.develop | 20 +++++++++---------- src/Services/Payment/Payment.API/Dockerfile | 12 +++++------ .../Payment/Payment.API/Dockerfile.develop | 14 ++++++------- src/Services/Webhooks/Webhooks.API/Dockerfile | 12 +++++------ .../Webhooks/Webhooks.API/Dockerfile.develop | 18 ++++++++--------- src/Web/WebMVC/Dockerfile | 12 +++++------ src/Web/WebMVC/Dockerfile.develop | 8 ++++---- src/Web/WebSPA/Dockerfile | 16 +++++++-------- src/Web/WebStatus/Dockerfile | 12 +++++------ src/Web/WebhookClient/Dockerfile | 12 +++++------ package-lock.json => src/package-lock.json | 0 {scripts => src/scripts}/restore-packages | 0 {scripts => src/scripts}/restore-packages.cmd | 0 29 files changed, 157 insertions(+), 158 deletions(-) delete mode 100644 global.json rename .dockerignore => src/.dockerignore (100%) rename NuGet.config => src/NuGet.config (100%) rename package-lock.json => src/package-lock.json (100%) rename {scripts => src/scripts}/restore-packages (100%) rename {scripts => src/scripts}/restore-packages.cmd (100%) diff --git a/global.json b/global.json deleted file mode 100644 index 9e26dfeeb..000000000 --- a/global.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/.dockerignore b/src/.dockerignore similarity index 100% rename from .dockerignore rename to src/.dockerignore diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile index 3d89c9b27..0572df716 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile @@ -7,14 +7,14 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/ApiGateways/Mobile.Bff.Shopping/aggregator +WORKDIR /src/ApiGateways/Mobile.Bff.Shopping/aggregator RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile b/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile index 2a3b551a2..82c8e88bd 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile @@ -7,14 +7,14 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/ApiGateways/Web.Bff.Shopping/aggregator +WORKDIR /src/ApiGateways/Web.Bff.Shopping/aggregator RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/NuGet.config b/src/NuGet.config similarity index 100% rename from NuGet.config rename to src/NuGet.config diff --git a/src/Services/Basket/Basket.API/Dockerfile b/src/Services/Basket/Basket.API/Dockerfile index c70aa3a96..de09bf101 100644 --- a/src/Services/Basket/Basket.API/Dockerfile +++ b/src/Services/Basket/Basket.API/Dockerfile @@ -7,21 +7,21 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Services/Basket/Basket.API +WORKDIR /src/Services/Basket/Basket.API RUN dotnet publish -c Release -o /app FROM build as unittest -WORKDIR /src/src/Services/Basket/Basket.UnitTests +WORKDIR /src/Services/Basket/Basket.UnitTests FROM build as functionaltest -WORKDIR /src/src/Services/Basket/Basket.FunctionalTests +WORKDIR /src/Services/Basket/Basket.FunctionalTests FROM build AS publish diff --git a/src/Services/Basket/Basket.API/Dockerfile.develop b/src/Services/Basket/Basket.API/Dockerfile.develop index 5ae5cc235..428aa85da 100644 --- a/src/Services/Basket/Basket.API/Dockerfile.develop +++ b/src/Services/Basket/Basket.API/Dockerfile.develop @@ -6,14 +6,14 @@ EXPOSE 80 WORKDIR /src -COPY ["src/BuildingBlocks/EventBus/EventBus/EventBus.csproj", "src/BuildingBlocks/EventBus/EventBus/"] -COPY ["src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "src/BuildingBlocks/EventBus/EventBusRabbitMQ/"] -COPY ["src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "src/BuildingBlocks/EventBus/EventBusServiceBus/"] -COPY ["src/Services/Basket/Basket.API/Basket.API.csproj", "src/Services/Basket/Basket.API/"] +COPY ["BuildingBlocks/EventBus/EventBus/EventBus.csproj", "BuildingBlocks/EventBus/EventBus/"] +COPY ["BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "BuildingBlocks/EventBus/EventBusRabbitMQ/"] +COPY ["BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "BuildingBlocks/EventBus/EventBusServiceBus/"] +COPY ["Services/Basket/Basket.API/Basket.API.csproj", "Services/Basket/Basket.API/"] -RUN dotnet restore src/Services/Basket/Basket.API/Basket.API.csproj -nowarn:msb3202,nu1503 +RUN dotnet restore Services/Basket/Basket.API/Basket.API.csproj -nowarn:msb3202,nu1503 COPY . . -WORKDIR /src/src/Services/Basket/Basket.API +WORKDIR /src/Services/Basket/Basket.API RUN dotnet build --no-restore -c $BUILD_CONFIGURATION ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] \ No newline at end of file diff --git a/src/Services/Catalog/Catalog.API/Dockerfile b/src/Services/Catalog/Catalog.API/Dockerfile index d9f06d64d..1ba73b95c 100644 --- a/src/Services/Catalog/Catalog.API/Dockerfile +++ b/src/Services/Catalog/Catalog.API/Dockerfile @@ -8,27 +8,27 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Services/Catalog/Catalog.API +WORKDIR /src/Services/Catalog/Catalog.API RUN dotnet publish -c Release -o /app FROM build as unittest -WORKDIR /src/src/Services/Catalog/Catalog.UnitTests +WORKDIR /src/Services/Catalog/Catalog.UnitTests FROM build as functionaltest -WORKDIR /src/src/Services/Catalog/Catalog.FunctionalTests +WORKDIR /src/Services/Catalog/Catalog.FunctionalTests FROM build AS publish FROM base AS final WORKDIR /app COPY --from=publish /app . -COPY --from=build /src/src/Services/Catalog/Catalog.API/Proto /app/Proto -COPY --from=build /src/src/Services/Catalog/Catalog.API/eshop.pfx . +COPY --from=build /src/Services/Catalog/Catalog.API/Proto /app/Proto +COPY --from=build /src/Services/Catalog/Catalog.API/eshop.pfx . ENTRYPOINT ["dotnet", "Catalog.API.dll"] diff --git a/src/Services/Catalog/Catalog.API/Dockerfile.develop b/src/Services/Catalog/Catalog.API/Dockerfile.develop index 11034a2bc..c158d2b97 100644 --- a/src/Services/Catalog/Catalog.API/Dockerfile.develop +++ b/src/Services/Catalog/Catalog.API/Dockerfile.develop @@ -6,16 +6,16 @@ EXPOSE 80 WORKDIR /src -COPY ["src/BuildingBlocks/EventBus/EventBus/EventBus.csproj", "src/BuildingBlocks/EventBus/EventBus/"] -COPY ["src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "src/BuildingBlocks/EventBus/EventBusRabbitMQ/"] -COPY ["src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "src/BuildingBlocks/EventBus/EventBusServiceBus/"] -COPY ["src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj", "src/BuildingBlocks/EventBus/IntegrationEventLogEF/"] -COPY ["src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj", "src/BuildingBlocks/WebHostCustomization/WebHost.Customization/"] -COPY ["src/Services/Catalog/Catalog.API/Catalog.API.csproj", "src/Services/Catalog/Catalog.API/"] +COPY ["BuildingBlocks/EventBus/EventBus/EventBus.csproj", "BuildingBlocks/EventBus/EventBus/"] +COPY ["BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "BuildingBlocks/EventBus/EventBusRabbitMQ/"] +COPY ["BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "BuildingBlocks/EventBus/EventBusServiceBus/"] +COPY ["BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj", "BuildingBlocks/EventBus/IntegrationEventLogEF/"] +COPY ["BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj", "BuildingBlocks/WebHostCustomization/WebHost.Customization/"] +COPY ["Services/Catalog/Catalog.API/Catalog.API.csproj", "Services/Catalog/Catalog.API/"] -RUN dotnet restore src/Services/Catalog/Catalog.API/Catalog.API.csproj -nowarn:msb3202,nu1503 +RUN dotnet restore Services/Catalog/Catalog.API/Catalog.API.csproj -nowarn:msb3202,nu1503 COPY . . -WORKDIR "/src/src/Services/Catalog/Catalog.API" +WORKDIR "/src/Services/Catalog/Catalog.API" RUN dotnet build --no-restore -c $BUILD_CONFIGURATION ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] \ No newline at end of file diff --git a/src/Services/Identity/Identity.API/Dockerfile b/src/Services/Identity/Identity.API/Dockerfile index 0096fe7f4..564980f1e 100644 --- a/src/Services/Identity/Identity.API/Dockerfile +++ b/src/Services/Identity/Identity.API/Dockerfile @@ -7,14 +7,14 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Services/Identity/Identity.API +WORKDIR /src/Services/Identity/Identity.API RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/src/Services/Identity/Identity.API/Dockerfile.develop b/src/Services/Identity/Identity.API/Dockerfile.develop index 3ab1fbe7c..e01f161ae 100644 --- a/src/Services/Identity/Identity.API/Dockerfile.develop +++ b/src/Services/Identity/Identity.API/Dockerfile.develop @@ -5,11 +5,11 @@ ENV DOTNET_USE_POLLING_FILE_WATCHER=true EXPOSE 80 WORKDIR /src -COPY ["src/Services/Identity/Identity.API/Identity.API.csproj", "src/Services/Identity/Identity.API/"] -COPY ["src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj", "src/BuildingBlocks/WebHostCustomization/WebHost.Customization/"] -RUN dotnet restore src/Services/Identity/Identity.API/Identity.API.csproj -nowarn:msb3202,nu1503 +COPY ["Services/Identity/Identity.API/Identity.API.csproj", "Services/Identity/Identity.API/"] +COPY ["BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj", "BuildingBlocks/WebHostCustomization/WebHost.Customization/"] +RUN dotnet restore Services/Identity/Identity.API/Identity.API.csproj -nowarn:msb3202,nu1503 COPY . . -WORKDIR "/src/src/Services/Identity/Identity.API" +WORKDIR "/src/Services/Identity/Identity.API" RUN dotnet build --no-restore -c $BUILD_CONFIGURATION ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] diff --git a/src/Services/Location/Locations.API/Dockerfile b/src/Services/Location/Locations.API/Dockerfile index d61b5dbdd..9cf68a0a2 100644 --- a/src/Services/Location/Locations.API/Dockerfile +++ b/src/Services/Location/Locations.API/Dockerfile @@ -7,18 +7,18 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Services/Location/Locations.API +WORKDIR /src/Services/Location/Locations.API RUN dotnet publish -c Release -o /app FROM build as functionaltest -WORKDIR /src/src/Services/Location/Locations.FunctionalTests +WORKDIR /src/Services/Location/Locations.FunctionalTests FROM build AS publish diff --git a/src/Services/Location/Locations.API/Dockerfile.develop b/src/Services/Location/Locations.API/Dockerfile.develop index a847b6c30..2ab8b74af 100644 --- a/src/Services/Location/Locations.API/Dockerfile.develop +++ b/src/Services/Location/Locations.API/Dockerfile.develop @@ -5,13 +5,13 @@ ENV DOTNET_USE_POLLING_FILE_WATCHER=true EXPOSE 80 WORKDIR /src -COPY ["src/Services/Location/Locations.API/Locations.API.csproj", "src/Services/Location/Locations.API/"] -COPY ["src/BuildingBlocks/EventBus/EventBus/EventBus.csproj", "src/BuildingBlocks/EventBus/EventBus/"] -COPY ["src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "src/BuildingBlocks/EventBus/EventBusRabbitMQ/"] -COPY ["src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "src/BuildingBlocks/EventBus/EventBusServiceBus/"] -RUN dotnet restore src/Services/Location/Locations.API/Locations.API.csproj -nowarn:msb3202,nu1503 +COPY ["Services/Location/Locations.API/Locations.API.csproj", "Services/Location/Locations.API/"] +COPY ["BuildingBlocks/EventBus/EventBus/EventBus.csproj", "BuildingBlocks/EventBus/EventBus/"] +COPY ["BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "BuildingBlocks/EventBus/EventBusRabbitMQ/"] +COPY ["BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "BuildingBlocks/EventBus/EventBusServiceBus/"] +RUN dotnet restore Services/Location/Locations.API/Locations.API.csproj -nowarn:msb3202,nu1503 COPY . . -WORKDIR "/src/src/Services/Location/Locations.API" +WORKDIR "/src/Services/Location/Locations.API" RUN dotnet build --no-restore -c $BUILD_CONFIGURATION ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] diff --git a/src/Services/Marketing/Marketing.API/Dockerfile b/src/Services/Marketing/Marketing.API/Dockerfile index 108b63f28..d64e7e396 100644 --- a/src/Services/Marketing/Marketing.API/Dockerfile +++ b/src/Services/Marketing/Marketing.API/Dockerfile @@ -7,18 +7,18 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Services/Marketing/Marketing.API +WORKDIR /src/Services/Marketing/Marketing.API RUN dotnet publish -c Release -o /app FROM build as functionaltest -WORKDIR /src/src/Services/Marketing/Marketing.FunctionalTests +WORKDIR /src/Services/Marketing/Marketing.FunctionalTests FROM build AS publish diff --git a/src/Services/Marketing/Marketing.API/Dockerfile.develop b/src/Services/Marketing/Marketing.API/Dockerfile.develop index 60fc6dd7c..2911c5fb7 100644 --- a/src/Services/Marketing/Marketing.API/Dockerfile.develop +++ b/src/Services/Marketing/Marketing.API/Dockerfile.develop @@ -5,14 +5,14 @@ ENV DOTNET_USE_POLLING_FILE_WATCHER=true EXPOSE 80 WORKDIR /src -COPY ["src/Services/Marketing/Marketing.API/Marketing.API.csproj", "src/Services/Marketing/Marketing.API/"] -COPY ["src/BuildingBlocks/EventBus/EventBus/EventBus.csproj", "src/BuildingBlocks/EventBus/EventBus/"] -COPY ["src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "src/BuildingBlocks/EventBus/EventBusRabbitMQ/"] -COPY ["src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "src/BuildingBlocks/EventBus/EventBusServiceBus/"] -COPY ["src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj", "src/BuildingBlocks/WebHostCustomization/WebHost.Customization/"] -RUN dotnet restore src/Services/Marketing/Marketing.API/Marketing.API.csproj -nowarn:msb3202,nu1503 +COPY [Services/Marketing/Marketing.API/Marketing.API.csproj", "Services/Marketing/Marketing.API/"] +COPY [BuildingBlocks/EventBus/EventBus/EventBus.csproj", "BuildingBlocks/EventBus/EventBus/"] +COPY [BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "BuildingBlocks/EventBus/EventBusRabbitMQ/"] +COPY [BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "BuildingBlocks/EventBus/EventBusServiceBus/"] +COPY [BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj", "BuildingBlocks/WebHostCustomization/WebHost.Customization/"] +RUN dotnet restore Services/Marketing/Marketing.API/Marketing.API.csproj -nowarn:msb3202,nu1503 COPY . . -WORKDIR "/src/src/Services/Marketing/Marketing.API" +WORKDIR "/src/Services/Marketing/Marketing.API" RUN dotnet build --no-restore -c $BUILD_CONFIGURATION ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] diff --git a/src/Services/Ordering/Ordering.API/Dockerfile b/src/Services/Ordering/Ordering.API/Dockerfile index dcb0d3022..3591abd0c 100644 --- a/src/Services/Ordering/Ordering.API/Dockerfile +++ b/src/Services/Ordering/Ordering.API/Dockerfile @@ -7,21 +7,21 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Services/Ordering/Ordering.API +WORKDIR /src/Services/Ordering/Ordering.API RUN dotnet publish -c Release -o /app FROM build as unittest -WORKDIR /src/src/Services/Ordering/Ordering.UnitTests +WORKDIR /src/Services/Ordering/Ordering.UnitTests FROM build as functionaltest -WORKDIR /src/src/Services/Ordering/Ordering.FunctionalTests +WORKDIR /src/Services/Ordering/Ordering.FunctionalTests FROM build AS publish diff --git a/src/Services/Ordering/Ordering.API/Dockerfile.develop b/src/Services/Ordering/Ordering.API/Dockerfile.develop index f91a71bd8..72d98aa72 100644 --- a/src/Services/Ordering/Ordering.API/Dockerfile.develop +++ b/src/Services/Ordering/Ordering.API/Dockerfile.develop @@ -5,18 +5,18 @@ ENV DOTNET_USE_POLLING_FILE_WATCHER=true EXPOSE 80 WORKDIR /src -COPY ["src/BuildingBlocks/EventBus/EventBus/EventBus.csproj", "src/BuildingBlocks/EventBus/EventBus/"] -COPY ["src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "src/BuildingBlocks/EventBus/EventBusRabbitMQ/"] -COPY ["src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "src/BuildingBlocks/EventBus/EventBusServiceBus/"] -COPY ["src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj", "src/BuildingBlocks/EventBus/IntegrationEventLogEF/"] -COPY ["src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj", "src/BuildingBlocks/WebHostCustomization/WebHost.Customization/"] -COPY ["src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj", "src/Services/Ordering/Ordering.Domain/"] -COPY ["src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj", "src/Services/Ordering/Ordering.Infrastructure/"] -COPY ["src/Services/Ordering/Ordering.API/Ordering.API.csproj", "src/Services/Ordering/Ordering.API/"] +COPY ["BuildingBlocks/EventBus/EventBus/EventBus.csproj", "BuildingBlocks/EventBus/EventBus/"] +COPY ["BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "BuildingBlocks/EventBus/EventBusRabbitMQ/"] +COPY ["BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "BuildingBlocks/EventBus/EventBusServiceBus/"] +COPY ["BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj", "BuildingBlocks/EventBus/IntegrationEventLogEF/"] +COPY ["BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj", "BuildingBlocks/WebHostCustomization/WebHost.Customization/"] +COPY ["Services/Ordering/Ordering.Domain/Ordering.Domain.csproj", "Services/Ordering/Ordering.Domain/"] +COPY ["Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj", "Services/Ordering/Ordering.Infrastructure/"] +COPY ["Services/Ordering/Ordering.API/Ordering.API.csproj", "Services/Ordering/Ordering.API/"] -RUN dotnet restore src/Services/Ordering/Ordering.API/Ordering.API.csproj +RUN dotnet restore Services/Ordering/Ordering.API/Ordering.API.csproj COPY . . -WORKDIR /src/src/Services/Ordering/Ordering.API +WORKDIR /src/Services/Ordering/Ordering.API RUN dotnet build --no-restore -c $BUILD_CONFIGURATION ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] \ No newline at end of file diff --git a/src/Services/Payment/Payment.API/Dockerfile b/src/Services/Payment/Payment.API/Dockerfile index 1f2ab41d1..cb4a7eb59 100644 --- a/src/Services/Payment/Payment.API/Dockerfile +++ b/src/Services/Payment/Payment.API/Dockerfile @@ -7,14 +7,14 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Services/Payment/Payment.API +WORKDIR /src/Services/Payment/Payment.API RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/src/Services/Payment/Payment.API/Dockerfile.develop b/src/Services/Payment/Payment.API/Dockerfile.develop index 4b959f4b3..585fbe48f 100644 --- a/src/Services/Payment/Payment.API/Dockerfile.develop +++ b/src/Services/Payment/Payment.API/Dockerfile.develop @@ -5,15 +5,15 @@ ENV DOTNET_USE_POLLING_FILE_WATCHER=true EXPOSE 80 WORKDIR /src -COPY ["src/BuildingBlocks/EventBus/EventBus/EventBus.csproj", "src/BuildingBlocks/EventBus/EventBus/"] -COPY ["src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "src/BuildingBlocks/EventBus/EventBusRabbitMQ/"] -COPY ["src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "src/BuildingBlocks/EventBus/EventBusServiceBus/"] -COPY ["src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj", "src/BuildingBlocks/EventBus/IntegrationEventLogEF/"] -COPY ["src/Services/Payment/Payment.API/Payment.API.csproj", "src/Services/Payment/Payment.API/"] +COPY ["BuildingBlocks/EventBus/EventBus/EventBus.csproj", "BuildingBlocks/EventBus/EventBus/"] +COPY ["BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "BuildingBlocks/EventBus/EventBusRabbitMQ/"] +COPY ["BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "BuildingBlocks/EventBus/EventBusServiceBus/"] +COPY ["BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj", "BuildingBlocks/EventBus/IntegrationEventLogEF/"] +COPY ["Services/Payment/Payment.API/Payment.API.csproj", "Services/Payment/Payment.API/"] -RUN dotnet restore src/Services/Payment/Payment.API/Payment.API.csproj +RUN dotnet restore Services/Payment/Payment.API/Payment.API.csproj COPY . . -WORKDIR /src/src/Services/Payment/Payment.API +WORKDIR /src/Services/Payment/Payment.API RUN dotnet build --no-restore -c $BUILD_CONFIGURATION ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] \ No newline at end of file diff --git a/src/Services/Webhooks/Webhooks.API/Dockerfile b/src/Services/Webhooks/Webhooks.API/Dockerfile index 5d3f6da5a..6c27341f7 100644 --- a/src/Services/Webhooks/Webhooks.API/Dockerfile +++ b/src/Services/Webhooks/Webhooks.API/Dockerfile @@ -7,14 +7,14 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR "/src/src/Services/Webhooks/Webhooks.API" +WORKDIR /src/Services/Webhooks/Webhooks.API RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/src/Services/Webhooks/Webhooks.API/Dockerfile.develop b/src/Services/Webhooks/Webhooks.API/Dockerfile.develop index 3cc1084f9..2c16150e4 100644 --- a/src/Services/Webhooks/Webhooks.API/Dockerfile.develop +++ b/src/Services/Webhooks/Webhooks.API/Dockerfile.develop @@ -6,17 +6,17 @@ EXPOSE 80 WORKDIR /src -COPY ["src/BuildingBlocks/EventBus/EventBus/EventBus.csproj", "src/BuildingBlocks/EventBus/EventBus/"] -COPY ["src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "src/BuildingBlocks/EventBus/EventBusRabbitMQ/"] -COPY ["src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "src/BuildingBlocks/EventBus/EventBusServiceBus/"] -COPY ["src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj", "src/BuildingBlocks/EventBus/IntegrationEventLogEF/"] -COPY ["src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj", "src/BuildingBlocks/WebHostCustomization/WebHost.Customization/"] -COPY ["src/BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj", "src/BuildingBlocks/Devspaces.Support/"] -COPY ["src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj", "src/Services/Webhooks/Webhooks.API/"] +COPY ["BuildingBlocks/EventBus/EventBus/EventBus.csproj", "BuildingBlocks/EventBus/EventBus/"] +COPY ["BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj", "BuildingBlocks/EventBus/EventBusRabbitMQ/"] +COPY ["BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj", "BuildingBlocks/EventBus/EventBusServiceBus/"] +COPY ["BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj", "BuildingBlocks/EventBus/IntegrationEventLogEF/"] +COPY ["BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj", "BuildingBlocks/WebHostCustomization/WebHost.Customization/"] +COPY ["BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj", "BuildingBlocks/Devspaces.Support/"] +COPY ["Services/Webhooks/Webhooks.API/Webhooks.API.csproj", "Services/Webhooks/Webhooks.API/"] -RUN dotnet restore src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj -nowarn:msb3202,nu1503 +RUN dotnet restore Services/Webhooks/Webhooks.API/Webhooks.API.csproj -nowarn:msb3202,nu1503 COPY . . -WORKDIR "/src/src/Services/Webhooks/Webhooks.API" +WORKDIR "/src/Services/Webhooks/Webhooks.API" RUN dotnet build --no-restore -c $BUILD_CONFIGURATION ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] \ No newline at end of file diff --git a/src/Web/WebMVC/Dockerfile b/src/Web/WebMVC/Dockerfile index c32a34295..9dc27258f 100644 --- a/src/Web/WebMVC/Dockerfile +++ b/src/Web/WebMVC/Dockerfile @@ -7,14 +7,14 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Web/WebMVC +WORKDIR /src/Web/WebMVC RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/src/Web/WebMVC/Dockerfile.develop b/src/Web/WebMVC/Dockerfile.develop index 6ff9cc869..172f6bf05 100644 --- a/src/Web/WebMVC/Dockerfile.develop +++ b/src/Web/WebMVC/Dockerfile.develop @@ -5,11 +5,11 @@ ENV DOTNET_USE_POLLING_FILE_WATCHER=true EXPOSE 80 WORKDIR /src -COPY ["src/Web/WebMVC/WebMVC.csproj", "src/Web/WebMVC/"] -COPY ["src/BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj", "src/BuildingBlocks/Devspaces.Support/"] -RUN dotnet restore "src/Web/WebMVC/WebMVC.csproj" +COPY ["Web/WebMVC/WebMVC.csproj", "Web/WebMVC/"] +COPY ["BuildingBlocks/Devspaces.Support/Devspaces.Support.csproj", "BuildingBlocks/Devspaces.Support/"] +RUN dotnet restore "Web/WebMVC/WebMVC.csproj" COPY . . -WORKDIR "/src/src/Web/WebMVC" +WORKDIR "/src/Web/WebMVC" RUN dotnet build --no-restore "WebMVC.csproj" -c $BUILD_CONFIGURATION ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] \ No newline at end of file diff --git a/src/Web/WebSPA/Dockerfile b/src/Web/WebSPA/Dockerfile index 14617aaa7..f32b76e6e 100644 --- a/src/Web/WebSPA/Dockerfile +++ b/src/Web/WebSPA/Dockerfile @@ -5,7 +5,7 @@ EXPOSE 80 FROM ${NODE_IMAGE} as node-build WORKDIR /web -COPY src/Web/WebSPA . +COPY Web/WebSPA . RUN npm install RUN npm run build:prod @@ -14,15 +14,15 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -COPY --from=node-build /web/wwwroot /src/src/Web/WebSPA/wwwroot/ -WORKDIR /src/src/Web/WebSPA +COPY --from=node-build /web/wwwroot /src/Web/WebSPA/wwwroot/ +WORKDIR /src/Web/WebSPA RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/src/Web/WebStatus/Dockerfile b/src/Web/WebStatus/Dockerfile index 35c81d594..95fa8b106 100644 --- a/src/Web/WebStatus/Dockerfile +++ b/src/Web/WebStatus/Dockerfile @@ -7,14 +7,14 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Web/WebStatus +WORKDIR /src/Web/WebStatus RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/src/Web/WebhookClient/Dockerfile b/src/Web/WebhookClient/Dockerfile index b756936f7..d0ed6fb4a 100644 --- a/src/Web/WebhookClient/Dockerfile +++ b/src/Web/WebhookClient/Dockerfile @@ -8,14 +8,14 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Web/WebhookClient +WORKDIR /src/Web/WebhookClient RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/package-lock.json b/src/package-lock.json similarity index 100% rename from package-lock.json rename to src/package-lock.json diff --git a/scripts/restore-packages b/src/scripts/restore-packages similarity index 100% rename from scripts/restore-packages rename to src/scripts/restore-packages diff --git a/scripts/restore-packages.cmd b/src/scripts/restore-packages.cmd similarity index 100% rename from scripts/restore-packages.cmd rename to src/scripts/restore-packages.cmd From 63e20bb07f4edb88766eb503fea45bdfbbd43c77 Mon Sep 17 00:00:00 2001 From: ericuss Date: Wed, 28 Aug 2019 14:12:57 +0200 Subject: [PATCH 074/113] refactor mobile bff --- docker-compose.override.yml | 1 + .../aggregator/Config/UrlsConfig.cs | 1 + .../aggregator/Services/BasketService.cs | 52 ++++--------- .../aggregator/Services/CatalogService.cs | 26 ++++--- .../aggregator/Services/GrpcCallerService.cs | 73 +++++++++++++++++++ .../aggregator/Services/OrderingService.cs | 43 +++-------- .../aggregator/appsettings.json | 5 -- .../aggregator/appsettings.localhost.json | 1 + .../aggregator/Services/CatalogService.cs | 16 ++-- 9 files changed, 125 insertions(+), 93 deletions(-) create mode 100644 src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/GrpcCallerService.cs diff --git a/docker-compose.override.yml b/docker-compose.override.yml index a8fce70ba..8bd11cb91 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -286,6 +286,7 @@ services: - urls__orders=http://ordering.api - urls__identity=http://identity.api - urls__grpcBasket=http://10.0.75.1:5580 + - urls__grpcCatalog=http://10.0.75.1:9101 - urls__grpcOrdering=http://10.0.75.1:5581 - CatalogUrlHC=http://catalog.api/hc - OrderingUrlHC=http://ordering.api/hc diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Config/UrlsConfig.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Config/UrlsConfig.cs index 7fd7cb5f3..c0bb9502e 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Config/UrlsConfig.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Config/UrlsConfig.cs @@ -28,6 +28,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config public string Catalog { get; set; } public string Orders { get; set; } public string GrpcBasket { get; set; } + public string GrpcCatalog { get; set; } public string GrpcOrdering { get; set; } } } diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs index fa1fc9ffe..80846ca3d 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/BasketService.cs @@ -27,50 +27,28 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services public async Task GetById(string id) { - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - - using (var httpClientHandler = new HttpClientHandler()) + return await GrpcCallerService.CallService(_urls.GrpcBasket, async httpClient => { - httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; - using (var httpClient = new HttpClient(httpClientHandler)) - { - //httpClient.BaseAddress = new Uri("http://10.0.75.1:5580"); - httpClient.BaseAddress = new Uri(_urls.GrpcBasket); - - _logger.LogDebug("Creating grpc client for basket {@httpClient.BaseAddress} ", httpClient.BaseAddress); - - var client = GrpcClient.Create(httpClient); - - _logger.LogDebug("grpc client created, request = {@id}", id); - - try - { - - var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); + var client = GrpcClient.Create(httpClient); + _logger.LogDebug("grpc client created, request = {@id}", id); + var response = await client.GetBasketByIdAsync(new BasketRequest { Id = id }); + _logger.LogDebug("grpc response {@response}", response); - _logger.LogDebug("grpc response {@response}", response); - - return MapToBasketData(response); - } - catch (RpcException e) - { - _logger.LogError($"Error calling via grpc: {e.Status} - {e.Message}"); - } - } - } - - return null; + return MapToBasketData(response); + }); } public async Task UpdateAsync(BasketData currentBasket) { - _httpClient.BaseAddress = new Uri(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket()); - - var client = GrpcClient.Create(_httpClient); - var request = MapToCustomerBasketRequest(currentBasket); + await GrpcCallerService.CallService(_urls.GrpcBasket, async httpClient => + { + var client = GrpcClient.Create(httpClient); + _logger.LogDebug("Grpc update basket currentBasket {@currentBasket}", currentBasket); + var request = MapToCustomerBasketRequest(currentBasket); + _logger.LogDebug("Grpc update basket request {@request}", request); - await client.UpdateBasketAsync(request); + return client.UpdateBasketAsync(request); + }); } private BasketData MapToBasketData(CustomerBasketResponse customerBasketRequest) diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/CatalogService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/CatalogService.cs index fbcc8349b..b03ad9bab 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/CatalogService.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/CatalogService.cs @@ -3,9 +3,8 @@ using Grpc.Net.Client; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models; using Microsoft.Extensions.Options; -using Newtonsoft.Json; -using System; using System.Collections.Generic; +using System.Linq; using System.Net.Http; using System.Threading.Tasks; using static CatalogApi.Catalog; @@ -25,21 +24,26 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services public async Task GetCatalogItemAsync(int id) { - _httpClient.BaseAddress = new Uri(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id)); - var client = GrpcClient.Create(_httpClient); - var request = new CatalogItemRequest { Id = id }; - var response = await client.GetItemByIdAsync(request); - - return MapToCatalogItemResponse(response); + return await GrpcCallerService.CallService(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id), async httpClient => + { + var client = GrpcClient.Create(_httpClient); + var request = new CatalogItemRequest { Id = id }; + var response = await client.GetItemByIdAsync(request); + return MapToCatalogItemResponse(response); + }); } public async Task> GetCatalogItemsAsync(IEnumerable ids) { - var stringContent = await _httpClient.GetStringAsync(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemsById(ids)); - var catalogItems = JsonConvert.DeserializeObject(stringContent); - return catalogItems; + return await GrpcCallerService.CallService(_urls.GrpcCatalog, async httpClient => + { + var client = GrpcClient.Create(httpClient); + var request = new CatalogItemsRequest { Ids = string.Join(",", ids), PageIndex = 1, PageSize = 10 }; + var response = await client.GetItemsByIdsAsync(request); + return response.Data.Select(this.MapToCatalogItemResponse); + }); } private CatalogItem MapToCatalogItemResponse(CatalogItemResponse catalogItemResponse) diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/GrpcCallerService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/GrpcCallerService.cs new file mode 100644 index 000000000..e730be327 --- /dev/null +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/GrpcCallerService.cs @@ -0,0 +1,73 @@ +using System.Net.Http; +using System.Threading.Tasks; +using System; +using Grpc.Core; +using Serilog; + +namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services +{ + public static class GrpcCallerService + { + public static async Task CallService(string urlGrpc, Func> func) + { + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + + using var httpClientHandler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; } + }; + + using var httpClient = new HttpClient(httpClientHandler) + { + BaseAddress = new Uri(urlGrpc) + }; + + Log.Information("Creating grpc client base address urlGrpc ={@urlGrpc}, BaseAddress={@BaseAddress} ", urlGrpc, httpClient.BaseAddress); + + try + { + return await func(httpClient); + } + catch (RpcException e) + { + Log.Error($"Error calling via grpc: {e.Status} - {e.Message}"); + } + + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", false); + + return default; + } + + public static async Task CallService(string urlGrpc, Func func) + { + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); + + using var httpClientHandler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; } + }; + + using var httpClient = new HttpClient(httpClientHandler) + { + BaseAddress = new Uri(urlGrpc) + }; + + Log.Debug("Creating grpc client base address {@httpClient.BaseAddress} ", httpClient.BaseAddress); + + try + { + await func(httpClient); + } + catch (RpcException e) + { + Log.Error($"Error calling via grpc: {e.Status} - {e.Message}"); + } + + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false); + AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", false); + } + } +} diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/OrderingService.cs b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/OrderingService.cs index f1e56c2ef..d42c14344 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/OrderingService.cs +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Services/OrderingService.cs @@ -3,12 +3,10 @@ using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config; using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using GrpcOrdering; -using Grpc.Core; namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services { @@ -27,43 +25,21 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services public async Task GetOrderDraftAsync(BasketData basketData) { - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); - using (var httpClientHandler = new HttpClientHandler()) + return await GrpcCallerService.CallService(_urls.GrpcOrdering, async httpClient => { - httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; - using (var httpClient = new HttpClient(httpClientHandler)) - { - httpClient.BaseAddress = new Uri(_urls.GrpcOrdering); + var client = GrpcClient.Create(httpClient); + _logger.LogDebug(" grpc client created, basketData={@basketData}", basketData); - _logger.LogDebug(" Creating grpc client for ordering {@httpClient.BaseAddress}", httpClient.BaseAddress); + var command = MapToOrderDraftCommand(basketData); + var response = await client.CreateOrderDraftFromBasketDataAsync(command); + _logger.LogDebug(" grpc response: {@response}", response); - var client = GrpcClient.Create(httpClient); - - _logger.LogDebug(" grpc client created, basketData={@basketData}", basketData); - - try - { - - var command = MapToOrderDraftCommand(basketData); - var response = await client.CreateOrderDraftFromBasketDataAsync(command); - - _logger.LogDebug(" grpc response: {@response}", response); - - return MapToResponse(response); - } - catch (RpcException e) - { - _logger.LogError($"Error calling via grpc to ordering: {e.Status} - {e.Message}"); - } - } - } - - return null; + return MapToResponse(response, basketData); + }); } - private OrderData MapToResponse(GrpcOrdering.OrderDraftDTO orderDraft) + private OrderData MapToResponse(GrpcOrdering.OrderDraftDTO orderDraft, BasketData basketData) { if (orderDraft == null) { @@ -72,6 +48,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services var data = new OrderData { + Buyer = basketData.BuyerId, Total = (decimal)orderDraft.Total, }; diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.json b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.json index 95b8bad4c..26bb0ac7a 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.json +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.json @@ -1,9 +1,4 @@ { - "Kestrel": { - "EndpointDefaults": { - "Protocols": "Http2" - } - }, "Logging": { "IncludeScopes": false, "Debug": { diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json index f14ca24b9..86fd1541d 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/appsettings.localhost.json @@ -5,6 +5,7 @@ "orders": "http://localhost:55102", "identity": "http://localhost:55105", "grpcBasket": "http://localhost:5580", + "grpcCatalog": "http://localhost:81", "grpcOrdering": "http://localhost:5581" }, "IdentityUrlExternal": "http://localhost:5105", diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs index 5e3e4e2f0..a03c67db2 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/CatalogService.cs @@ -28,13 +28,15 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services public async Task GetCatalogItemAsync(int id) { - _httpClient.BaseAddress = new Uri(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id)); - - var client = GrpcClient.Create(_httpClient); - var request = new CatalogItemRequest { Id = id }; - var response = await client.GetItemByIdAsync(request); - - return MapToCatalogItemResponse(response); + return await GrpcCallerService.CallService(_urls.GrpcCatalog, async httpClient => + { + var client = GrpcClient.Create(httpClient); + var request = new CatalogItemRequest { Id = id }; + _logger.LogInformation("grpc client created, request = {@request}", request); + var response = await client.GetItemByIdAsync(request); + _logger.LogInformation("grpc response {@response}", response); + return MapToCatalogItemResponse(response); + }); } public async Task> GetCatalogItemsAsync(IEnumerable ids) From f83b873ded1edea8f78bc01e98b4271d49b11e1d Mon Sep 17 00:00:00 2001 From: eiximenis Date: Wed, 28 Aug 2019 14:23:12 +0200 Subject: [PATCH 075/113] Deleted unneeded Dockerfile --- src/ApiGateways/Envoy/Dockerfile | 1 - 1 file changed, 1 deletion(-) delete mode 100644 src/ApiGateways/Envoy/Dockerfile diff --git a/src/ApiGateways/Envoy/Dockerfile b/src/ApiGateways/Envoy/Dockerfile deleted file mode 100644 index 0f714330f..000000000 --- a/src/ApiGateways/Envoy/Dockerfile +++ /dev/null @@ -1 +0,0 @@ -FROM envoyproxy/envoy \ No newline at end of file From 7f88a71cce16f828bc811e534bb1d12ab6bb29d4 Mon Sep 17 00:00:00 2001 From: ericuss Date: Thu, 29 Aug 2019 09:38:03 +0200 Subject: [PATCH 076/113] update dockerfiles --- src/ApiGateways/ApiGw-Base/Dockerfile | 12 ++++++------ .../Ordering/Ordering.BackgroundTasks/Dockerfile | 13 +++++++------ .../Ordering/Ordering.SignalrHub/Dockerfile | 12 ++++++------ 3 files changed, 19 insertions(+), 18 deletions(-) diff --git a/src/ApiGateways/ApiGw-Base/Dockerfile b/src/ApiGateways/ApiGw-Base/Dockerfile index 7a5bb928c..00da7c461 100644 --- a/src/ApiGateways/ApiGw-Base/Dockerfile +++ b/src/ApiGateways/ApiGw-Base/Dockerfile @@ -6,14 +6,14 @@ FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/ApiGateways/ApiGw-Base/ +WORKDIR /src/ApiGateways/ApiGw-Base/ RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile index 820f8d4b1..87a735827 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Dockerfile @@ -7,14 +7,15 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ + COPY . . -WORKDIR /src/src/Services/Ordering/Ordering.BackgroundTasks +WORKDIR /src/Services/Ordering/Ordering.BackgroundTasks RUN dotnet publish -c Release -o /app FROM build AS publish diff --git a/src/Services/Ordering/Ordering.SignalrHub/Dockerfile b/src/Services/Ordering/Ordering.SignalrHub/Dockerfile index 15389786c..3174a4781 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Dockerfile +++ b/src/Services/Ordering/Ordering.SignalrHub/Dockerfile @@ -7,14 +7,14 @@ WORKDIR /src COPY scripts scripts/ -COPY src/ApiGateways/*/*.csproj /src/csproj-files/ -COPY src/ApiGateways/*/*/*.csproj /src/csproj-files/ -COPY src/BuildingBlocks/*/*/*.csproj /src/csproj-files/ -COPY src/Services/*/*/*.csproj /src/csproj-files/ -COPY src/Web/*/*.csproj /src/csproj-files/ +COPY ApiGateways/*/*.csproj csproj-files/ +COPY ApiGateways/*/*/*.csproj csproj-files/ +COPY BuildingBlocks/*/*/*.csproj csproj-files/ +COPY Services/*/*/*.csproj csproj-files/ +COPY Web/*/*.csproj csproj-files/ COPY . . -WORKDIR /src/src/Services/Ordering/Ordering.SignalrHub +WORKDIR /src/Services/Ordering/Ordering.SignalrHub RUN dotnet publish -c Release -o /app FROM build AS publish From 4398b25fc1e4988b93dc5a2848fbb2ab019dbf2f Mon Sep 17 00:00:00 2001 From: ericuss Date: Thu, 29 Aug 2019 13:13:10 +0200 Subject: [PATCH 077/113] Fix mvc calls to grpc --- .../aggregator/Controllers/BasketController.cs | 10 ++++++---- .../aggregator/Services/BasketService.cs | 2 +- .../Basket/Basket.API/Controllers/BasketController.cs | 10 ---------- src/Services/Basket/Basket.API/Model/CustomerBasket.cs | 3 +-- src/Web/WebMVC/Controllers/CartController.cs | 4 ++-- 5 files changed, 10 insertions(+), 19 deletions(-) diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs index 5905ae214..429d6e82d 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Controllers/BasketController.cs @@ -125,12 +125,14 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers var currentBasket = (await _basket.GetById(data.BasketId)) ?? new BasketData(data.BasketId); // Step 3: Search if exist product into basket var product = currentBasket.Items.SingleOrDefault(i => i.ProductId == item.Id.ToString()); - - if(product != null){ + + if (product != null) + { // Step 4: Update quantity for product product.Quantity += data.Quantity; } - else{ + else + { // Step 4: Merge current status with new product currentBasket.Items.Add(new BasketDataItem() { @@ -142,7 +144,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Controllers Id = Guid.NewGuid().ToString() }); } - + // Step 5: Update basket await _basket.UpdateAsync(currentBasket); diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs index 3875f3bdb..8eb8865fe 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Services/BasketService.cs @@ -46,7 +46,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services var request = MapToCustomerBasketRequest(currentBasket); _logger.LogDebug("Grpc update basket request {@request}", request); - return client.UpdateBasketAsync(request); + return await client.UpdateBasketAsync(request); }); } diff --git a/src/Services/Basket/Basket.API/Controllers/BasketController.cs b/src/Services/Basket/Basket.API/Controllers/BasketController.cs index fca033301..59f117a3b 100644 --- a/src/Services/Basket/Basket.API/Controllers/BasketController.cs +++ b/src/Services/Basket/Basket.API/Controllers/BasketController.cs @@ -63,8 +63,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers basketCheckout.RequestId = (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty) ? guid : basketCheckout.RequestId; - _logger.LogInformation("----- CheckoutAsync userId: {userId} ", userId); - var basket = await _repository.GetBasketAsync(userId); if (basket == null) @@ -72,14 +70,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers return BadRequest(); } - _logger.LogInformation("----- CheckoutAsync basket: {@basket} ", basket); - - _logger.LogInformation("----- CheckoutAsync user identity: {User} ", string.Join(':', ((ClaimsIdentity)User.Identity).Claims.Select(c => c.Type + " " + c.Value))); - var userName = User.FindFirst(x => x.Type == ClaimTypes.Name).Value; - _logger.LogInformation("----- CheckoutAsync userName: {@userName} ", userName); - var eventMessage = new UserCheckoutAcceptedIntegrationEvent(userId, userName, basketCheckout.City, basketCheckout.Street, basketCheckout.State, basketCheckout.Country, basketCheckout.ZipCode, basketCheckout.CardNumber, basketCheckout.CardHolderName, basketCheckout.CardExpiration, basketCheckout.CardSecurityNumber, basketCheckout.CardTypeId, basketCheckout.Buyer, basketCheckout.RequestId, basket); @@ -89,8 +81,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers // order creation process try { - _logger.LogInformation("----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", eventMessage.Id, Program.AppName, eventMessage); - _eventBus.Publish(eventMessage); } catch (Exception ex) diff --git a/src/Services/Basket/Basket.API/Model/CustomerBasket.cs b/src/Services/Basket/Basket.API/Model/CustomerBasket.cs index b075f3150..9ae495d4f 100644 --- a/src/Services/Basket/Basket.API/Model/CustomerBasket.cs +++ b/src/Services/Basket/Basket.API/Model/CustomerBasket.cs @@ -6,7 +6,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Model { public string BuyerId { get; set; } - public List Items { get; set; } + public List Items { get; set; } = new List(); public CustomerBasket() { @@ -16,7 +16,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Model public CustomerBasket(string customerId) { BuyerId = customerId; - Items = new List(); } } } diff --git a/src/Web/WebMVC/Controllers/CartController.cs b/src/Web/WebMVC/Controllers/CartController.cs index 6887c8d41..b05009cc7 100644 --- a/src/Web/WebMVC/Controllers/CartController.cs +++ b/src/Web/WebMVC/Controllers/CartController.cs @@ -41,7 +41,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers return View(); } - + [HttpPost] public async Task Index(Dictionary quantities, string action) { @@ -72,7 +72,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers var user = _appUserParser.Parse(HttpContext.User); await _basketSvc.AddItemToBasket(user, productDetails.Id); } - return RedirectToAction("Index", "Catalog"); + return RedirectToAction("Index", "Catalog"); } catch (BrokenCircuitException) { From 10759109aba67d4cead55848ededa1993a753733 Mon Sep 17 00:00:00 2001 From: ericuss Date: Thu, 29 Aug 2019 16:16:24 +0200 Subject: [PATCH 078/113] temporal fix to get the order in local dbset of orders for UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs --- .../Repositories/OrderRepository.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs b/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs index 1047d6c7e..c6d57b17b 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs +++ b/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs @@ -28,7 +28,7 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositor public Order Add(Order order) { return _context.Orders.Add(order).Entity; - + } public async Task GetAsync(int orderId) @@ -37,6 +37,14 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositor .Orders .Include(x => x.Address) .FirstOrDefaultAsync(o => o.Id == orderId); + if (order == null) + { + + order = _context + .Orders + .Local + .FirstOrDefault(o => o.Id == orderId); + } if (order != null) { await _context.Entry(order) From e689cfd65e739070f58654d6240f4ec3346bb496 Mon Sep 17 00:00:00 2001 From: ericuss Date: Thu, 29 Aug 2019 16:17:06 +0200 Subject: [PATCH 079/113] add using --- .../Ordering.Infrastructure/Repositories/OrderRepository.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs b/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs index c6d57b17b..4d4f64d7a 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs +++ b/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs @@ -3,6 +3,7 @@ using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.Order using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork; using Ordering.Domain.Exceptions; using System; +using System.Linq; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories From ffe2884dc4c752ae5e522d2698b88500ce79ae75 Mon Sep 17 00:00:00 2001 From: ericuss Date: Fri, 30 Aug 2019 14:20:26 +0200 Subject: [PATCH 080/113] fix checkout process of mvc app --- .../OrderStartedIntegrationEventHandler.cs | 2 - ...ductPriceChangedIntegrationEventHandler.cs | 4 -- .../Catalog.API/Grpc/CatalogService.cs | 7 ---- .../CatalogIntegrationEventService.cs | 4 -- ...aitingValidationIntegrationEventHandler.cs | 2 - ...tusChangedToPaidIntegrationEventHandler.cs | 2 - .../Services/LocationsService.cs | 3 -- ...rLocationUpdatedIntegrationEventHandler.cs | 2 - .../Behaviors/ValidatorBehavior.cs | 2 - .../Commands/CreateOrderCommandHandler.cs | 2 - ...PaymentMethodVerifiedDomainEventHandler.cs | 1 - ...egateWhenOrderStartedDomainEventHandler.cs | 15 ++++---- ...ePeriodConfirmedIntegrationEventHandler.cs | 2 - ...derPaymentFailedIntegrationEventHandler.cs | 2 - ...rPaymentSuccededIntegrationEventHandler.cs | 2 - ...erStockConfirmedIntegrationEventHandler.cs | 2 - ...derStockRejectedIntegrationEventHandler.cs | 2 - ...CheckoutAcceptedIntegrationEventHandler.cs | 10 +---- .../OrderingIntegrationEventService.cs | 4 -- .../Controllers/OrdersController.cs | 6 +-- .../Ordering.API/Grpc/OrderingService.cs | 2 +- .../Tasks/GracePeriodManagerTask.cs | 2 - .../AggregatesModel/OrderAggregate/Order.cs | 7 ++-- .../OrderEntityTypeConfiguration.cs | 38 +++++++++++++++---- .../OrderItemEntityTypeConfiguration.cs | 25 +++++++++--- .../PaymentMethodEntityTypeConfiguration.cs | 28 +++++++++++--- .../Repositories/OrderRepository.cs | 1 - ...aitingValidationIntegrationEventHandler.cs | 2 - ...angedToCancelledIntegrationEventHandler.cs | 2 - ...tusChangedToPaidIntegrationEventHandler.cs | 2 - ...ChangedToShippedIntegrationEventHandler.cs | 2 - ...ToStockConfirmedIntegrationEventHandler.cs | 2 - ...angedToSubmittedIntegrationEventHandler.cs | 2 - ...ToStockConfirmedIntegrationEventHandler.cs | 4 -- .../WebMVC/Controllers/AccountController.cs | 2 - 35 files changed, 90 insertions(+), 107 deletions(-) diff --git a/src/Services/Basket/Basket.API/IntegrationEvents/EventHandling/OrderStartedIntegrationEventHandler.cs b/src/Services/Basket/Basket.API/IntegrationEvents/EventHandling/OrderStartedIntegrationEventHandler.cs index cb7b6a2d6..4fc2e2ec0 100644 --- a/src/Services/Basket/Basket.API/IntegrationEvents/EventHandling/OrderStartedIntegrationEventHandler.cs +++ b/src/Services/Basket/Basket.API/IntegrationEvents/EventHandling/OrderStartedIntegrationEventHandler.cs @@ -26,8 +26,6 @@ namespace Basket.API.IntegrationEvents.EventHandling { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - await _repository.DeleteBasketAsync(@event.UserId.ToString()); } } diff --git a/src/Services/Basket/Basket.API/IntegrationEvents/EventHandling/ProductPriceChangedIntegrationEventHandler.cs b/src/Services/Basket/Basket.API/IntegrationEvents/EventHandling/ProductPriceChangedIntegrationEventHandler.cs index c27200e6f..d303e0771 100644 --- a/src/Services/Basket/Basket.API/IntegrationEvents/EventHandling/ProductPriceChangedIntegrationEventHandler.cs +++ b/src/Services/Basket/Basket.API/IntegrationEvents/EventHandling/ProductPriceChangedIntegrationEventHandler.cs @@ -26,8 +26,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.IntegrationEvents.Even { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - var userIds = _repository.GetUsers(); foreach (var id in userIds) @@ -46,8 +44,6 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.IntegrationEvents.Even if (itemsToUpdate != null) { - _logger.LogInformation("----- ProductPriceChangedIntegrationEventHandler - Updating items in basket for user: {BuyerId} ({@Items})", basket.BuyerId, itemsToUpdate); - foreach (var item in itemsToUpdate) { if (item.UnitPrice == oldPrice) diff --git a/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs b/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs index 9c620a481..39d7828c2 100644 --- a/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs +++ b/src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs @@ -64,12 +64,10 @@ namespace Catalog.API.Grpc public override async Task GetItemsByIds(CatalogItemsRequest request, ServerCallContext context) { - _logger.LogInformation("---------- GetItemsByIds request {@request}", request); if (!string.IsNullOrEmpty(request.Ids)) { var items = await GetItemsByIdsAsync(request.Ids); - _logger.LogInformation("---------- GetItemsByIds items {@items}", items); if (!items.Any()) { context.Status = new Status(StatusCode.NotFound, $"ids value invalid. Must be comma-separated list of numbers"); @@ -78,18 +76,15 @@ namespace Catalog.API.Grpc return this.MapToResponse(items); } - _logger.LogInformation("---------- GetItemsByIds else"); var totalItems = await _catalogContext.CatalogItems .LongCountAsync(); - _logger.LogInformation("---------- GetItemsByIds totalItems {@totalItems}", totalItems); var itemsOnPage = await _catalogContext.CatalogItems .OrderBy(c => c.Name) .Skip(request.PageSize * request.PageIndex) .Take(request.PageSize) .ToListAsync(); - _logger.LogInformation("---------- GetItemsByIds itemsOnPage {@itemsOnPage}", itemsOnPage); /* The "awesome" fix for testing Devspaces */ /* @@ -100,10 +95,8 @@ namespace Catalog.API.Grpc */ itemsOnPage = ChangeUriPlaceholder(itemsOnPage); - _logger.LogInformation("---------- GetItemsByIds itemsOnPage2 {@itemsOnPage}", itemsOnPage); var model = this.MapToResponse(itemsOnPage, totalItems, request.PageIndex, request.PageSize); - _logger.LogInformation("---------- GetItemsByIds model {@model}", model); context.Status = new Status(StatusCode.OK, string.Empty); return model; diff --git a/src/Services/Catalog/Catalog.API/IntegrationEvents/CatalogIntegrationEventService.cs b/src/Services/Catalog/Catalog.API/IntegrationEvents/CatalogIntegrationEventService.cs index bb3a23d40..e84de7e9e 100644 --- a/src/Services/Catalog/Catalog.API/IntegrationEvents/CatalogIntegrationEventService.cs +++ b/src/Services/Catalog/Catalog.API/IntegrationEvents/CatalogIntegrationEventService.cs @@ -39,8 +39,6 @@ namespace Catalog.API.IntegrationEvents { try { - _logger.LogInformation("----- Publishing integration event: {IntegrationEventId_published} from {AppName} - ({@IntegrationEvent})", evt.Id, Program.AppName, evt); - await _eventLogService.MarkEventAsInProgressAsync(evt.Id); _eventBus.Publish(evt); await _eventLogService.MarkEventAsPublishedAsync(evt.Id); @@ -54,8 +52,6 @@ namespace Catalog.API.IntegrationEvents public async Task SaveEventAndCatalogContextChangesAsync(IntegrationEvent evt) { - _logger.LogInformation("----- CatalogIntegrationEventService - Saving changes and integrationEvent: {IntegrationEventId}", evt.Id); - //Use of an EF Core resiliency strategy when using multiple DbContexts within an explicit BeginTransaction(): //See: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency await ResilientTransaction.New(_catalogContext).ExecuteAsync(async () => diff --git a/src/Services/Catalog/Catalog.API/IntegrationEvents/EventHandling/OrderStatusChangedToAwaitingValidationIntegrationEventHandler.cs b/src/Services/Catalog/Catalog.API/IntegrationEvents/EventHandling/OrderStatusChangedToAwaitingValidationIntegrationEventHandler.cs index 493a271cc..2c9fd337c 100644 --- a/src/Services/Catalog/Catalog.API/IntegrationEvents/EventHandling/OrderStatusChangedToAwaitingValidationIntegrationEventHandler.cs +++ b/src/Services/Catalog/Catalog.API/IntegrationEvents/EventHandling/OrderStatusChangedToAwaitingValidationIntegrationEventHandler.cs @@ -32,8 +32,6 @@ { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - var confirmedOrderStockItems = new List(); foreach (var orderStockItem in @event.OrderStockItems) diff --git a/src/Services/Catalog/Catalog.API/IntegrationEvents/EventHandling/OrderStatusChangedToPaidIntegrationEventHandler.cs b/src/Services/Catalog/Catalog.API/IntegrationEvents/EventHandling/OrderStatusChangedToPaidIntegrationEventHandler.cs index 7d383254f..e7520a651 100644 --- a/src/Services/Catalog/Catalog.API/IntegrationEvents/EventHandling/OrderStatusChangedToPaidIntegrationEventHandler.cs +++ b/src/Services/Catalog/Catalog.API/IntegrationEvents/EventHandling/OrderStatusChangedToPaidIntegrationEventHandler.cs @@ -25,8 +25,6 @@ { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - //we're not blocking stock/inventory foreach (var orderStockItem in @event.OrderStockItems) { diff --git a/src/Services/Location/Locations.API/Infrastructure/Services/LocationsService.cs b/src/Services/Location/Locations.API/Infrastructure/Services/LocationsService.cs index f6b9ed708..dc91d0d50 100644 --- a/src/Services/Location/Locations.API/Infrastructure/Services/LocationsService.cs +++ b/src/Services/Location/Locations.API/Infrastructure/Services/LocationsService.cs @@ -72,9 +72,6 @@ { var newUserLocations = MapUserLocationDetails(newLocations); var @event = new UserLocationUpdatedIntegrationEvent(userId, newUserLocations); - - _logger.LogInformation("----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - _eventBus.Publish(@event); } diff --git a/src/Services/Marketing/Marketing.API/IntegrationEvents/Handlers/UserLocationUpdatedIntegrationEventHandler.cs b/src/Services/Marketing/Marketing.API/IntegrationEvents/Handlers/UserLocationUpdatedIntegrationEventHandler.cs index 3d5e62e45..5b93a17d0 100644 --- a/src/Services/Marketing/Marketing.API/IntegrationEvents/Handlers/UserLocationUpdatedIntegrationEventHandler.cs +++ b/src/Services/Marketing/Marketing.API/IntegrationEvents/Handlers/UserLocationUpdatedIntegrationEventHandler.cs @@ -28,8 +28,6 @@ { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - var userMarketingData = await _marketingDataRepository.GetAsync(@event.UserId); userMarketingData = userMarketingData ?? new MarketingData() { UserId = @event.UserId }; diff --git a/src/Services/Ordering/Ordering.API/Application/Behaviors/ValidatorBehavior.cs b/src/Services/Ordering/Ordering.API/Application/Behaviors/ValidatorBehavior.cs index 6fc12258b..9be24e20f 100644 --- a/src/Services/Ordering/Ordering.API/Application/Behaviors/ValidatorBehavior.cs +++ b/src/Services/Ordering/Ordering.API/Application/Behaviors/ValidatorBehavior.cs @@ -24,8 +24,6 @@ namespace Ordering.API.Application.Behaviors { var typeName = request.GetGenericTypeName(); - _logger.LogInformation("----- Validating command {CommandType}", typeName); - var failures = _validators .Select(v => v.Validate(request)) .SelectMany(result => result.Errors) diff --git a/src/Services/Ordering/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs b/src/Services/Ordering/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs index b2fff253d..1cbd21536 100644 --- a/src/Services/Ordering/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs +++ b/src/Services/Ordering/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs @@ -53,8 +53,6 @@ order.AddOrderItem(item.ProductId, item.ProductName, item.UnitPrice, item.Discount, item.PictureUrl, item.Units); } - _logger.LogInformation("----- Creating Order - Order: {@Order}", order); - _orderRepository.Add(order); return await _orderRepository.UnitOfWork diff --git a/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/BuyerAndPaymentMethodVerified/UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs b/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/BuyerAndPaymentMethodVerified/UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs index 32b927368..4d3a3280c 100644 --- a/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/BuyerAndPaymentMethodVerified/UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs +++ b/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/BuyerAndPaymentMethodVerified/UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs @@ -27,7 +27,6 @@ namespace Ordering.API.Application.DomainEventHandlers.BuyerAndPaymentMethodVeri public async Task Handle(BuyerAndPaymentMethodVerifiedDomainEvent buyerPaymentMethodVerifiedEvent, CancellationToken cancellationToken) { var log = _logger.CreateLogger(); - log.LogInformation("----- Handling BuyerAndPaymentMethodVerifiedDomainEvent - buyerPaymentMethodVerifiedEvent: {@buyerPaymentMethodVerifiedEvent}", buyerPaymentMethodVerifiedEvent); var orderToUpdate = await _orderRepository.GetAsync(buyerPaymentMethodVerifiedEvent.OrderId); orderToUpdate.SetBuyerId(buyerPaymentMethodVerifiedEvent.Buyer.Id); orderToUpdate.SetPaymentId(buyerPaymentMethodVerifiedEvent.Payment.Id); diff --git a/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/OrderStartedEvent/ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler.cs b/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/OrderStartedEvent/ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler.cs index 054c20de5..5b8f19b00 100644 --- a/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/OrderStartedEvent/ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler.cs +++ b/src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/OrderStartedEvent/ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler.cs @@ -12,7 +12,7 @@ using System.Threading.Tasks; namespace Ordering.API.Application.DomainEventHandlers.OrderStartedEvent { - public class ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler + public class ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler : INotificationHandler { private readonly ILoggerFactory _logger; @@ -21,8 +21,8 @@ namespace Ordering.API.Application.DomainEventHandlers.OrderStartedEvent private readonly IOrderingIntegrationEventService _orderingIntegrationEventService; public ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler( - ILoggerFactory logger, - IBuyerRepository buyerRepository, + ILoggerFactory logger, + IBuyerRepository buyerRepository, IIdentityService identityService, IOrderingIntegrationEventService orderingIntegrationEventService) { @@ -33,13 +33,13 @@ namespace Ordering.API.Application.DomainEventHandlers.OrderStartedEvent } public async Task Handle(OrderStartedDomainEvent orderStartedEvent, CancellationToken cancellationToken) - { + { var cardTypeId = (orderStartedEvent.CardTypeId != 0) ? orderStartedEvent.CardTypeId : 1; var buyer = await _buyerRepository.FindAsync(orderStartedEvent.UserId); bool buyerOriginallyExisted = (buyer == null) ? false : true; if (!buyerOriginallyExisted) - { + { buyer = new Buyer(orderStartedEvent.UserId, orderStartedEvent.UserName); } @@ -51,8 +51,8 @@ namespace Ordering.API.Application.DomainEventHandlers.OrderStartedEvent orderStartedEvent.CardExpiration, orderStartedEvent.Order.Id); - var buyerUpdated = buyerOriginallyExisted ? - _buyerRepository.Update(buyer) : + var buyerUpdated = buyerOriginallyExisted ? + _buyerRepository.Update(buyer) : _buyerRepository.Add(buyer); await _buyerRepository.UnitOfWork @@ -60,7 +60,6 @@ namespace Ordering.API.Application.DomainEventHandlers.OrderStartedEvent var orderStatusChangedTosubmittedIntegrationEvent = new OrderStatusChangedToSubmittedIntegrationEvent(orderStartedEvent.Order.Id, orderStartedEvent.Order.OrderStatus.Name, buyer.Name); await _orderingIntegrationEventService.AddAndSaveEventAsync(orderStatusChangedTosubmittedIntegrationEvent); - _logger.CreateLogger() .LogTrace("Buyer {BuyerId} and related payment method were validated or updated for orderId: {OrderId}.", buyerUpdated.Id, orderStartedEvent.Order.Id); diff --git a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/GracePeriodConfirmedIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/GracePeriodConfirmedIntegrationEventHandler.cs index 2e003b322..e3df4d11d 100644 --- a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/GracePeriodConfirmedIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/GracePeriodConfirmedIntegrationEventHandler.cs @@ -37,8 +37,6 @@ namespace Ordering.API.Application.IntegrationEvents.EventHandling { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - var command = new SetAwaitingValidationOrderStatusCommand(@event.OrderId); _logger.LogInformation( diff --git a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderPaymentFailedIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderPaymentFailedIntegrationEventHandler.cs index a123dd891..e54a14fb0 100644 --- a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderPaymentFailedIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderPaymentFailedIntegrationEventHandler.cs @@ -31,8 +31,6 @@ { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - var command = new CancelOrderCommand(@event.OrderId); _logger.LogInformation( diff --git a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderPaymentSuccededIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderPaymentSuccededIntegrationEventHandler.cs index 9cc69e5e8..dc2c6b9cd 100644 --- a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderPaymentSuccededIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderPaymentSuccededIntegrationEventHandler.cs @@ -31,8 +31,6 @@ { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - var command = new SetPaidOrderStatusCommand(@event.OrderId); _logger.LogInformation( diff --git a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderStockConfirmedIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderStockConfirmedIntegrationEventHandler.cs index 6438b01d0..8572a09dd 100644 --- a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderStockConfirmedIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderStockConfirmedIntegrationEventHandler.cs @@ -31,8 +31,6 @@ { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - var command = new SetStockConfirmedOrderStatusCommand(@event.OrderId); _logger.LogInformation( diff --git a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderStockRejectedIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderStockRejectedIntegrationEventHandler.cs index b457211ed..1c6a3edd6 100644 --- a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderStockRejectedIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/OrderStockRejectedIntegrationEventHandler.cs @@ -30,8 +30,6 @@ { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - var orderStockRejectedItems = @event.OrderStockItems .FindAll(c => !c.HasStock) .Select(c => c.ProductId) diff --git a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/UserCheckoutAcceptedIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/UserCheckoutAcceptedIntegrationEventHandler.cs index a1452b23c..f55542b34 100644 --- a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/UserCheckoutAcceptedIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/UserCheckoutAcceptedIntegrationEventHandler.cs @@ -35,11 +35,9 @@ namespace Ordering.API.Application.IntegrationEvents.EventHandling /// /// public async Task Handle(UserCheckoutAcceptedIntegrationEvent @event) - { + { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - var result = false; if (@event.RequestId != Guid.Empty) @@ -62,11 +60,7 @@ namespace Ordering.API.Application.IntegrationEvents.EventHandling result = await _mediator.Send(requestCreateOrder); - if (result) - { - _logger.LogInformation("----- CreateOrderCommand suceeded - RequestId: {RequestId}", @event.RequestId); - } - else + if (!result) { _logger.LogWarning("CreateOrderCommand failed - RequestId: {RequestId}", @event.RequestId); } diff --git a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/OrderingIntegrationEventService.cs b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/OrderingIntegrationEventService.cs index cb7ce5513..776b90927 100644 --- a/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/OrderingIntegrationEventService.cs +++ b/src/Services/Ordering/Ordering.API/Application/IntegrationEvents/OrderingIntegrationEventService.cs @@ -45,8 +45,6 @@ namespace Ordering.API.Application.IntegrationEvents foreach (var logEvt in pendingLogEvents) { - _logger.LogInformation("----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", logEvt.EventId, Program.AppName, logEvt.IntegrationEvent); - try { await _eventLogService.MarkEventAsInProgressAsync(logEvt.EventId); @@ -64,8 +62,6 @@ namespace Ordering.API.Application.IntegrationEvents public async Task AddAndSaveEventAsync(IntegrationEvent evt) { - _logger.LogInformation("----- Enqueuing integration event {IntegrationEventId} to repository ({@IntegrationEvent})", evt.Id, evt); - await _eventLogService.SaveEventAsync(evt, _orderingContext.GetCurrentTransaction()); } } diff --git a/src/Services/Ordering/Ordering.API/Controllers/OrdersController.cs b/src/Services/Ordering/Ordering.API/Controllers/OrdersController.cs index 7a592bfb8..58640412b 100644 --- a/src/Services/Ordering/Ordering.API/Controllers/OrdersController.cs +++ b/src/Services/Ordering/Ordering.API/Controllers/OrdersController.cs @@ -49,7 +49,7 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API.Controllers { var requestCancelOrder = new IdentifiedCommand(command, guid); - _logger.LogInformation( + _logger.LogTrace( "----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})", requestCancelOrder.GetGenericTypeName(), nameof(requestCancelOrder.Command.OrderNumber), @@ -79,7 +79,7 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API.Controllers { var requestShipOrder = new IdentifiedCommand(command, guid); - _logger.LogInformation( + _logger.LogTrace( "----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})", requestShipOrder.GetGenericTypeName(), nameof(requestShipOrder.Command.OrderNumber), @@ -141,7 +141,7 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API.Controllers [HttpPost] public async Task> CreateOrderDraftFromBasketDataAsync([FromBody] CreateOrderDraftCommand createOrderDraftCommand) { - _logger.LogInformation( + _logger.LogTrace( "----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})", createOrderDraftCommand.GetGenericTypeName(), nameof(createOrderDraftCommand.BuyerId), diff --git a/src/Services/Ordering/Ordering.API/Grpc/OrderingService.cs b/src/Services/Ordering/Ordering.API/Grpc/OrderingService.cs index af59420e7..adc210a1a 100644 --- a/src/Services/Ordering/Ordering.API/Grpc/OrderingService.cs +++ b/src/Services/Ordering/Ordering.API/Grpc/OrderingService.cs @@ -27,7 +27,7 @@ namespace GrpcOrdering public override async Task CreateOrderDraftFromBasketData(CreateOrderDraftCommand createOrderDraftCommand, ServerCallContext context) { _logger.LogInformation($"Begin grpc call from method {context.Method} for ordering get order draft {createOrderDraftCommand}"); - _logger.LogInformation( + _logger.LogTrace( "----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})", createOrderDraftCommand.GetGenericTypeName(), nameof(createOrderDraftCommand.BuyerId), diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs b/src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs index 9d4c83c57..f70fdeb06 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Tasks/GracePeriodManagerTask.cs @@ -55,8 +55,6 @@ namespace Ordering.BackgroundTasks.Tasks { var confirmGracePeriodEvent = new GracePeriodConfirmedIntegrationEvent(orderId); - _logger.LogInformation("----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", confirmGracePeriodEvent.Id, _settings.SubscriptionClientName, confirmGracePeriodEvent); - _eventBus.Publish(confirmGracePeriodEvent); } } diff --git a/src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Order.cs b/src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Order.cs index 7da025d3a..b5639ac50 100644 --- a/src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Order.cs +++ b/src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Order.cs @@ -18,7 +18,7 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.O // Address is a Value Object pattern example persisted as EF Core 2.0 owned entity public Address Address { get; private set; } - public int? GetBuyerId => _buyerId; + public int? GetBuyerId { get { return this._buyerId; } } private int? _buyerId; public OrderStatus OrderStatus { get; private set; } @@ -26,7 +26,7 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.O private string _description; - + // Draft orders have this set to true. Currently we don't check anywhere the draft status of an Order, but we could do it if needed private bool _isDraft; @@ -46,7 +46,8 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.O return order; } - protected Order() { + protected Order() + { _orderItems = new List(); _isDraft = false; } diff --git a/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderEntityTypeConfiguration.cs b/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderEntityTypeConfiguration.cs index c4c7fce38..9bfccd64c 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderEntityTypeConfiguration.cs +++ b/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderEntityTypeConfiguration.cs @@ -27,10 +27,31 @@ namespace Ordering.Infrastructure.EntityConfigurations a.WithOwner(); }); - orderConfiguration.Property("OrderDate").IsRequired(); - orderConfiguration.Property("BuyerId").IsRequired(false); - orderConfiguration.Property("OrderStatusId").IsRequired(); - orderConfiguration.Property("PaymentMethodId").IsRequired(false); + orderConfiguration + .Property("_buyerId") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("BuyerId") + .IsRequired(false); + + orderConfiguration + .Property("_orderDate") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("OrderDate") + .IsRequired(); + + orderConfiguration + .Property("_orderStatusId") + // .HasField("_orderStatusId") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("OrderStatusId") + .IsRequired(); + + orderConfiguration + .Property("_paymentMethodId") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("PaymentMethodId") + .IsRequired(false); + orderConfiguration.Property("Description").IsRequired(false); var navigation = orderConfiguration.Metadata.FindNavigation(nameof(Order.OrderItems)); @@ -41,18 +62,21 @@ namespace Ordering.Infrastructure.EntityConfigurations orderConfiguration.HasOne() .WithMany() - .HasForeignKey("PaymentMethodId") + // .HasForeignKey("PaymentMethodId") + .HasForeignKey("_paymentMethodId") .IsRequired(false) .OnDelete(DeleteBehavior.Restrict); orderConfiguration.HasOne() .WithMany() .IsRequired(false) - .HasForeignKey("BuyerId"); + // .HasForeignKey("BuyerId"); + .HasForeignKey("_buyerId"); orderConfiguration.HasOne(o => o.OrderStatus) .WithMany() - .HasForeignKey("OrderStatusId"); + // .HasForeignKey("OrderStatusId"); + .HasForeignKey("_orderStatusId"); } } } diff --git a/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderItemEntityTypeConfiguration.cs b/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderItemEntityTypeConfiguration.cs index ca16eddad..e4100eb0d 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderItemEntityTypeConfiguration.cs +++ b/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/OrderItemEntityTypeConfiguration.cs @@ -22,22 +22,37 @@ namespace Ordering.Infrastructure.EntityConfigurations orderItemConfiguration.Property("OrderId") .IsRequired(); - orderItemConfiguration.Property("Discount") + orderItemConfiguration + .Property("_discount") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("Discount") .IsRequired(); orderItemConfiguration.Property("ProductId") .IsRequired(); - orderItemConfiguration.Property("ProductName") + orderItemConfiguration + .Property("_productName") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("ProductName") .IsRequired(); - orderItemConfiguration.Property("UnitPrice") + orderItemConfiguration + .Property("_unitPrice") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("UnitPrice") .IsRequired(); - orderItemConfiguration.Property("Units") + orderItemConfiguration + .Property("_units") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("Units") .IsRequired(); - orderItemConfiguration.Property("PictureUrl") + orderItemConfiguration + .Property("_pictureUrl") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("PictureUrl") .IsRequired(false); } } diff --git a/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/PaymentMethodEntityTypeConfiguration.cs b/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/PaymentMethodEntityTypeConfiguration.cs index 871c2057e..8343deb3b 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/PaymentMethodEntityTypeConfiguration.cs +++ b/src/Services/Ordering/Ordering.Infrastructure/EntityConfigurations/PaymentMethodEntityTypeConfiguration.cs @@ -23,27 +23,43 @@ namespace Ordering.Infrastructure.EntityConfigurations paymentConfiguration.Property("BuyerId") .IsRequired(); - paymentConfiguration.Property("CardHolderName") + paymentConfiguration + .Property("_cardHolderName") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("CardHolderName") .HasMaxLength(200) .IsRequired(); - paymentConfiguration.Property("Alias") + paymentConfiguration + .Property("_alias") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("Alias") .HasMaxLength(200) .IsRequired(); - paymentConfiguration.Property("CardNumber") + paymentConfiguration + .Property("_cardNumber") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("CardNumber") .HasMaxLength(25) .IsRequired(); - paymentConfiguration.Property("Expiration") + paymentConfiguration + .Property("_expiration") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("Expiration") + .HasMaxLength(25) .IsRequired(); - paymentConfiguration.Property("CardTypeId") + paymentConfiguration + .Property("_cardTypeId") + .UsePropertyAccessMode(PropertyAccessMode.Field) + .HasColumnName("CardTypeId") .IsRequired(); paymentConfiguration.HasOne(p => p.CardType) .WithMany() - .HasForeignKey("CardTypeId"); + .HasForeignKey("_cardTypeId"); } } } diff --git a/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs b/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs index 4d4f64d7a..f2e13577c 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs +++ b/src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs @@ -40,7 +40,6 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositor .FirstOrDefaultAsync(o => o.Id == orderId); if (order == null) { - order = _context .Orders .Local diff --git a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToAwaitingValidationIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToAwaitingValidationIntegrationEventHandler.cs index 0e2665232..7a99d898c 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToAwaitingValidationIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToAwaitingValidationIntegrationEventHandler.cs @@ -27,8 +27,6 @@ namespace Ordering.SignalrHub.IntegrationEvents { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - await _hubContext.Clients .Group(@event.BuyerName) .SendAsync("UpdatedOrderState", new { OrderId = @event.OrderId, Status = @event.OrderStatus }); diff --git a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToCancelledIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToCancelledIntegrationEventHandler.cs index 6257bb237..15d2cce47 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToCancelledIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToCancelledIntegrationEventHandler.cs @@ -28,8 +28,6 @@ namespace Ordering.SignalrHub.IntegrationEvents.EventHandling { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - await _hubContext.Clients .Group(@event.BuyerName) .SendAsync("UpdatedOrderState", new { OrderId = @event.OrderId, Status = @event.OrderStatus }); diff --git a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToPaidIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToPaidIntegrationEventHandler.cs index 836e02d3c..0d70edcbf 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToPaidIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToPaidIntegrationEventHandler.cs @@ -26,8 +26,6 @@ namespace Ordering.SignalrHub.IntegrationEvents.EventHandling { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - await _hubContext.Clients .Group(@event.BuyerName) .SendAsync("UpdatedOrderState", new { OrderId = @event.OrderId, Status = @event.OrderStatus }); diff --git a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToShippedIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToShippedIntegrationEventHandler.cs index 5b08d08b4..782ee1a11 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToShippedIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToShippedIntegrationEventHandler.cs @@ -28,8 +28,6 @@ namespace Ordering.SignalrHub.IntegrationEvents.EventHandling { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - await _hubContext.Clients .Group(@event.BuyerName) .SendAsync("UpdatedOrderState", new { OrderId = @event.OrderId, Status = @event.OrderStatus }); diff --git a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToStockConfirmedIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToStockConfirmedIntegrationEventHandler.cs index 348627716..364c1c307 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToStockConfirmedIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToStockConfirmedIntegrationEventHandler.cs @@ -29,8 +29,6 @@ namespace Ordering.SignalrHub.IntegrationEvents.EventHandling { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - await _hubContext.Clients .Group(@event.BuyerName) .SendAsync("UpdatedOrderState", new { OrderId = @event.OrderId, Status = @event.OrderStatus }); diff --git a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToSubmittedIntegrationEventHandler.cs b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToSubmittedIntegrationEventHandler.cs index 422bc4a7a..30183ef77 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToSubmittedIntegrationEventHandler.cs +++ b/src/Services/Ordering/Ordering.SignalrHub/IntegrationEvents/EventHandling/OrderStatusChangedToSubmittedIntegrationEventHandler.cs @@ -29,8 +29,6 @@ namespace Ordering.SignalrHub.IntegrationEvents.EventHandling { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - await _hubContext.Clients .Group(@event.BuyerName) .SendAsync("UpdatedOrderState", new { OrderId = @event.OrderId, Status = @event.OrderStatus }); diff --git a/src/Services/Payment/Payment.API/IntegrationEvents/EventHandling/OrderStatusChangedToStockConfirmedIntegrationEventHandler.cs b/src/Services/Payment/Payment.API/IntegrationEvents/EventHandling/OrderStatusChangedToStockConfirmedIntegrationEventHandler.cs index bbd4b14de..7570bc117 100644 --- a/src/Services/Payment/Payment.API/IntegrationEvents/EventHandling/OrderStatusChangedToStockConfirmedIntegrationEventHandler.cs +++ b/src/Services/Payment/Payment.API/IntegrationEvents/EventHandling/OrderStatusChangedToStockConfirmedIntegrationEventHandler.cs @@ -31,8 +31,6 @@ { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { - _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); - IntegrationEvent orderPaymentIntegrationEvent; //Business feature comment: @@ -50,8 +48,6 @@ orderPaymentIntegrationEvent = new OrderPaymentFailedIntegrationEvent(@event.OrderId); } - _logger.LogInformation("----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", orderPaymentIntegrationEvent.Id, Program.AppName, orderPaymentIntegrationEvent); - _eventBus.Publish(orderPaymentIntegrationEvent); await Task.CompletedTask; diff --git a/src/Web/WebMVC/Controllers/AccountController.cs b/src/Web/WebMVC/Controllers/AccountController.cs index 8b82498ba..dfd4984c5 100644 --- a/src/Web/WebMVC/Controllers/AccountController.cs +++ b/src/Web/WebMVC/Controllers/AccountController.cs @@ -25,8 +25,6 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers var user = User as ClaimsPrincipal; var token = await HttpContext.GetTokenAsync("access_token"); - _logger.LogInformation("----- User {@User} authenticated into {AppName}", user, Program.AppName); - if (token != null) { ViewData["access_token"] = token; From f8c42c2fbe3d7db132a1857063c350e635e5cd2e Mon Sep 17 00:00:00 2001 From: ericuss Date: Mon, 2 Sep 2019 11:38:51 +0200 Subject: [PATCH 081/113] Migrate packages in preview7 to preview8 --- src/_build/dependencies.props | 36 +++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/_build/dependencies.props b/src/_build/dependencies.props index 16cf2f2b5..dc33e8623 100644 --- a/src/_build/dependencies.props +++ b/src/_build/dependencies.props @@ -23,7 +23,7 @@ 2.23.0 0.1.22-pre2 - 3.0.0-preview7.19362.4 + 3.0.0-preview8.19405.4 1.7.9 2.2.0 2.2.0 @@ -53,42 +53,42 @@ 2.6.1 1.0.2 3.0.0-preview4-19123-01 - 3.0.0-preview7.19365.7 + 3.0.0-preview8.19405.7 3.0.0-preview4-19123-01 3.0.0-preview4-19123-01 3.0.0-alpha1-10670 2.2.0-preview2-35157 3.0.0-alpha1-34847 - 3.0.0-preview7.19365.7 - 3.0.0-preview7.19365.7 + 3.0.0-preview8.19405.7 + 3.0.0-preview8.19405.7 2.2.0 1.0.0 2.2.0 3.0.0-preview4-19123-01 3.0.0-preview6.19307.2 - 3.0.0-preview7.19365.7 - 3.0.0-preview7.19365.7 - 3.0.0-preview7.19365.7 + 3.0.0-preview8.19405.7 + 3.0.0-preview8.19405.7 + 3.0.0-preview8.19405.7 3.0.0-preview4-19123-01 3.0.0-preview4-19123-01 7.5.0 3.0.0 4.5.0 - 4.7.0-preview7.19362.9 - 3.0.0-preview7.19362.6 - 3.0.0-preview7.19362.6 - 3.0.0-preview7.19362.6 - 3.0.0-preview7.19362.6 - 3.0.0-preview7.19362.6 - 3.0.0-preview7.19362.9 - 3.0.0-preview7.19365.7 - 3.0.0-preview7.19362.4 + 4.7.0-preview8.19405.3 + 3.0.0-preview8.19405.11 + 3.0.0-preview8.19405.11 + 3.0.0-preview8.19405.11 + 3.0.0-preview8.19405.11 + 3.0.0-preview8.19405.11 + 3.0.0-preview8.19405.3 + 3.0.0-preview8.19405.7 + 3.0.0-preview8.19405.4 2.2.0 2.2.0 2.2.0 2.2.0 2.2.0 - 3.0.0-preview7.19362.4 + 3.0.0-preview8.19405.4 16.0.1 2.9.0-beta2 2.9.0-beta2 @@ -96,7 +96,7 @@ 2.9.0-beta2 4.10.1 12.0.2 - 3.0.0-preview7.19365.7 + 3.0.0-preview8.19405.7 12.0.1 6.0.1 3.0.0-preview3.4 From 16710627155525e37ad88f90e2766843e5957cf1 Mon Sep 17 00:00:00 2001 From: ericuss Date: Tue, 3 Sep 2019 16:07:05 +0200 Subject: [PATCH 082/113] fix identity server --- .../Identity.API/IWebHostExtensions.cs | 79 +++++++++++++++++++ .../Identity/Identity.API/Identity.API.csproj | 13 ++- 2 files changed, 85 insertions(+), 7 deletions(-) create mode 100644 src/Services/Identity/Identity.API/IWebHostExtensions.cs diff --git a/src/Services/Identity/Identity.API/IWebHostExtensions.cs b/src/Services/Identity/Identity.API/IWebHostExtensions.cs new file mode 100644 index 000000000..aff262b73 --- /dev/null +++ b/src/Services/Identity/Identity.API/IWebHostExtensions.cs @@ -0,0 +1,79 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Polly; +using System; +using System.Data.SqlClient; + +namespace Microsoft.AspNetCore.Hosting +{ + public static class IWebHostExtensions + { + public static bool IsInKubernetes(this IWebHost webHost) + { + var cfg = webHost.Services.GetService(); + var orchestratorType = cfg.GetValue("OrchestratorType"); + return orchestratorType?.ToUpper() == "K8S"; + } + + public static IWebHost MigrateDbContext(this IWebHost webHost, Action seeder) where TContext : DbContext + { + var underK8s = webHost.IsInKubernetes(); + + using (var scope = webHost.Services.CreateScope()) + { + var services = scope.ServiceProvider; + var logger = services.GetRequiredService>(); + var context = services.GetService(); + + try + { + logger.LogInformation("Migrating database associated with context {DbContextName}", typeof(TContext).Name); + + if (underK8s) + { + InvokeSeeder(seeder, context, services); + } + else + { + var retries = 10; + var retry = Policy.Handle() + .WaitAndRetry( + retryCount: retries, + sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), + onRetry: (exception, timeSpan, retry, ctx) => + { + logger.LogWarning(exception, "[{prefix}] Exception {ExceptionType} with message {Message} detected on attempt {retry} of {retries}", nameof(TContext), exception.GetType().Name, exception.Message, retry, retries); + }); + + //if the sql server container is not created on run docker compose this + //migration can't fail for network related exception. The retry options for DbContext only + //apply to transient exceptions + // Note that this is NOT applied when running some orchestrators (let the orchestrator to recreate the failing service) + retry.Execute(() => InvokeSeeder(seeder, context, services)); + } + + logger.LogInformation("Migrated database associated with context {DbContextName}", typeof(TContext).Name); + } + catch (Exception ex) + { + logger.LogError(ex, "An error occurred while migrating the database used on context {DbContextName}", typeof(TContext).Name); + if (underK8s) + { + throw; // Rethrow under k8s because we rely on k8s to re-run the pod + } + } + } + + return webHost; + } + + private static void InvokeSeeder(Action seeder, TContext context, IServiceProvider services) + where TContext : DbContext + { + context.Database.Migrate(); + seeder(context, services); + } + } +} diff --git a/src/Services/Identity/Identity.API/Identity.API.csproj b/src/Services/Identity/Identity.API/Identity.API.csproj index ed9900f5c..068cc8a14 100644 --- a/src/Services/Identity/Identity.API/Identity.API.csproj +++ b/src/Services/Identity/Identity.API/Identity.API.csproj @@ -19,6 +19,8 @@ + + @@ -27,13 +29,14 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -41,8 +44,8 @@ - - + + - - + - + + + + + + - + \ No newline at end of file diff --git a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj index 269a133f2..8d0081e18 100644 --- a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj +++ b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj @@ -16,21 +16,19 @@ - - - - - + + + + + all runtime; build; native; contentfiles; analyzers - + - - diff --git a/src/Services/Basket/Basket.FunctionalTests/BasketScenarios.cs b/src/Services/Basket/Basket.FunctionalTests/BasketScenarios.cs index 09ea14ff3..c5eacfa4e 100644 --- a/src/Services/Basket/Basket.FunctionalTests/BasketScenarios.cs +++ b/src/Services/Basket/Basket.FunctionalTests/BasketScenarios.cs @@ -5,7 +5,6 @@ using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; -using WebMVC.Services.ModelDTOs; using Xunit; namespace Basket.FunctionalTests @@ -74,7 +73,7 @@ namespace Basket.FunctionalTests string BuildCheckout() { - var checkoutBasket = new BasketDTO() + var checkoutBasket = new { City = "city", Street = "street", diff --git a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj index 54d753de9..019d5bdfc 100644 --- a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj +++ b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj @@ -10,17 +10,17 @@ - - - - - - + + + + + + all runtime; build; native; contentfiles; analyzers - - + + diff --git a/src/Services/Catalog/Catalog.API/Catalog.API.csproj b/src/Services/Catalog/Catalog.API/Catalog.API.csproj index 0b32dea4b..3d64e1181 100644 --- a/src/Services/Catalog/Catalog.API/Catalog.API.csproj +++ b/src/Services/Catalog/Catalog.API/Catalog.API.csproj @@ -42,30 +42,30 @@ - - - + + + - - - - - - - - - + + + + + + + + + - - - + + + - - - + + + - + diff --git a/src/Services/Catalog/Catalog.API/Infrastructure/CatalogContextSeed.cs b/src/Services/Catalog/Catalog.API/Infrastructure/CatalogContextSeed.cs index ab88002ce..cd1ea4ab1 100644 --- a/src/Services/Catalog/Catalog.API/Infrastructure/CatalogContextSeed.cs +++ b/src/Services/Catalog/Catalog.API/Infrastructure/CatalogContextSeed.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Options; using Model; using Polly; + using Polly.Retry; using System; using System.Collections.Generic; using System.Data.SqlClient; @@ -369,7 +370,7 @@ } } - private Policy CreatePolicy( ILogger logger, string prefix,int retries = 3) + private AsyncRetryPolicy CreatePolicy( ILogger logger, string prefix,int retries = 3) { return Policy.Handle(). WaitAndRetryAsync( diff --git a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj index 9db9a3c37..22ca35532 100644 --- a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj +++ b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj @@ -33,11 +33,11 @@ - - - - - + + + + + all runtime; build; native; contentfiles; analyzers diff --git a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj index e603d6106..29729d05d 100644 --- a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj +++ b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj @@ -9,15 +9,15 @@ - - - - + + + + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Identity/Identity.API/Identity.API.csproj b/src/Services/Identity/Identity.API/Identity.API.csproj index d18cb4b19..27eda89f5 100644 --- a/src/Services/Identity/Identity.API/Identity.API.csproj +++ b/src/Services/Identity/Identity.API/Identity.API.csproj @@ -16,36 +16,39 @@ - - - - - - - - - - - - + + + + + + + + + + + + - - - - - - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + - - - + + + - - + + - + $(NetCoreTargetVersion) @@ -59,7 +27,6 @@ - diff --git a/src/Web/WebMVC/Controllers/CartController.cs b/src/Web/WebMVC/Controllers/CartController.cs index b05009cc7..78cec5670 100644 --- a/src/Web/WebMVC/Controllers/CartController.cs +++ b/src/Web/WebMVC/Controllers/CartController.cs @@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.WebMVC.Services; using Microsoft.eShopOnContainers.WebMVC.ViewModels; -using Polly.CircuitBreaker; using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -32,10 +31,9 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers return View(vm); } - catch (BrokenCircuitException) + catch (Exception ex) { - // Catch error when Basket.api is in circuit-opened mode - HandleBrokenCircuitException(); + HandleException(ex); } return View(); @@ -54,10 +52,9 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers return RedirectToAction("Create", "Order"); } } - catch (BrokenCircuitException) + catch (Exception ex) { - // Catch error when Basket.api is in circuit-opened mode - HandleBrokenCircuitException(); + HandleException(ex); } return View(); @@ -74,18 +71,18 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers } return RedirectToAction("Index", "Catalog"); } - catch (BrokenCircuitException) + catch (Exception ex) { // Catch error when Basket.api is in circuit-opened mode - HandleBrokenCircuitException(); + HandleException(ex); } return RedirectToAction("Index", "Catalog", new { errorMsg = ViewBag.BasketInoperativeMsg }); } - private void HandleBrokenCircuitException() + private void HandleException(Exception ex) { - ViewBag.BasketInoperativeMsg = "Basket Service is inoperative, please try later on. (Business Msg Due to Circuit-Breaker)"; + ViewBag.BasketInoperativeMsg = $"Basket Service is inoperative {ex.GetType().Name} - {ex.Message}"; } } } diff --git a/src/Web/WebMVC/Controllers/OrderController.cs b/src/Web/WebMVC/Controllers/OrderController.cs index 6249492da..f308d0bdc 100644 --- a/src/Web/WebMVC/Controllers/OrderController.cs +++ b/src/Web/WebMVC/Controllers/OrderController.cs @@ -2,7 +2,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.WebMVC.Services; using Microsoft.eShopOnContainers.WebMVC.ViewModels; -using Polly.CircuitBreaker; +using System; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.WebMVC.Controllers @@ -47,9 +47,9 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers return RedirectToAction("Index"); } } - catch (BrokenCircuitException) + catch (Exception ex) { - ModelState.AddModelError("Error", "It was not possible to create a new order, please try later on. (Business Msg Due to Circuit-Breaker)"); + ModelState.AddModelError("Error", $"It was not possible to create a new order, please try later on ({ex.GetType().Name} - {ex.Message})"); } return View("Create", model); diff --git a/src/Web/WebMVC/Startup.cs b/src/Web/WebMVC/Startup.cs index 7f4abb55f..bfba90662 100644 --- a/src/Web/WebMVC/Startup.cs +++ b/src/Web/WebMVC/Startup.cs @@ -15,8 +15,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Logging; -using Polly; -using Polly.Extensions.Http; using StackExchange.Redis; using System; using System.IdentityModel.Tokens.Jwt; @@ -146,7 +144,7 @@ namespace Microsoft.eShopOnContainers.WebMVC return services; } - // Adds all Http client services (like Service-Agents) using resilient Http requests based on HttpClient factory and Polly's policies + // Adds all Http client services public static IServiceCollection AddHttpClientServices(this IServiceCollection services, IConfiguration configuration) { services.AddSingleton(); @@ -162,32 +160,22 @@ namespace Microsoft.eShopOnContainers.WebMVC services.AddHttpClient() .SetHandlerLifetime(TimeSpan.FromMinutes(5)) //Sample. Default lifetime is 2 minutes .AddHttpMessageHandler() - .AddPolicyHandler(GetRetryPolicy()) - .AddPolicyHandler(GetCircuitBreakerPolicy()) .AddDevspacesSupport(); services.AddHttpClient() - .AddPolicyHandler(GetRetryPolicy()) - .AddPolicyHandler(GetCircuitBreakerPolicy()) .AddDevspacesSupport(); services.AddHttpClient() .AddHttpMessageHandler() .AddHttpMessageHandler() - .AddPolicyHandler(GetRetryPolicy()) - .AddPolicyHandler(GetCircuitBreakerPolicy()) .AddDevspacesSupport(); services.AddHttpClient() .AddHttpMessageHandler() - .AddPolicyHandler(GetRetryPolicy()) - .AddPolicyHandler(GetCircuitBreakerPolicy()) .AddDevspacesSupport(); services.AddHttpClient() .AddHttpMessageHandler() - .AddPolicyHandler(GetRetryPolicy()) - .AddPolicyHandler(GetCircuitBreakerPolicy()) .AddDevspacesSupport(); //add custom application services @@ -235,19 +223,5 @@ namespace Microsoft.eShopOnContainers.WebMVC return services; } - - static IAsyncPolicy GetRetryPolicy() - { - return HttpPolicyExtensions - .HandleTransientHttpError() - .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound) - .WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); - } - static IAsyncPolicy GetCircuitBreakerPolicy() - { - return HttpPolicyExtensions - .HandleTransientHttpError() - .CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)); - } } } diff --git a/src/Web/WebMVC/ViewComponents/Cart.cs b/src/Web/WebMVC/ViewComponents/Cart.cs index 05c7dac50..6cd8bf2d5 100644 --- a/src/Web/WebMVC/ViewComponents/Cart.cs +++ b/src/Web/WebMVC/ViewComponents/Cart.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Polly.CircuitBreaker; namespace Microsoft.eShopOnContainers.WebMVC.ViewComponents { @@ -25,9 +24,8 @@ namespace Microsoft.eShopOnContainers.WebMVC.ViewComponents vm.ItemsCount = itemsInCart; return View(vm); } - catch (BrokenCircuitException) + catch { - // Catch error when Basket.api is in circuit-opened mode ViewBag.IsBasketInoperative = true; } diff --git a/src/Web/WebMVC/ViewComponents/CartList.cs b/src/Web/WebMVC/ViewComponents/CartList.cs index 60fe863d4..88d1f9abb 100644 --- a/src/Web/WebMVC/ViewComponents/CartList.cs +++ b/src/Web/WebMVC/ViewComponents/CartList.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Polly.CircuitBreaker; namespace Microsoft.eShopOnContainers.WebMVC.ViewComponents { @@ -23,10 +22,9 @@ namespace Microsoft.eShopOnContainers.WebMVC.ViewComponents vm = await GetItemsAsync(user); return View(vm); } - catch (BrokenCircuitException) + catch (Exception ex) { - // Catch error when Basket.api is in circuit-opened mode - ViewBag.BasketInoperativeMsg = "Basket Service is inoperative, please try later on. (Business Msg Due to Circuit-Breaker)"; + ViewBag.BasketInoperativeMsg = $"Basket Service is inoperative, please try later on. ({ex.GetType().Name} - {ex.Message}))"; } return View(vm); diff --git a/src/Web/WebMVC/WebMVC.csproj b/src/Web/WebMVC/WebMVC.csproj index f161a9477..f5da398b3 100644 --- a/src/Web/WebMVC/WebMVC.csproj +++ b/src/Web/WebMVC/WebMVC.csproj @@ -31,7 +31,6 @@ - From 0df81ff5d26cae6fb57de77d714388ed96651461 Mon Sep 17 00:00:00 2001 From: eiximenis Date: Tue, 15 Oct 2019 11:23:25 +0200 Subject: [PATCH 107/113] Removing unneeded files. Making compatible FailingMiddleware & Healthchecks --- k8s/basket-data.yaml | 29 - k8s/deployments.yaml | 923 ------------------ k8s/eshop-namespace.yaml | 5 - k8s/ingress.yaml | 59 -- k8s/keystore-data.yaml | 29 - k8s/linkerd/basket-api-sp.yaml | 42 + k8s/linkerd/catalog-api-sp.yaml | 47 + k8s/nosql-data.yaml | 30 - k8s/rabbitmq.yaml | 30 - k8s/services.yaml | 195 ---- k8s/sql-data.yaml | 35 - .../Middlewares/FailingMiddleware.cs | 15 +- .../Middlewares/FailingOptions.cs | 2 + src/Services/Basket/Basket.API/Program.cs | 5 +- 14 files changed, 108 insertions(+), 1338 deletions(-) delete mode 100644 k8s/basket-data.yaml delete mode 100644 k8s/deployments.yaml delete mode 100644 k8s/eshop-namespace.yaml delete mode 100644 k8s/ingress.yaml delete mode 100644 k8s/keystore-data.yaml create mode 100644 k8s/linkerd/basket-api-sp.yaml create mode 100644 k8s/linkerd/catalog-api-sp.yaml delete mode 100644 k8s/nosql-data.yaml delete mode 100644 k8s/rabbitmq.yaml delete mode 100644 k8s/services.yaml delete mode 100644 k8s/sql-data.yaml diff --git a/k8s/basket-data.yaml b/k8s/basket-data.yaml deleted file mode 100644 index b48e73fed..000000000 --- a/k8s/basket-data.yaml +++ /dev/null @@ -1,29 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: basket-data - name: basket-data -spec: - ports: - - port: 6379 - selector: - app: eshop - component: basket-data ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: basket-data -spec: - template: - metadata: - labels: - app: eshop - component: basket-data - spec: - containers: - - name: basket-data - image: redis - diff --git a/k8s/deployments.yaml b/k8s/deployments.yaml deleted file mode 100644 index ca97df9eb..000000000 --- a/k8s/deployments.yaml +++ /dev/null @@ -1,923 +0,0 @@ -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: basket -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: basket - spec: - containers: - - name: basket - image: eshop/basket.api - imagePullPolicy: Always - env: - - name: PATH_BASE - value: /basket-api - - name: ConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: basket__ConnectionString - - name: EventBusConnection - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EventBusConnection - - name: AzureServiceBusEnabled - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__UseAzureServiceBus - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: IdentityUrl - valueFrom: - configMapKeyRef: - name: urls - key: identity_e - - name: UseLoadTest - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EnableLoadTest - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: catalog -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: catalog - spec: - containers: - - name: catalog - image: eshop/catalog.api - imagePullPolicy: Always - env: - - name: PATH_BASE - value: /catalog-api - - name: ConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: catalog__ConnectionString - - name: PicBaseUrl - valueFrom: - configMapKeyRef: - name: urls - key: PicBaseUrl - - name: AzureStorageEnabled - valueFrom: - configMapKeyRef: - name: externalcfg - key: catalog__AzureStorageEnabled - - name: EventBusConnection - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EventBusConnection - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: identity -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: identity - spec: - containers: - - name: identity - image: eshop/identity.api - imagePullPolicy: Always - env: - - name: PATH_BASE - value: /identity - - name: ConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: identity__ConnectionString - - name: DPConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: keystore - - name: IsClusterEnv - value: 'True' - - name: MvcClient - valueFrom: - configMapKeyRef: - name: urls - key: mvc_e - - name: SpaClient - valueFrom: - configMapKeyRef: - name: urls - key: spa_e - - name: LocationApiClient - valueFrom: - configMapKeyRef: - name: urls - key: locations_e - - name: MarketingApiClient - valueFrom: - configMapKeyRef: - name: urls - key: marketing_e - - name: BasketApiClient - valueFrom: - configMapKeyRef: - name: urls - key: basket_e - - name: OrderingApiClient - valueFrom: - configMapKeyRef: - name: urls - key: ordering_e - - name: MobileShoppingAggClient - valueFrom: - configMapKeyRef: - name: urls - key: mobileshoppingagg_e - - name: WebShoppingAggClient - valueFrom: - configMapKeyRef: - name: urls - key: webshoppingagg_e - - name: XamarinCallback - valueFrom: - configMapKeyRef: - name: urls - key: xamarin_callback_e - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: ordering -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: ordering - spec: - containers: - - name: ordering - image: eshop/ordering.api - imagePullPolicy: Always - env: - - name: PATH_BASE - value: /ordering-api - - name: ConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: ordering__ConnectionString - - name: EventBusConnection - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EventBusConnection - - name: AzureServiceBusEnabled - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__UseAzureServiceBus - - name: IdentityUrl - valueFrom: - configMapKeyRef: - name: urls - key: identity_e - - name: CheckUpdateTime - valueFrom: - configMapKeyRef: - name: externalcfg - key: GracePeriodManager__CheckUpdateTime - - name: GracePeriodTime - valueFrom: - configMapKeyRef: - name: externalcfg - key: GracePeriodManager__GracePeriodTime - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: UseLoadTest - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EnableLoadTest - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: ordering-backgroundtasks -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: ordering-backgroundtasks - spec: - containers: - - name: ordering-backgroundtasks - image: eshop/ordering.backgroundtasks - imagePullPolicy: Always - env: - - name: ConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: ordering__ConnectionString - - name: EventBusConnection - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EventBusConnection - - name: AzureServiceBusEnabled - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__UseAzureServiceBus - - name: CheckUpdateTime - valueFrom: - configMapKeyRef: - name: externalcfg - key: GracePeriodManager__CheckUpdateTime - - name: GracePeriodTime - valueFrom: - configMapKeyRef: - name: externalcfg - key: GracePeriodManager__GracePeriodTime - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: UseLoadTest - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EnableLoadTest - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: ordering-signalrhub -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: ordering-signalrhub - spec: - containers: - - name: ordering-signalrhub - image: eshop/ordering.signalrhub - imagePullPolicy: Always - env: - - name: EventBusConnection - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EventBusConnection - - name: IdentityUrl - valueFrom: - configMapKeyRef: - name: urls - key: identity_e - - name: AzureServiceBusEnabled - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__UseAzureServiceBus - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: OrchestratorType - value: 'K8S' - - name: IsClusterEnv - value: 'True' - - name: SignalrStoreConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: keystore - ports: - - containerPort: 80 - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: locations -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: locations - spec: - containers: - - name: locations - image: eshop/locations.api - imagePullPolicy: Always - env: - - name: PATH_BASE - value: /locations-api - - name: ConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: locations__ConnectionString - - name: Database - valueFrom: - configMapKeyRef: - name: externalcfg - key: locations__Database - - name: AzureServiceBusEnabled - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__UseAzureServiceBus - - name: EventBusConnection - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EventBusConnection - - name: IdentityUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: identity - - name: IdentityUrlExternal - valueFrom: - configMapKeyRef: - name: urls - key: identity_e - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: UseLoadTest - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EnableLoadTest - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: marketing -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: marketing - spec: - containers: - - name: marketing - image: eshop/marketing.api - imagePullPolicy: Always - env: - - name: PATH_BASE - value: /marketing-api - - name: ConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: marketing__ConnectionString - - name: MongoConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: marketing__MongoConnectionString - - name: MongoDatabase - valueFrom: - configMapKeyRef: - name: externalcfg - key: marketing__MongoDatabase - - name: AzureServiceBusEnabled - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__UseAzureServiceBus - - name: EventBusConnection - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EventBusConnection - - name: IdentityUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: identity - - name: IdentityUrlExternal - valueFrom: - configMapKeyRef: - name: urls - key: identity_e - - name: PicBaseUrl - valueFrom: - configMapKeyRef: - name: urls - key: Marketing_PicBaseUrl - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: UseLoadTest - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EnableLoadTest - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: payment -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: payment - spec: - containers: - - name: payment - image: eshop/payment.api - imagePullPolicy: Always - env: - - name: PATH_BASE - value: /payment-api - - name: AzureServiceBusEnabled - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__UseAzureServiceBus - - name: EventBusConnection - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EventBusConnection - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: webmvc -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: webmvc - spec: - containers: - - name: webmvc - image: eshop/webmvc - imagePullPolicy: Always - env: - - name: PATH_BASE - value: /webmvc - - name: DPConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: keystore - - name: IsClusterEnv - value: 'True' - - name: PurchaseUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: apigwws - - name: ExternalPurchaseUrl - valueFrom: - configMapKeyRef: - name: urls - key: webshoppingapigw_e - - name: CallBackUrl - valueFrom: - configMapKeyRef: - name: urls - key: mvc_e - - name: IdentityUrl - valueFrom: - configMapKeyRef: - name: urls - key: identity_e - - name: MarketingUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: apigwwm - - name: BasketUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: basket__hc - - name: CatalogUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: catalog__hc - - name: IdentityUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: identity__hc - - name: OrderingUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: ordering__hc - - name: MarketingUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: marketing__hc - - name: PaymentUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: payment__hc - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: UseLoadTest - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__EnableLoadTest - - name: OrchestratorType - value: 'K8S' - - name: SignalrHubUrl - valueFrom: - configMapKeyRef: - name: urls - key: webshoppingapigw_e - ports: - - containerPort: 80 - - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: webstatus -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: webstatus - spec: - containers: - - name: webstatus - image: eshop/webstatus - imagePullPolicy: Always - env: - - name: PATH_BASE - value: /webstatus - - name: BasketUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: basket__hc - - name: CatalogUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: catalog__hc - - name: IdentityUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: identity__hc - - name: OrderingUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: ordering__hc - - name: LocationsUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: locations__hc - - name: MarketingUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: marketing__hc - - name: mvc - valueFrom: - configMapKeyRef: - name: internalurls - key: mvc__hc - - name: spa - valueFrom: - configMapKeyRef: - name: internalurls - key: spa__hc - - name: PaymentUrl - valueFrom: - configMapKeyRef: - name: internalurls - key: payment__hc - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: OrchestratorType - value: 'K8S' - ports: - - containerPort: 80 - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: webspa -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: webspa - spec: - containers: - - name: webspa - image: eshop/webspa - imagePullPolicy: Always - env: - - name: ASPNETCORE_URLS - value: http://0.0.0.0:80 - - name: DPConnectionString - valueFrom: - configMapKeyRef: - name: externalcfg - key: keystore - - name: IsClusterEnv - value: 'True' - - name: PurchaseUrl - valueFrom: - configMapKeyRef: - name: urls - key: webshoppingapigw_e - - name: CallBackUrl - valueFrom: - configMapKeyRef: - name: urls - key: spa_e - - name: IdentityUrl - valueFrom: - configMapKeyRef: - name: urls - key: identity_e - - name: MarketingUrl - valueFrom: - configMapKeyRef: - name: urls - key: marketingapigw_e - - name: BasketUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: basket__hc - - name: CatalogUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: catalog__hc - - name: IdentityUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: identity__hc - - name: OrderingUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: ordering__hc - - name: MarketingUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: marketing__hc - - name: PaymentUrlHC - valueFrom: - configMapKeyRef: - name: internalurls - key: payment__hc - - name: ApplicationInsights__InstrumentationKey - valueFrom: - configMapKeyRef: - name: externalcfg - key: all__InstrumentationKey - - name: OrchestratorType - value: 'K8S' - - name: SignalrHubUrl - valueFrom: - configMapKeyRef: - name: urls - key: webshoppingapigw_e - ports: - - containerPort: 80 - - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: webshoppingagg -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: webshoppingagg - spec: - containers: - - name: webshoppingagg - image: eshop/webshoppingagg - imagePullPolicy: Always - env: - - name: ASPNETCORE_URLS - value: http://0.0.0.0:80 - - name: urls__basket - valueFrom: - configMapKeyRef: - name: internalurls - key: basket - - name: urls__catalog - valueFrom: - configMapKeyRef: - name: internalurls - key: catalog - - name: urls__orders - valueFrom: - configMapKeyRef: - name: internalurls - key: ordering - - name: urls__identity - valueFrom: - configMapKeyRef: - name: internalurls - key: identity - ports: - - containerPort: 80 - imagePullSecrets: - - name: registry-key ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: mobileshoppingagg -spec: - paused: true - template: - metadata: - labels: - app: eshop - component: mobileshoppingagg - spec: - containers: - - name: mobileshoppingagg - image: eshop/mobileshoppingagg - imagePullPolicy: Always - env: - - name: ASPNETCORE_URLS - value: http://0.0.0.0:80 - - name: urls__basket - valueFrom: - configMapKeyRef: - name: internalurls - key: basket - - name: urls__catalog - valueFrom: - configMapKeyRef: - name: internalurls - key: catalog - - name: urls__orders - valueFrom: - configMapKeyRef: - name: internalurls - key: ordering - - name: urls__identity - valueFrom: - configMapKeyRef: - name: internalurls - key: identity - ports: - - containerPort: 80 - imagePullSecrets: - - name: registry-key ---- diff --git a/k8s/eshop-namespace.yaml b/k8s/eshop-namespace.yaml deleted file mode 100644 index c7eebb7a0..000000000 --- a/k8s/eshop-namespace.yaml +++ /dev/null @@ -1,5 +0,0 @@ -apiVersion: v1 -kind: Namespace -metadata: - name: eshop - \ No newline at end of file diff --git a/k8s/ingress.yaml b/k8s/ingress.yaml deleted file mode 100644 index b5773bb25..000000000 --- a/k8s/ingress.yaml +++ /dev/null @@ -1,59 +0,0 @@ -apiVersion: extensions/v1beta1 -kind: Ingress -metadata: - labels: - app: eshop - component: frontend - name: eshop-ingress - annotations: - ingress.kubernetes.io/ssl-redirect: "false" -spec: - rules: - - http: - paths: - - path: /identity - backend: - serviceName: identity - servicePort: 80 - - path: /webmvc - backend: - serviceName: webmvc - servicePort: 80 - - path: /webstatus - backend: - serviceName: webstatus - servicePort: 80 - - path: /webshoppingapigw - backend: - serviceName: ocelotapigw-ws - servicePort: 80 - - path: /webmarketingapigw - backend: - serviceName: ocelotapigw-wm - servicePort: 80 - - path: /mobilemarketingapigw - backend: - serviceName: ocelotapigw-mm - servicePort: 80 - - path: /mobileshoppingapigw - backend: - serviceName: ocelotapigw-ms - servicePort: 80 - - path: /webshoppingagg - backend: - serviceName: webshoppingagg - servicePort: 80 - - path: /mobileshoppingagg - backend: - serviceName: mobileshoppingagg - servicePort: 80 - - path: /payment-api - backend: - serviceName: payment - servicePort: 80 - - path: / - backend: - serviceName: webspa - servicePort: 80 - - diff --git a/k8s/keystore-data.yaml b/k8s/keystore-data.yaml deleted file mode 100644 index 0e2dfa9b9..000000000 --- a/k8s/keystore-data.yaml +++ /dev/null @@ -1,29 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: keystore-data - name: keystore-data -spec: - ports: - - port: 6379 - selector: - app: eshop - component: keystore-data ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: keystore-data -spec: - template: - metadata: - labels: - app: eshop - component: keystore-data - spec: - containers: - - name: keystore-data - image: redis - diff --git a/k8s/linkerd/basket-api-sp.yaml b/k8s/linkerd/basket-api-sp.yaml new file mode 100644 index 000000000..6b23bdb9f --- /dev/null +++ b/k8s/linkerd/basket-api-sp.yaml @@ -0,0 +1,42 @@ +apiVersion: linkerd.io/v1alpha2 +kind: ServiceProfile +metadata: + creationTimestamp: null + name: basket-api.default.svc.cluster.local + namespace: default +spec: + routes: + - condition: + method: GET + pathRegex: /basket-api/api/v1/basket/[^/]* + name: GET Basket {id} + isRetryable: true + - condition: + method: GET + pathRegex: /hc + name: GET /hc + isRetryable: false + - condition: + method: GET + pathRegex: /liveness + name: GET /liveness + isRetryable: false + - condition: + method: POST + pathRegex: /BasketApi\.Basket/GetBasketById + name: POST /BasketApi.Basket/GetBasketById + isRetryable: true + - condition: + method: POST + pathRegex: /BasketApi\.Basket/UpdateBasket + name: POST /BasketApi.Basket/UpdateBasket + isRetryable: true + - condition: + method: POST + pathRegex: /basket-api/api/v1/basket/checkout + name: POST /v1/basket/checkout + isRetryable: true + retryBudget: + retryRatio: 0.2 + minRetriesPerSecond: 10 + ttl: 10s \ No newline at end of file diff --git a/k8s/linkerd/catalog-api-sp.yaml b/k8s/linkerd/catalog-api-sp.yaml new file mode 100644 index 000000000..6e9afa472 --- /dev/null +++ b/k8s/linkerd/catalog-api-sp.yaml @@ -0,0 +1,47 @@ +apiVersion: linkerd.io/v1alpha2 +kind: ServiceProfile +metadata: + creationTimestamp: null + name: catalog-api.default.svc.cluster.local + namespace: default +spec: + routes: + - condition: + method: GET + pathRegex: /catalog-api/api/v1/catalog/catalogbrands + name: GET /v1/catalog/catalogbrands + isRetryable: true + - condition: + method: GET + pathRegex: /catalog-api/api/v1/catalog/catalogtypes + name: GET /v1/catalog/catalogtypes + isRetryable: true + - condition: + method: GET + pathRegex: /catalog-api/api/v1/catalog/items + name: GET /v1/catalog/items + isRetryable: true + - condition: + method: GET + pathRegex: /api/v1/catalog/items/[^/]*/pic/ + name: GET /v1/catalog/items/{id}/pic/ + isRetryable: false + - condition: + method: GET + pathRegex: /hc + name: GET /hc + isRetryable: false + - condition: + method: GET + pathRegex: /liveness + isRetryable: false + name: GET /liveness + - condition: + method: POST + pathRegex: /CatalogApi\.Catalog/GetItemsByIds + name: POST /CatalogApi.Catalog/GetItemsByIds + isRetryable: true + retryBudget: + retryRatio: 0.2 + minRetriesPerSecond: 10 + ttl: 10s \ No newline at end of file diff --git a/k8s/nosql-data.yaml b/k8s/nosql-data.yaml deleted file mode 100644 index 5dfb67c6e..000000000 --- a/k8s/nosql-data.yaml +++ /dev/null @@ -1,30 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: nosql-data - name: nosql-data -spec: - ports: - - port: 27017 - selector: - app: eshop - component: nosql-data ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: nosql-data -spec: - template: - metadata: - labels: - app: eshop - component: nosql-data - spec: - containers: - - name: nosql-data - image: mongo - ports: - - containerPort: 27017 diff --git a/k8s/rabbitmq.yaml b/k8s/rabbitmq.yaml deleted file mode 100644 index d2a7de906..000000000 --- a/k8s/rabbitmq.yaml +++ /dev/null @@ -1,30 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: rabbitmq - name: rabbitmq -spec: - ports: - - port: 5672 - selector: - app: eshop - component: rabbitmq ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: rabbitmq -spec: - template: - metadata: - labels: - app: eshop - component: rabbitmq - spec: - containers: - - name: rabbitmq - image: rabbitmq:3-management - ports: - - containerPort: 5672 diff --git a/k8s/services.yaml b/k8s/services.yaml deleted file mode 100644 index ad537eaf0..000000000 --- a/k8s/services.yaml +++ /dev/null @@ -1,195 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: basket - name: basket -spec: - ports: - - port: 80 - selector: - app: eshop - component: basket ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: catalog - name: catalog -spec: - ports: - - port: 80 - selector: - app: eshop - component: catalog ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: identity - name: identity -spec: - ports: - - port: 80 - selector: - app: eshop - component: identity ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: ordering - name: ordering -spec: - ports: - - port: 80 - selector: - app: eshop - component: ordering ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: ordering-backgroundtasks - name: ordering-background -spec: - ports: - - port: 80 - selector: - app: eshop - component: ordering-backgroundtasks ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: ordering-signalrhub - name: ordering-signalrhub -spec: - ports: - - port: 80 - selector: - app: eshop - component: ordering-signalrhub ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: locations - name: locations -spec: - ports: - - port: 80 - selector: - app: eshop - component: locations ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: payment - name: payment -spec: - ports: - - port: 80 - selector: - app: eshop - component: payment ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: marketing - name: marketing -spec: - ports: - - port: 80 - selector: - app: eshop - component: marketing ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: webshoppingagg - name: webshoppingagg -spec: - ports: - - port: 80 - selector: - app: eshop - component: webshoppingagg ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: mobileshoppingagg - name: mobileshoppingagg -spec: - ports: - - port: 80 - selector: - app: eshop - component: mobileshoppingagg ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: webmvc - name: webmvc -spec: - ports: - - port: 80 - selector: - app: eshop - component: webmvc ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: webstatus - name: webstatus -spec: - ports: - - port: 80 - selector: - app: eshop - component: webstatus ---- -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: webspa - name: webspa -spec: - ports: - - port: 80 - selector: - app: eshop - component: webspa diff --git a/k8s/sql-data.yaml b/k8s/sql-data.yaml deleted file mode 100644 index 245622e83..000000000 --- a/k8s/sql-data.yaml +++ /dev/null @@ -1,35 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - labels: - app: eshop - component: sql-data - name: sql-data -spec: - ports: - - port: 1433 - selector: - app: eshop - component: sql-data ---- -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: sql-data -spec: - template: - metadata: - labels: - app: eshop - component: sql-data - spec: - containers: - - name: sql-data - image: microsoft/mssql-server-linux:2017-latest - env: - - name: ACCEPT_EULA - value: "Y" - - name: MSSQL_PID - value: Developer - - name: MSSQL_SA_PASSWORD - value: Pass@word diff --git a/src/Services/Basket/Basket.API/Infrastructure/Middlewares/FailingMiddleware.cs b/src/Services/Basket/Basket.API/Infrastructure/Middlewares/FailingMiddleware.cs index 875749b5f..852c61d1f 100644 --- a/src/Services/Basket/Basket.API/Infrastructure/Middlewares/FailingMiddleware.cs +++ b/src/Services/Basket/Basket.API/Infrastructure/Middlewares/FailingMiddleware.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading.Tasks; @@ -10,11 +11,13 @@ namespace Basket.API.Infrastructure.Middlewares private readonly RequestDelegate _next; private bool _mustFail; private readonly FailingOptions _options; - public FailingMiddleware(RequestDelegate next, FailingOptions options) + private readonly ILogger _logger; + public FailingMiddleware(RequestDelegate next, ILogger logger, FailingOptions options) { _next = next; _options = options; _mustFail = false; + _logger = logger; } public async Task Invoke(HttpContext context) { @@ -27,6 +30,7 @@ namespace Basket.API.Infrastructure.Middlewares if (MustFail(context)) { + _logger.LogInformation($"Response for path {path} will fail."); context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Failed due to FailingMiddleware enabled."); @@ -74,8 +78,15 @@ namespace Basket.API.Infrastructure.Middlewares private bool MustFail(HttpContext context) { + var rpath = context.Request.Path.Value; + + if (_options.NotFilteredPaths.Any(p => p.Equals(rpath, StringComparison.InvariantCultureIgnoreCase))) + { + return false; + } + return _mustFail && - (_options.EndpointPaths.Any(x => x == context.Request.Path.Value) + (_options.EndpointPaths.Any(x => x == rpath) || _options.EndpointPaths.Count == 0); } } diff --git a/src/Services/Basket/Basket.API/Infrastructure/Middlewares/FailingOptions.cs b/src/Services/Basket/Basket.API/Infrastructure/Middlewares/FailingOptions.cs index 45989832c..63e1e5525 100644 --- a/src/Services/Basket/Basket.API/Infrastructure/Middlewares/FailingOptions.cs +++ b/src/Services/Basket/Basket.API/Infrastructure/Middlewares/FailingOptions.cs @@ -6,5 +6,7 @@ namespace Basket.API.Infrastructure.Middlewares { public string ConfigPath = "/Failing"; public List EndpointPaths { get; set; } = new List(); + + public List NotFilteredPaths {get; set;} = new List(); } } diff --git a/src/Services/Basket/Basket.API/Program.cs b/src/Services/Basket/Basket.API/Program.cs index de1b54c2b..ac7294c15 100644 --- a/src/Services/Basket/Basket.API/Program.cs +++ b/src/Services/Basket/Basket.API/Program.cs @@ -60,7 +60,10 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API }); }) - .UseFailing(options => options.ConfigPath = "/Failing") + .UseFailing(options => { + options.ConfigPath = "/Failing"; + options.NotFilteredPaths.AddRange(new[] {"/hc","/liveness"}); + }) .UseStartup() .UseApplicationInsights() .UseContentRoot(Directory.GetCurrentDirectory()) From e4df0336e58ee204f4b84dc7f03248606327bbfd Mon Sep 17 00:00:00 2001 From: eiximenis Date: Wed, 16 Oct 2019 10:26:43 +0200 Subject: [PATCH 108/113] Changes in compose config for docker-compose up running ok. Added volumes for data --- .../Envoy/config/mobilemarketing/envoy.yaml | 28 +++++++++- .../Envoy/config/mobileshopping/envoy.yaml | 54 ++++++++++++++---- .../Envoy/config/webmarketing/envoy.yaml | 32 +++++++++-- .../Envoy/config/webshopping/envoy.yaml | 56 +++++++++++++++---- src/docker-compose.override.yml | 40 +++++++++---- 5 files changed, 169 insertions(+), 41 deletions(-) diff --git a/src/ApiGateways/Envoy/config/mobilemarketing/envoy.yaml b/src/ApiGateways/Envoy/config/mobilemarketing/envoy.yaml index 324d903ab..54b1afa06 100644 --- a/src/ApiGateways/Envoy/config/mobilemarketing/envoy.yaml +++ b/src/ApiGateways/Envoy/config/mobilemarketing/envoy.yaml @@ -23,17 +23,39 @@ static_resources: domains: - "*" routes: - - match: + - name: "m-short" + match: prefix: "/m/" route: + auto_host_rewrite: true prefix_rewrite: "/marketing-api/" cluster: marketing - - match: + - name: "m-long" + match: prefix: "/marketing-api/" route: + auto_host_rewrite: true cluster: marketing http_filters: - - name: envoy.router + - name: envoy.router + access_log: + - name: envoy.file_access_log + filter: + not_health_check_filter: {} + config: + json_format: + time: "%START_TIME%" + protocol: "%PROTOCOL%" + duration: "%DURATION%" + request_method: "%REQ(:METHOD)%" + request_host: "%REQ(HOST)%" + path: "%REQ(X-ENVOY-ORIGINAL-PATH?:PATH)%" + response_flags: "%RESPONSE_FLAGS%" + route_name: "%ROUTE_NAME%" + upstream_host: "%UPSTREAM_HOST%" + upstream_cluster: "%UPSTREAM_CLUSTER%" + upstream_local_address: "%UPSTREAM_LOCAL_ADDRESS%" + path: "/tmp/access.log" clusters: - name: marketing connect_timeout: 0.25s diff --git a/src/ApiGateways/Envoy/config/mobileshopping/envoy.yaml b/src/ApiGateways/Envoy/config/mobileshopping/envoy.yaml index 4d9f449cb..373806b06 100644 --- a/src/ApiGateways/Envoy/config/mobileshopping/envoy.yaml +++ b/src/ApiGateways/Envoy/config/mobileshopping/envoy.yaml @@ -23,44 +23,76 @@ static_resources: domains: - "*" routes: - - match: + - name: "c-short" + match: prefix: "/c/" route: + auto_host_rewrite: true prefix_rewrite: "/catalog-api/" cluster: catalog - - match: + - name: "c-long" + match: prefix: "/catalog-api/" route: + auto_host_rewrite: true cluster: catalog - - match: + - name: "o-short" + match: prefix: "/o/" route: + auto_host_rewrite: true prefix_rewrite: "/ordering-api/" cluster: ordering - - match: + - name: "o-long" + match: prefix: "/ordering-api/" route: + auto_host_rewrite: true cluster: ordering - - match: + - name: "b-short" + match: prefix: "/b/" route: + auto_host_rewrite: true prefix_rewrite: "/basket-api/" cluster: basket - - match: + - name: "b-long" + match: prefix: "/basket-api/" route: + auto_host_rewrite: true cluster: basket - - match: + - name: "agg" + match: prefix: "/" route: + auto_host_rewrite: true prefix_rewrite: "/" cluster: shoppingagg http_filters: - name: envoy.router + access_log: + - name: envoy.file_access_log + filter: + not_health_check_filter: {} + config: + json_format: + time: "%START_TIME%" + protocol: "%PROTOCOL%" + duration: "%DURATION%" + request_method: "%REQ(:METHOD)%" + request_host: "%REQ(HOST)%" + path: "%REQ(X-ENVOY-ORIGINAL-PATH?:PATH)%" + response_flags: "%RESPONSE_FLAGS%" + route_name: "%ROUTE_NAME%" + upstream_host: "%UPSTREAM_HOST%" + upstream_cluster: "%UPSTREAM_CLUSTER%" + upstream_local_address: "%UPSTREAM_LOCAL_ADDRESS%" + path: "/tmp/access.log" clusters: - name: shoppingagg connect_timeout: 0.25s - type: logical_dns + type: strict_dns lb_policy: round_robin hosts: - socket_address: @@ -68,7 +100,7 @@ static_resources: port_value: 80 - name: catalog connect_timeout: 0.25s - type: logical_dns + type: strict_dns lb_policy: round_robin hosts: - socket_address: @@ -76,7 +108,7 @@ static_resources: port_value: 80 - name: basket connect_timeout: 0.25s - type: logical_dns + type: strict_dns lb_policy: round_robin hosts: - socket_address: @@ -84,7 +116,7 @@ static_resources: port_value: 80 - name: ordering connect_timeout: 0.25s - type: logical_dns + type: strict_dns lb_policy: round_robin hosts: - socket_address: diff --git a/src/ApiGateways/Envoy/config/webmarketing/envoy.yaml b/src/ApiGateways/Envoy/config/webmarketing/envoy.yaml index 324d903ab..c6f3421de 100644 --- a/src/ApiGateways/Envoy/config/webmarketing/envoy.yaml +++ b/src/ApiGateways/Envoy/config/webmarketing/envoy.yaml @@ -23,21 +23,43 @@ static_resources: domains: - "*" routes: - - match: + - name: "m-short" + match: prefix: "/m/" route: + auto_host_rewrite: true prefix_rewrite: "/marketing-api/" cluster: marketing - - match: + - name: "m-long" + match: prefix: "/marketing-api/" route: + auto_host_rewrite: true cluster: marketing http_filters: - - name: envoy.router + - name: envoy.router + access_log: + - name: envoy.file_access_log + filter: + not_health_check_filter: {} + config: + json_format: + time: "%START_TIME%" + protocol: "%PROTOCOL%" + duration: "%DURATION%" + request_method: "%REQ(:METHOD)%" + request_host: "%REQ(HOST)%" + path: "%REQ(X-ENVOY-ORIGINAL-PATH?:PATH)%" + response_flags: "%RESPONSE_FLAGS%" + route_name: "%ROUTE_NAME%" + upstream_host: "%UPSTREAM_HOST%" + upstream_cluster: "%UPSTREAM_CLUSTER%" + upstream_local_address: "%UPSTREAM_LOCAL_ADDRESS%" + path: "/tmp/access.log" clusters: - name: marketing connect_timeout: 0.25s - type: logical_dns + type: strict_dns lb_policy: round_robin hosts: - socket_address: @@ -45,7 +67,7 @@ static_resources: port_value: 80 - name: locations connect_timeout: 0.25s - type: logical_dns + type: strict_dns lb_policy: round_robin hosts: - socket_address: diff --git a/src/ApiGateways/Envoy/config/webshopping/envoy.yaml b/src/ApiGateways/Envoy/config/webshopping/envoy.yaml index 4d9f449cb..1491f37af 100644 --- a/src/ApiGateways/Envoy/config/webshopping/envoy.yaml +++ b/src/ApiGateways/Envoy/config/webshopping/envoy.yaml @@ -23,44 +23,76 @@ static_resources: domains: - "*" routes: - - match: + - name: "c-short" + match: prefix: "/c/" route: + auto_host_rewrite: true prefix_rewrite: "/catalog-api/" cluster: catalog - - match: + - name: "c-long" + match: prefix: "/catalog-api/" route: + auto_host_rewrite: true cluster: catalog - - match: + - name: "o-short" + match: prefix: "/o/" route: + auto_host_rewrite: true prefix_rewrite: "/ordering-api/" cluster: ordering - - match: + - name: "o-long" + match: prefix: "/ordering-api/" route: + auto_host_rewrite: true cluster: ordering - - match: + - name: "b-short" + match: prefix: "/b/" route: + auto_host_rewrite: true prefix_rewrite: "/basket-api/" cluster: basket - - match: + - name: "b-long" + match: prefix: "/basket-api/" route: + auto_host_rewrite: true cluster: basket - - match: + - name: "agg" + match: prefix: "/" route: + auto_host_rewrite: true prefix_rewrite: "/" cluster: shoppingagg http_filters: - - name: envoy.router + - name: envoy.router + access_log: + - name: envoy.file_access_log + filter: + not_health_check_filter: {} + config: + json_format: + time: "%START_TIME%" + protocol: "%PROTOCOL%" + duration: "%DURATION%" + request_method: "%REQ(:METHOD)%" + request_host: "%REQ(HOST)%" + path: "%REQ(X-ENVOY-ORIGINAL-PATH?:PATH)%" + response_flags: "%RESPONSE_FLAGS%" + route_name: "%ROUTE_NAME%" + upstream_host: "%UPSTREAM_HOST%" + upstream_cluster: "%UPSTREAM_CLUSTER%" + upstream_local_address: "%UPSTREAM_LOCAL_ADDRESS%" + path: "/tmp/access.log" clusters: - name: shoppingagg connect_timeout: 0.25s - type: logical_dns + type: strict_dns lb_policy: round_robin hosts: - socket_address: @@ -68,7 +100,7 @@ static_resources: port_value: 80 - name: catalog connect_timeout: 0.25s - type: logical_dns + type: strict_dns lb_policy: round_robin hosts: - socket_address: @@ -76,7 +108,7 @@ static_resources: port_value: 80 - name: basket connect_timeout: 0.25s - type: logical_dns + type: strict_dns lb_policy: round_robin hosts: - socket_address: @@ -84,7 +116,7 @@ static_resources: port_value: 80 - name: ordering connect_timeout: 0.25s - type: logical_dns + type: strict_dns lb_policy: round_robin hosts: - socket_address: diff --git a/src/docker-compose.override.yml b/src/docker-compose.override.yml index a6fa6c483..564ff4eb9 100644 --- a/src/docker-compose.override.yml +++ b/src/docker-compose.override.yml @@ -19,15 +19,20 @@ services: - ACCEPT_EULA=Y ports: - "5433:1433" + volumes: + - eshop-sqldata:/var/opt/mssql nosqldata: ports: - "27017:27017" + volumes: + - eshop-nosqldata:/data/db basketdata: ports: - "6379:6379" - + volumes: + - eshop-basketdata:/data rabbitmq: ports: - "15672:15672" @@ -69,10 +74,12 @@ services: - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - OrchestratorType=${ORCHESTRATOR_TYPE} - UseLoadTest=${USE_LOADTEST:-False} - + - PATH_BASE=/basket-api + - GRPC_PORT=81 + - PORT=80 ports: - "5103:80" - - "5580:5001" + - "9103:81" catalog-api: environment: @@ -91,6 +98,7 @@ services: - OrchestratorType=${ORCHESTRATOR_TYPE} - GRPC_PORT=81 - PORT=80 + - PATH_BASE=/catalog-api ports: - "5101:80" - "9101:81" @@ -113,9 +121,12 @@ services: - UseLoadTest=${USE_LOADTEST:-False} - Serilog__MinimumLevel__Override__Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ=Verbose - Serilog__MinimumLevel__Override__ordering-api=Verbose + - PATH_BASE=/ordering-api + - GRPC_PORT=81 + - PORT=80 ports: - "5102:80" - - "5581:5001" + - "9102:81" ordering-backgroundtasks: environment: @@ -157,6 +168,7 @@ services: - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - OrchestratorType=${ORCHESTRATOR_TYPE} - UseLoadTest=${USE_LOADTEST:-False} + - PATH_BASE=/marketing-api ports: - "5110:80" @@ -190,6 +202,7 @@ services: - ApplicationInsights__InstrumentationKey=${INSTRUMENTATION_KEY} - OrchestratorType=${ORCHESTRATOR_TYPE} - UseLoadTest=${USE_LOADTEST:-False} + - PATH_BASE=/locations-api ports: - "5109:80" @@ -241,9 +254,9 @@ services: - urls__catalog=http://catalog-api - urls__orders=http://ordering-api - urls__identity=http://identity-api - - urls__grpcBasket=http://10.0.75.1:5580 - - urls__grpcCatalog=http://10.0.75.1:9101 - - urls__grpcOrdering=http://10.0.75.1:5581 + - urls__grpcBasket=http://basket-api:81 + - urls__grpcCatalog=http://catalog-api:81 + - urls__grpcOrdering=http://ordering-api:81 - CatalogUrlHC=http://catalog-api/hc - OrderingUrlHC=http://ordering-api/hc - IdentityUrlHC=http://identity-api/hc @@ -262,9 +275,9 @@ services: - urls__catalog=http://catalog-api - urls__orders=http://ordering-api - urls__identity=http://identity-api - - urls__grpcBasket=http://10.0.75.1:5580 - - urls__grpcCatalog=http://10.0.75.1:9101 - - urls__grpcOrdering=http://10.0.75.1:5581 + - urls__grpcBasket=http://basket-api:81 + - urls__grpcCatalog=http://catalog-api:81 + - urls__grpcOrdering=http://ordering-api:81 - CatalogUrlHC=http://catalog-api/hc - OrderingUrlHC=http://ordering-api/hc - IdentityUrlHC=http://identity-api/hc @@ -366,4 +379,11 @@ services: - SelfUrl=http://webhooks-client/ ports: - "5114:80" +volumes: + eshop-sqldata: + external: false + eshop-nosqldata: + external: false + eshop-basketdata: + external: false From 34a0c03434f1ccebe8cf70b02ad60aa4bf9d3974 Mon Sep 17 00:00:00 2001 From: eiximenis Date: Thu, 31 Oct 2019 09:45:18 +0100 Subject: [PATCH 109/113] Update dockerfile.develop to net3 --- k8s/helm/deploy-all.ps1 | 2 +- .../Mobile.Bff.Shopping/aggregator/Dockerfile.develop | 2 +- src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile.develop | 2 +- src/Services/Basket/Basket.API/Dockerfile.develop | 2 +- src/Services/Catalog/Catalog.API/Dockerfile.develop | 2 +- src/Services/Identity/Identity.API/Dockerfile.develop | 2 +- src/Services/Location/Locations.API/Dockerfile.develop | 2 +- src/Services/Marketing/Marketing.API/Dockerfile.develop | 2 +- src/Services/Ordering/Ordering.API/Dockerfile.develop | 2 +- src/Services/Ordering/Ordering.SignalrHub/Dockerfile.develop | 2 +- src/Services/Payment/Payment.API/Dockerfile.develop | 2 +- src/Services/Webhooks/Webhooks.API/Dockerfile.develop | 2 +- src/Web/WebMVC/Dockerfile.develop | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/k8s/helm/deploy-all.ps1 b/k8s/helm/deploy-all.ps1 index a30cc10b9..ae49de625 100644 --- a/k8s/helm/deploy-all.ps1 +++ b/k8s/helm/deploy-all.ps1 @@ -11,7 +11,7 @@ Param( [parameter(Mandatory=$false)][string]$aksRg="", [parameter(Mandatory=$false)][string]$imageTag="latest", [parameter(Mandatory=$false)][bool]$useLocalk8s=$false, - [parameter(Mandatory=$false)][bool]$useMesh=$true, + [parameter(Mandatory=$false)][bool]$useMesh=$false, [parameter(Mandatory=$false)][string][ValidateSet('Always','IfNotPresent','Never', IgnoreCase=$false)]$imagePullPolicy="Always", [parameter(Mandatory=$false)][string]$chartsToDeploy="*", [parameter(Mandatory=$false)][string]$ingressMeshAnnotationsFile="ingress_values_linkerd.yaml" diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile.develop b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile.develop index c4330c370..4cfe352f0 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile.develop +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile.develop b/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile.develop index 3d0d16dd3..79f531777 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile.develop +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/Services/Basket/Basket.API/Dockerfile.develop b/src/Services/Basket/Basket.API/Dockerfile.develop index 428aa85da..66ea6a07d 100644 --- a/src/Services/Basket/Basket.API/Dockerfile.develop +++ b/src/Services/Basket/Basket.API/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/Services/Catalog/Catalog.API/Dockerfile.develop b/src/Services/Catalog/Catalog.API/Dockerfile.develop index c158d2b97..bb79af28d 100644 --- a/src/Services/Catalog/Catalog.API/Dockerfile.develop +++ b/src/Services/Catalog/Catalog.API/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/Services/Identity/Identity.API/Dockerfile.develop b/src/Services/Identity/Identity.API/Dockerfile.develop index e01f161ae..746354008 100644 --- a/src/Services/Identity/Identity.API/Dockerfile.develop +++ b/src/Services/Identity/Identity.API/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/Services/Location/Locations.API/Dockerfile.develop b/src/Services/Location/Locations.API/Dockerfile.develop index 2ab8b74af..ab1f7bfb8 100644 --- a/src/Services/Location/Locations.API/Dockerfile.develop +++ b/src/Services/Location/Locations.API/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/Services/Marketing/Marketing.API/Dockerfile.develop b/src/Services/Marketing/Marketing.API/Dockerfile.develop index 2911c5fb7..8425f47c1 100644 --- a/src/Services/Marketing/Marketing.API/Dockerfile.develop +++ b/src/Services/Marketing/Marketing.API/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/Services/Ordering/Ordering.API/Dockerfile.develop b/src/Services/Ordering/Ordering.API/Dockerfile.develop index 72d98aa72..70fbab4bf 100644 --- a/src/Services/Ordering/Ordering.API/Dockerfile.develop +++ b/src/Services/Ordering/Ordering.API/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/Services/Ordering/Ordering.SignalrHub/Dockerfile.develop b/src/Services/Ordering/Ordering.SignalrHub/Dockerfile.develop index d96223149..d55d319b1 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Dockerfile.develop +++ b/src/Services/Ordering/Ordering.SignalrHub/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/Services/Payment/Payment.API/Dockerfile.develop b/src/Services/Payment/Payment.API/Dockerfile.develop index 585fbe48f..0b671a94f 100644 --- a/src/Services/Payment/Payment.API/Dockerfile.develop +++ b/src/Services/Payment/Payment.API/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/Services/Webhooks/Webhooks.API/Dockerfile.develop b/src/Services/Webhooks/Webhooks.API/Dockerfile.develop index 2c16150e4..9dbc57a1f 100644 --- a/src/Services/Webhooks/Webhooks.API/Dockerfile.develop +++ b/src/Services/Webhooks/Webhooks.API/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true diff --git a/src/Web/WebMVC/Dockerfile.develop b/src/Web/WebMVC/Dockerfile.develop index 172f6bf05..0e4a5dc81 100644 --- a/src/Web/WebMVC/Dockerfile.develop +++ b/src/Web/WebMVC/Dockerfile.develop @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.2-sdk +FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster ARG BUILD_CONFIGURATION=Debug ENV ASPNETCORE_ENVIRONMENT=Development ENV DOTNET_USE_POLLING_FILE_WATCHER=true From d2d33da437241fad49a0f0aa1c66e64ff2a185a7 Mon Sep 17 00:00:00 2001 From: eiximenis Date: Thu, 31 Oct 2019 11:03:37 +0100 Subject: [PATCH 110/113] Readme updated to net3 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 839e2f186..6dfd3bd0c 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,8 @@ Dev branch contains the latest "stable" code, and their images are tagged with ` **NEWS / ANNOUNCEMENTS** Do you want to be up-to-date on .NET Architecture guidance and reference apps like eShopOnContainers? --> Subscribe by "WATCHING" this new GitHub repo: https://github.com/dotnet-architecture/News -## Updated for .NET Core 2.2 "wave" of technologies -eShopOnContainers is updated to .NET Core 2.x (currently updated to 2.2) "wave" of technologies. Not just compilation but also new recommended code in EF Core, ASP.NET Core, and other new related versions. +## Updated for .NET Core 3.0 +eShopOnContainers is updated to .NET Core 3.0 "wave" of technologies. Not just compilation but also new recommended code in EF Core, ASP.NET Core, and other new related versions. The **dockerfiles** in the solution have also been updated and now support [**Docker Multi-Stage**](https://blogs.msdn.microsoft.com/stevelasker/2017/09/11/net-and-multistage-dockerfiles/) since mid-December 2017. From 87f38fd934326ec050fb5706a6f6189c69440efc Mon Sep 17 00:00:00 2001 From: eiximenis Date: Thu, 31 Oct 2019 11:06:42 +0100 Subject: [PATCH 111/113] fixed path in azure devops build --- build/azure-devops/buildimages.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/build/azure-devops/buildimages.yaml b/build/azure-devops/buildimages.yaml index fc2a41e72..fc97aaaea 100644 --- a/build/azure-devops/buildimages.yaml +++ b/build/azure-devops/buildimages.yaml @@ -36,7 +36,7 @@ jobs: dockerComposeCommand: 'build ${{ parameters.services }}' containerregistrytype: Container Registry dockerRegistryEndpoint: ${{ parameters.registryEndpoint }} - dockerComposeFile: docker-compose.yml + dockerComposeFile: src/docker-compose.yml qualifyImageNames: true projectName: "" dockerComposeFileArgs: | @@ -47,7 +47,7 @@ jobs: dockerComposeCommand: 'push ${{ parameters.services }}' containerregistrytype: Container Registry dockerRegistryEndpoint: ${{ parameters.registryEndpoint }} - dockerComposeFile: docker-compose.yml + dockerComposeFile: src/docker-compose.yml qualifyImageNames: true projectName: "" dockerComposeFileArgs: | @@ -71,7 +71,7 @@ jobs: dockerComposeCommand: 'build ${{ parameters.services }}' containerregistrytype: Container Registry dockerRegistryEndpoint: ${{ parameters.registryEndpoint }} - dockerComposeFile: docker-compose.yml + dockerComposeFile: src/docker-compose.yml qualifyImageNames: true projectName: "" dockerComposeFileArgs: | @@ -84,7 +84,7 @@ jobs: dockerComposeCommand: 'push ${{ parameters.services }}' containerregistrytype: Container Registry dockerRegistryEndpoint: ${{ parameters.registryEndpoint }} - dockerComposeFile: docker-compose.yml + dockerComposeFile: src/docker-compose.yml qualifyImageNames: true projectName: "" dockerComposeFileArgs: | From b34b8d24034a467355d4cf39ae2701e9ac23e5d2 Mon Sep 17 00:00:00 2001 From: Miguel Veloso Date: Wed, 6 Nov 2019 11:14:19 +0000 Subject: [PATCH 112/113] Sort package references --- .../Mobile.Shopping.HttpAggregator.csproj | 6 +++--- .../Web.Shopping.HttpAggregator.csproj | 8 ++++---- .../EventBus.Tests/EventBus.Tests.csproj | 2 +- .../IntegrationEventLogEF.csproj | 5 +++-- .../WebHost.Customization.csproj | 4 ++-- .../Clients.Grpc.Caller.csproj | 1 + .../eShopOnContainers.Core.csproj | 7 ++++--- .../eShopOnContainers.UnitTests.csproj | 3 ++- .../Basket/Basket.API/Basket.API.csproj | 4 ++-- .../Basket.FunctionalTests.csproj | 7 +++---- .../Basket.UnitTests/Basket.UnitTests.csproj | 13 ++++++------ .../Catalog/Catalog.API/Catalog.API.csproj | 9 ++++----- .../Catalog.FunctionalTests.csproj | 5 ++--- .../Catalog.UnitTests.csproj | 9 ++++----- .../Identity/Identity.API/Identity.API.csproj | 20 ++++++------------- .../Locations.API/Locations.API.csproj | 5 +++-- .../Locations.FunctionalTests.csproj | 5 ++--- .../AzureFunctions/marketing-functions.csproj | 4 +++- .../Marketing.API/Marketing.API.csproj | 8 +++++--- .../Marketing.FunctionalTests.csproj | 5 ++--- .../Ordering/Ordering.API/Ordering.API.csproj | 15 +++++++------- .../Ordering.BackgroundTasks.csproj | 9 ++++----- .../Ordering.Domain/Ordering.Domain.csproj | 2 +- .../Ordering.FunctionalTests.csproj | 3 +-- .../Ordering.Infrastructure.csproj | 2 +- .../Ordering.SignalrHub.csproj | 8 +++----- .../Ordering.UnitTests.csproj | 11 +++++----- .../Payment/Payment.API/Payment.API.csproj | 3 ++- .../Webhooks/Webhooks.API/Webhooks.API.csproj | 13 ++++++------ src/Web/WebMVC/WebMVC.csproj | 20 ++++++------------- src/Web/WebSPA/WebSPA.csproj | 12 +---------- src/Web/WebStatus/WebStatus.csproj | 6 ++++-- src/Web/WebhookClient/WebhookClient.csproj | 5 ++--- 33 files changed, 107 insertions(+), 132 deletions(-) diff --git a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj index 060cf3a3b..31d56dda7 100644 --- a/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj @@ -15,18 +15,18 @@ - - + + + - diff --git a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj index 86b660e21..0f8ae5efe 100644 --- a/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj +++ b/src/ApiGateways/Web.Bff.Shopping/aggregator/Web.Shopping.HttpAggregator.csproj @@ -15,19 +15,19 @@ - - + + - + + - diff --git a/src/BuildingBlocks/EventBus/EventBus.Tests/EventBus.Tests.csproj b/src/BuildingBlocks/EventBus/EventBus.Tests/EventBus.Tests.csproj index ef1a920e9..1d3f2bc0f 100644 --- a/src/BuildingBlocks/EventBus/EventBus.Tests/EventBus.Tests.csproj +++ b/src/BuildingBlocks/EventBus/EventBus.Tests/EventBus.Tests.csproj @@ -6,8 +6,8 @@ - + diff --git a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj index 793171c78..14b867059 100644 --- a/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj +++ b/src/BuildingBlocks/EventBus/IntegrationEventLogEF/IntegrationEventLogEF.csproj @@ -6,15 +6,16 @@ - all runtime; build; native; contentfiles; analyzers; buildtransitive + - + + diff --git a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj index 4352c2dee..38ab6b285 100644 --- a/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj +++ b/src/BuildingBlocks/WebHostCustomization/WebHost.Customization/WebHost.Customization.csproj @@ -6,16 +6,16 @@ - - all runtime; build; native; contentfiles; analyzers; buildtransitive + + diff --git a/src/Clients/Clients.Grpc.Caller/Clients.Grpc.Caller.csproj b/src/Clients/Clients.Grpc.Caller/Clients.Grpc.Caller.csproj index 379eb2de1..7cf903982 100644 --- a/src/Clients/Clients.Grpc.Caller/Clients.Grpc.Caller.csproj +++ b/src/Clients/Clients.Grpc.Caller/Clients.Grpc.Caller.csproj @@ -10,6 +10,7 @@ + diff --git a/src/Mobile/eShopOnContainers/eShopOnContainers.Core/eShopOnContainers.Core.csproj b/src/Mobile/eShopOnContainers/eShopOnContainers.Core/eShopOnContainers.Core.csproj index 99606079f..8b77f5733 100644 --- a/src/Mobile/eShopOnContainers/eShopOnContainers.Core/eShopOnContainers.Core.csproj +++ b/src/Mobile/eShopOnContainers/eShopOnContainers.Core/eShopOnContainers.Core.csproj @@ -5,15 +5,16 @@ - - + + + - + diff --git a/src/Mobile/eShopOnContainers/eShopOnContainers.UnitTests/eShopOnContainers.UnitTests.csproj b/src/Mobile/eShopOnContainers/eShopOnContainers.UnitTests/eShopOnContainers.UnitTests.csproj index d5c8bdb3b..f31ca2aed 100644 --- a/src/Mobile/eShopOnContainers/eShopOnContainers.UnitTests/eShopOnContainers.UnitTests.csproj +++ b/src/Mobile/eShopOnContainers/eShopOnContainers.UnitTests/eShopOnContainers.UnitTests.csproj @@ -6,9 +6,10 @@ - + + diff --git a/src/Services/Basket/Basket.API/Basket.API.csproj b/src/Services/Basket/Basket.API/Basket.API.csproj index 769260d44..df260ed7e 100644 --- a/src/Services/Basket/Basket.API/Basket.API.csproj +++ b/src/Services/Basket/Basket.API/Basket.API.csproj @@ -21,8 +21,8 @@ - + @@ -36,8 +36,8 @@ - + diff --git a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj index 8d0081e18..5e9e5c036 100644 --- a/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj +++ b/src/Services/Basket/Basket.FunctionalTests/Basket.FunctionalTests.csproj @@ -17,15 +17,14 @@ - - + + all runtime; build; native; contentfiles; analyzers - - + diff --git a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj index 019d5bdfc..92731fb9c 100644 --- a/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj +++ b/src/Services/Basket/Basket.UnitTests/Basket.UnitTests.csproj @@ -7,20 +7,19 @@ - - + - - + + - + + all runtime; build; native; contentfiles; analyzers - - + diff --git a/src/Services/Catalog/Catalog.API/Catalog.API.csproj b/src/Services/Catalog/Catalog.API/Catalog.API.csproj index 3d64e1181..662c55c08 100644 --- a/src/Services/Catalog/Catalog.API/Catalog.API.csproj +++ b/src/Services/Catalog/Catalog.API/Catalog.API.csproj @@ -42,16 +42,15 @@ - - - - + + + @@ -62,8 +61,8 @@ - + diff --git a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj index 22ca35532..5e7fcefbe 100644 --- a/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj +++ b/src/Services/Catalog/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj @@ -34,14 +34,13 @@ - - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj index 29729d05d..44b5660c1 100644 --- a/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj +++ b/src/Services/Catalog/Catalog.UnitTests/Catalog.UnitTests.csproj @@ -7,17 +7,16 @@ - - + - + + all runtime; build; native; contentfiles; analyzers - - + diff --git a/src/Services/Identity/Identity.API/Identity.API.csproj b/src/Services/Identity/Identity.API/Identity.API.csproj index 27eda89f5..f2e7bec58 100644 --- a/src/Services/Identity/Identity.API/Identity.API.csproj +++ b/src/Services/Identity/Identity.API/Identity.API.csproj @@ -19,17 +19,19 @@ - - - + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -44,21 +46,11 @@ - + - - - - diff --git a/src/Services/Location/Locations.API/Locations.API.csproj b/src/Services/Location/Locations.API/Locations.API.csproj index 789c518b7..517586eb4 100644 --- a/src/Services/Location/Locations.API/Locations.API.csproj +++ b/src/Services/Location/Locations.API/Locations.API.csproj @@ -8,6 +8,7 @@ true $(LangVersion) + @@ -24,14 +25,14 @@ - + - + diff --git a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj index 97670c9d1..1e3e15e8a 100644 --- a/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj +++ b/src/Services/Location/Locations.FunctionalTests/Locations.FunctionalTests.csproj @@ -18,14 +18,13 @@ - - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Marketing/Infrastructure/AzureFunctions/marketing-functions.csproj b/src/Services/Marketing/Infrastructure/AzureFunctions/marketing-functions.csproj index e159feb69..33e93b625 100644 --- a/src/Services/Marketing/Infrastructure/AzureFunctions/marketing-functions.csproj +++ b/src/Services/Marketing/Infrastructure/AzureFunctions/marketing-functions.csproj @@ -2,11 +2,13 @@ net461 + - + + diff --git a/src/Services/Marketing/Marketing.API/Marketing.API.csproj b/src/Services/Marketing/Marketing.API/Marketing.API.csproj index f0b370ba4..339da9be2 100644 --- a/src/Services/Marketing/Marketing.API/Marketing.API.csproj +++ b/src/Services/Marketing/Marketing.API/Marketing.API.csproj @@ -22,6 +22,7 @@ + @@ -33,23 +34,24 @@ + - + - + - + diff --git a/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj b/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj index 26f54e7d8..9f51dfbbc 100644 --- a/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj +++ b/src/Services/Marketing/Marketing.FunctionalTests/Marketing.FunctionalTests.csproj @@ -18,14 +18,13 @@ - - + all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Ordering/Ordering.API/Ordering.API.csproj b/src/Services/Ordering/Ordering.API/Ordering.API.csproj index 0728d5f5e..e3e5c8767 100644 --- a/src/Services/Ordering/Ordering.API/Ordering.API.csproj +++ b/src/Services/Ordering/Ordering.API/Ordering.API.csproj @@ -37,10 +37,6 @@ - - - - @@ -48,13 +44,18 @@ - + + + + + + @@ -63,13 +64,13 @@ - + - + PreserveNewest diff --git a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj index f068176d2..5e9a6eb83 100644 --- a/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj +++ b/src/Services/Ordering/Ordering.BackgroundTasks/Ordering.BackgroundTasks.csproj @@ -13,21 +13,20 @@ - + - - - + + - + diff --git a/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj b/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj index c7e83afc6..0574427f0 100644 --- a/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj +++ b/src/Services/Ordering/Ordering.Domain/Ordering.Domain.csproj @@ -5,8 +5,8 @@ - + diff --git a/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj b/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj index 363154aab..05668125f 100644 --- a/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj +++ b/src/Services/Ordering/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj @@ -20,12 +20,11 @@ - all runtime; build; native; contentfiles; analyzers - + diff --git a/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj b/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj index 0f7038bfd..22bfb2a56 100644 --- a/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj +++ b/src/Services/Ordering/Ordering.Infrastructure/Ordering.Infrastructure.csproj @@ -9,8 +9,8 @@ - + diff --git a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj index e079f0e4e..b64c881a8 100644 --- a/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj +++ b/src/Services/Ordering/Ordering.SignalrHub/Ordering.SignalrHub.csproj @@ -8,8 +8,6 @@ $(LangVersion) - - @@ -22,6 +20,8 @@ + + @@ -29,13 +29,11 @@ - - - + diff --git a/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj b/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj index 3c12dc001..5b7ed2060 100644 --- a/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj +++ b/src/Services/Ordering/Ordering.UnitTests/Ordering.UnitTests.csproj @@ -7,18 +7,17 @@ - - + + + - + all runtime; build; native; contentfiles; analyzers - - - + diff --git a/src/Services/Payment/Payment.API/Payment.API.csproj b/src/Services/Payment/Payment.API/Payment.API.csproj index dfca01597..497349a66 100644 --- a/src/Services/Payment/Payment.API/Payment.API.csproj +++ b/src/Services/Payment/Payment.API/Payment.API.csproj @@ -24,9 +24,10 @@ - + + diff --git a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj index b179b4e42..1e9b44858 100644 --- a/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj +++ b/src/Services/Webhooks/Webhooks.API/Webhooks.API.csproj @@ -11,19 +11,20 @@ - - + + - + - + + + - - + diff --git a/src/Web/WebMVC/WebMVC.csproj b/src/Web/WebMVC/WebMVC.csproj index f5da398b3..f6d02d0cd 100644 --- a/src/Web/WebMVC/WebMVC.csproj +++ b/src/Web/WebMVC/WebMVC.csproj @@ -23,36 +23,28 @@ - + + + + - - + - - - + - - diff --git a/src/Web/WebSPA/WebSPA.csproj b/src/Web/WebSPA/WebSPA.csproj index 5929a758b..a3b247086 100644 --- a/src/Web/WebSPA/WebSPA.csproj +++ b/src/Web/WebSPA/WebSPA.csproj @@ -92,24 +92,14 @@ + - - - - - diff --git a/src/Web/WebStatus/WebStatus.csproj b/src/Web/WebStatus/WebStatus.csproj index 5fc1ca257..7ddadb6f2 100644 --- a/src/Web/WebStatus/WebStatus.csproj +++ b/src/Web/WebStatus/WebStatus.csproj @@ -6,9 +6,10 @@ true $(LangVersion) + - + @@ -21,9 +22,10 @@ - + + Always diff --git a/src/Web/WebhookClient/WebhookClient.csproj b/src/Web/WebhookClient/WebhookClient.csproj index 1e87e6404..95f4b79e8 100644 --- a/src/Web/WebhookClient/WebhookClient.csproj +++ b/src/Web/WebhookClient/WebhookClient.csproj @@ -11,12 +11,11 @@ $(LangVersion) - + + - - From 8712d7eaac22d71e9ac7fdfb5de888d32f57960c Mon Sep 17 00:00:00 2001 From: Miguel Veloso Date: Wed, 6 Nov 2019 12:33:02 +0000 Subject: [PATCH 113/113] Aling basket-data-test entry with base .yml --- src/docker-compose-tests.override.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/docker-compose-tests.override.yml b/src/docker-compose-tests.override.yml index 068f02e66..cee5c6623 100644 --- a/src/docker-compose-tests.override.yml +++ b/src/docker-compose-tests.override.yml @@ -6,6 +6,10 @@ services: - "15672:15672" - "5672:5672" + basket-data-test: + ports: + - "6379:6379" + sql-data-test: environment: - SA_PASSWORD=Pass@word @@ -17,10 +21,6 @@ services: ports: - "27017:27017" - basket-data-test: - ports: - - "6379:6379" - identity-api-test: environment: - ASPNETCORE_ENVIRONMENT=Development