Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/PublicApi/PublicApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>..\..</DockerfileContext>
<Nullable>enable</Nullable>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand Down
13 changes: 13 additions & 0 deletions src/PublicApi/dotnet-tools.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "10.0.8",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}
126 changes: 86 additions & 40 deletions src/Web/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,67 +17,113 @@ public static class ServiceCollectionExtensions
{
public static void AddDatabaseContexts(this IServiceCollection services, IWebHostEnvironment environment, ConfigurationManager configuration)
{
var useInMemory = configuration.GetValue<bool>("UseOnlyInMemoryDatabase");

if (useInMemory)
{
// ✅ Use InMemory DB (NO Azure, NO SQL, NO KeyVault)
services.AddDbContext<CatalogContext>(options =>
options.UseInMemoryDatabase("Catalog"));

services.AddDbContext<AppIdentityDbContext>(options =>
options.UseInMemoryDatabase("Identity"));

return;
}

if (environment.IsDevelopment() || environment.IsDocker())
{
// Configure SQL Server (local)
services.ConfigureLocalDatabaseContexts(configuration);
}
else
{
// Configure SQL Server (prod)
var credential = new ChainedTokenCredential(new AzureDeveloperCliCredential(), new DefaultAzureCredential());
configuration.AddAzureKeyVault(new Uri(configuration["AZURE_KEY_VAULT_ENDPOINT"] ?? ""), credential);
// ❌ Only used when real Azure setup exists
var credential = new ChainedTokenCredential(
new AzureDeveloperCliCredential(),
new DefaultAzureCredential());

configuration.AddAzureKeyVault(
new Uri(configuration["AZURE_KEY_VAULT_ENDPOINT"] ?? ""),
credential);

services.AddDbContext<CatalogContext>((provider, options) =>
{
var connectionString = configuration[configuration["AZURE_SQL_CATALOG_CONNECTION_STRING_KEY"] ?? ""];
options.UseSqlServer(connectionString, sqlOptions => sqlOptions.EnableRetryOnFailure())
.AddInterceptors(provider.GetRequiredService<DbCallCountingInterceptor>());
.AddInterceptors(provider.GetRequiredService<DbCallCountingInterceptor>());
});
services.AddDbContext<AppIdentityDbContext>((provider,options) =>

services.AddDbContext<AppIdentityDbContext>((provider, options) =>
{
var connectionString = configuration[configuration["AZURE_SQL_IDENTITY_CONNECTION_STRING_KEY"] ?? ""];
options.UseSqlServer(connectionString, sqlOptions => sqlOptions.EnableRetryOnFailure())
.AddInterceptors(provider.GetRequiredService<DbCallCountingInterceptor>());
.AddInterceptors(provider.GetRequiredService<DbCallCountingInterceptor>());
});
}
}
//public static void AddDatabaseContexts(this IServiceCollection services, IWebHostEnvironment environment, ConfigurationManager configuration)
//{
// if (environment.IsDevelopment() || environment.IsDocker())
// {
// // Configure SQL Server (local)
// services.ConfigureLocalDatabaseContexts(configuration);
// }
// else
// {
// // Configure SQL Server (prod)
// var credential = new ChainedTokenCredential(new AzureDeveloperCliCredential(), new DefaultAzureCredential());
// configuration.AddAzureKeyVault(new Uri(configuration["AZURE_KEY_VAULT_ENDPOINT"] ?? ""), credential);

public static void AddCookieAuthentication(this IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Lax;
});
}
// services.AddDbContext<CatalogContext>((provider, options) =>
// {
// var connectionString = configuration[configuration["AZURE_SQL_CATALOG_CONNECTION_STRING_KEY"] ?? ""];
// options.UseSqlServer(connectionString, sqlOptions => sqlOptions.EnableRetryOnFailure())
// .AddInterceptors(provider.GetRequiredService<DbCallCountingInterceptor>());
// });
// services.AddDbContext<AppIdentityDbContext>((provider,options) =>
// {
// var connectionString = configuration[configuration["AZURE_SQL_IDENTITY_CONNECTION_STRING_KEY"] ?? ""];
// options.UseSqlServer(connectionString, sqlOptions => sqlOptions.EnableRetryOnFailure())
// .AddInterceptors(provider.GetRequiredService<DbCallCountingInterceptor>());
// });
// }
//}

public static void AddCustomHealthChecks(this IServiceCollection services)
{
services
.AddHealthChecks()
.AddCheck<ApiHealthCheck>("api_health_check", tags: new[] { "apiHealthCheck" })
.AddCheck<HomePageHealthCheck>("home_page_health_check", tags: new[] { "homePageHealthCheck" });
}
//public static void AddCookieAuthentication(this IServiceCollection services)
//{
// services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
// .AddCookie(options =>
// {
// options.Cookie.HttpOnly = true;
// options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
// options.Cookie.SameSite = SameSiteMode.Lax;
// });
//}

public static void AddBlazor(this IServiceCollection services, ConfigurationManager configuration)
{
var configSection = configuration.GetRequiredSection(BaseUrlConfiguration.CONFIG_NAME);
services.Configure<BaseUrlConfiguration>(configSection);
//public static void AddCustomHealthChecks(this IServiceCollection services)
//{
// services
// .AddHealthChecks()
// .AddCheck<ApiHealthCheck>("api_health_check", tags: new[] { "apiHealthCheck" })
// .AddCheck<HomePageHealthCheck>("home_page_health_check", tags: new[] { "homePageHealthCheck" });
//}

// Blazor Admin Required Services for Prerendering
services.AddScoped<HttpClient>(s => new HttpClient
{
BaseAddress = new Uri("https+http://blazoradmin")
});
//public static void AddBlazor(this IServiceCollection services, ConfigurationManager configuration)
//{
// var configSection = configuration.GetRequiredSection(BaseUrlConfiguration.CONFIG_NAME);
// services.Configure<BaseUrlConfiguration>(configSection);

// add blazor services
services.AddBlazoredLocalStorage();
services.AddServerSideBlazor();
services.AddScoped<ToastService>();
services.AddScoped<HttpService>();
services.AddBlazorServices();
}
// // Blazor Admin Required Services for Prerendering
// services.AddScoped<HttpClient>(s => new HttpClient
// {
// BaseAddress = new Uri("https+http://blazoradmin")
// });

// // add blazor services
// services.AddBlazoredLocalStorage();
// services.AddServerSideBlazor();
// services.AddScoped<ToastService>();
// services.AddScoped<HttpService>();
// services.AddBlazorServices();
//}
}
81 changes: 63 additions & 18 deletions src/Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.EntityFrameworkCore;
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
using Microsoft.eShopWeb.Infrastructure.Data;
using Microsoft.eShopWeb.Infrastructure.Identity;
using Microsoft.eShopWeb.Web;
using Microsoft.eShopWeb.Web.Areas.Identity.Helpers;
Expand All @@ -15,10 +17,24 @@
// Add service defaults & Aspire components.
builder.AddAspireServiceDefaults();

builder.Services.AddDatabaseContexts(builder.Environment, builder.Configuration);
// 🔥 READ FLAG
var useInMemory = builder.Configuration.GetValue<bool>("UseOnlyInMemoryDatabase");

// 🔥 DATABASE CONFIGURATION FIX
if (useInMemory)
{
builder.Services.AddDbContext<CatalogContext>(options =>
options.UseInMemoryDatabase("Catalog"));

builder.Services.AddDbContext<AppIdentityDbContext>(options =>
options.UseInMemoryDatabase("Identity"));
}
else
{
builder.Services.AddDatabaseContexts(builder.Environment, builder.Configuration);
}

builder.Services.AddCookieSettings();
builder.Services.AddCookieAuthentication();

builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDefaultUI()
Expand All @@ -38,7 +54,7 @@
options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
options.TokenEndpoint = "https://github.com/login/oauth/access_token";
options.UserInformationEndpoint = "https://api.github.com/user";
options.UsePkce = false; // PKCE not supported by GitHub
options.UsePkce = false;
options.SaveTokens = true;
options.ClaimsIssuer = "GitHub";
options.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
Expand All @@ -52,50 +68,70 @@
builder.Services.AddCoreServices(builder.Configuration);
builder.Services.AddWebServices(builder.Configuration);

// Add memory cache services
builder.Services.AddMemoryCache();

builder.Services.AddRouting(options =>
{
// Replace the type and the name used to refer to it with your own
// IOutboundParameterTransformer implementation
options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
});

builder.Services.AddMvc(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(
new SlugifyParameterTransformer()));

});

builder.Services.AddControllersWithViews();

builder.Services.AddRazorPages(options =>
{
options.Conventions.AuthorizePage("/Basket/Checkout");
});
builder.Services.AddHttpContextAccessor();

builder.Services.AddCustomHealthChecks();
builder.Services.AddHttpContextAccessor();

builder.Services.Configure<ServiceConfig>(config =>
{
config.Services = new List<ServiceDescriptor>(builder.Services);
config.Path = "/allservices";
});

builder.Services.AddBlazor(builder.Configuration);

builder.Services.AddMetronome();
builder.AddSeqEndpoint(connectionName: "seq");
//builder.AddSeqEndpoint(connectionName: "seq");

builder.Services.AddDatabaseDeveloperPageExceptionFilter();

var app = builder.Build();

app.Logger.LogInformation("App created...");

await app.SeedDatabaseAsync();
// 🔥 FIX: SEED DATABASE (IN-MEMORY AND SQL)
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var catalogContext = services.GetRequiredService<CatalogContext>();
var identityContext = services.GetRequiredService<AppIdentityDbContext>();
var logger = services.GetRequiredService<ILogger<Program>>();

if (useInMemory)
{
// Seed in-memory database
await CatalogContextSeed.SeedAsync(catalogContext, logger);

// Seed Identity database with users and roles
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
await AppIdentityDbContextSeed.SeedAsync(identityContext, userManager, roleManager);
}
else
{
// Seed SQL database
await app.SeedDatabaseAsync();
}
}

var catalogBaseUrl = builder.Configuration.GetValue(typeof(string), "CatalogBaseUrl") as string;

if (!string.IsNullOrEmpty(catalogBaseUrl))
{
app.Use((context, next) =>
Expand All @@ -105,9 +141,7 @@
});
}


app.UseCustomHealthChecks();

app.UseTroubleshootingMiddlewares();

app.UseHttpsRedirection();
Expand All @@ -118,13 +152,24 @@
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();

app.UseMiddleware<UserContextEnrichmentMiddleware>();

app.MapControllerRoute("default", "{controller:slugify=Home}/{action:slugify=Index}/{id?}");
app.MapRazorPages();
app.MapHealthChecks("home_page_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("homePageHealthCheck") });
app.MapHealthChecks("api_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("apiHealthCheck") });
//endpoints.MapBlazorHub("/admin");

app.MapHealthChecks("home_page_health_check", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("homePageHealthCheck")
});

app.MapHealthChecks("api_health_check", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("apiHealthCheck")
});

app.MapFallbackToFile("index.html");

app.Logger.LogInformation("LAUNCHING");

app.Run();
33 changes: 18 additions & 15 deletions src/Web/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
{
"baseUrls": {
"apiBase": "https://localhost:5099/api/"
},
"ConnectionStrings": {
"CatalogConnection": "Server=(localdb)\\mssqllocaldb;Integrated Security=true;Initial Catalog=Microsoft.eShopOnWeb.CatalogDb;",
"IdentityConnection": "Server=(localdb)\\mssqllocaldb;Integrated Security=true;Initial Catalog=Microsoft.eShopOnWeb.Identity;"
},
"CatalogBaseUrl": "",
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning",
"Microsoft": "Warning",
"System": "Warning"
"baseUrls": {
"apiBase": "https://localhost:5099/api/",
"webBase": "https://localhost:5001/"
},
"ConnectionStrings": {
"CatalogConnection": "Server=(localdb)\\mssqllocaldb;Integrated Security=true;Initial Catalog=Microsoft.eShopOnWeb.CatalogDb;",
"IdentityConnection": "Server=(localdb)\\mssqllocaldb;Integrated Security=true;Initial Catalog=Microsoft.eShopOnWeb.Identity;"
},
"CatalogBaseUrl": "",
"UseOnlyInMemoryDatabase": true,
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
//"Microsoft.eShopWeb": "Information",
//"CatalogItemListPagedEndpoint": "Information"
}
},
"AllowedHosts": "*"
}
}