Skip to content

Commit

Permalink
fix: additional template fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
ascott18 committed Sep 27, 2024
1 parent b2e7b34 commit 281c535
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@
"**/AuthenticationConfiguration.cs",
"**/Forbidden.vue",
"**/UserAvatar.vue",
"**/UserProfile.vue",
"**/SignIn.*",
"**/SignOut.*",
"**/AppClaimTypes.cs",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,29 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
#if Identity
using Coalesce.Starter.Vue.Web.Auth;
#endif
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
// Explicit declaration prevents ASP.NET Core from erroring if wwwroot doesn't exist at startup:
WebRootPath = "wwwroot"
Args = args,
// Explicit declaration prevents ASP.NET Core from erroring if wwwroot doesn't exist at startup:
WebRootPath = "wwwroot"
});

builder.Logging
.AddConsole()
// Filter out Request Starting/Request Finished noise:
.AddFilter<ConsoleLoggerProvider>("Microsoft.AspNetCore.Hosting.Diagnostics", LogLevel.Warning);
.AddConsole()
// Filter out Request Starting/Request Finished noise:
.AddFilter<ConsoleLoggerProvider>("Microsoft.AspNetCore.Hosting.Diagnostics", LogLevel.Warning);

builder.Configuration
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile("appsettings.localhost.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile("appsettings.localhost.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();

#region Configure Services

Expand All @@ -47,40 +49,40 @@
#if AppInsights
services.AddApplicationInsightsTelemetry(b =>
{
b.ConnectionString = builder.Configuration["ApplicationInsights:ConnectionString"];
b.ConnectionString = builder.Configuration["ApplicationInsights:ConnectionString"];
});
services.AddSingleton<ITelemetryInitializer, AppInsightsTelemetryEnricher>();
services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) =>
{
module.EnableSqlCommandTextInstrumentation = true;
module.EnableSqlCommandTextInstrumentation = true;
});
// App insights filters all logs to Warning by default. We want to include our own logging.
builder.Logging.AddFilter<ApplicationInsightsLoggerProvider>("Coalesce.Starter.Vue", LogLevel.Information);
#endif


services.AddDbContext<AppDbContext>(options => options
.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"), opt => opt
.EnableRetryOnFailure()
.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)
)
// Ignored because it interferes with the construction of Coalesce IncludeTrees via .Include()
.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.NavigationBaseIncludeIgnored))
.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"), opt => opt
.EnableRetryOnFailure()
.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)
)
// Ignored because it interferes with the construction of Coalesce IncludeTrees via .Include()
.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.NavigationBaseIncludeIgnored))
);

services.AddCoalesce<AppDbContext>();

services.AddDataProtection()
.PersistKeysToDbContext<AppDbContext>();
.PersistKeysToDbContext<AppDbContext>();

services
.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

#if Identity
builder.ConfigureAuthentication();
Expand All @@ -89,8 +91,8 @@
#if OpenAPI
services.AddSwaggerGen(c =>
{
c.AddCoalesce();
c.SwaggerDoc("current", new OpenApiInfo { Title = "Current API", Version = "current" });
c.AddCoalesce();
c.SwaggerDoc("current", new OpenApiInfo { Title = "Current API", Version = "current" });
});
#endif

Expand All @@ -102,9 +104,9 @@
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(x =>
{
var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext;
var factory = x.GetRequiredService<IUrlHelperFactory>();
return factory.GetUrlHelper(actionContext!);
var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext;
var factory = x.GetRequiredService<IUrlHelperFactory>();
return factory.GetUrlHelper(actionContext!);
});

services.AddScoped<InvitationService>();
Expand All @@ -119,31 +121,31 @@

if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDeveloperExceptionPage();

app.UseViteDevelopmentServer(c =>
{
c.DevServerPort = 5002;
});
app.UseViteDevelopmentServer(c =>
{
c.DevServerPort = 5002;
});

app.MapCoalesceSecurityOverview("coalesce-security");
app.MapCoalesceSecurityOverview("coalesce-security");

#if (!Identity)
// TODO: Dummy authentication for initial development.
// Replace this with a proper authentication scheme like
// Windows Authentication, or an OIDC provider, or something else.
// If you wanted to use ASP.NET Core Identity, you're recommended
// to keep the "--Identity" parameter to the Coalesce template enabled.
app.Use(async (context, next) =>
{
Claim[] claims = [new Claim(ClaimTypes.Name, "developmentuser")];
var identity = new ClaimsIdentity(claims, "dummy-auth");
context.User = new ClaimsPrincipal(identity);
await next.Invoke();
});
// End Dummy Authentication.
// TODO: Dummy authentication for initial development.
// Replace this with a proper authentication scheme like
// Windows Authentication, or an OIDC provider, or something else.
// If you wanted to use ASP.NET Core Identity, you're recommended
// to keep the "--Identity" parameter to the Coalesce template enabled.
app.Use(async (context, next) =>
{
Claim[] claims = [new Claim(ClaimTypes.Name, "developmentuser")];
var identity = new ClaimsIdentity(claims, "dummy-auth");
context.User = new ClaimsPrincipal(identity);
await next.Invoke();
});
// End Dummy Authentication.
#endif
}

Expand All @@ -153,30 +155,30 @@
var containsFileHashRegex = new Regex(@"[.-][0-9a-zA-Z-_]{8}\.[^\.]*$", RegexOptions.Compiled);
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
// vite puts 8-char hashes before the file extension.
// Use this to determine if we can send a long-term cache duration.
if (containsFileHashRegex.IsMatch(ctx.File.Name))
{
ctx.Context.Response.GetTypedHeaders().CacheControl = new() { Public = true, MaxAge = TimeSpan.FromDays(30) };
}
}
OnPrepareResponse = ctx =>
{
// vite puts 8-char hashes before the file extension.
// Use this to determine if we can send a long-term cache duration.
if (containsFileHashRegex.IsMatch(ctx.File.Name))
{
ctx.Context.Response.GetTypedHeaders().CacheControl = new() { Public = true, MaxAge = TimeSpan.FromDays(30) };
}
}
});

// For all requests that aren't to static files, disallow caching by default.
// Individual endpoints may override this.
app.Use(async (context, next) =>
{
context.Response.GetTypedHeaders().CacheControl = new() { NoCache = true, NoStore = true };
await next();
context.Response.GetTypedHeaders().CacheControl = new() { NoCache = true, NoStore = true };
await next();
});

#if OpenAPI
app.MapSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/current/swagger.json", "Current API");
c.SwaggerEndpoint("/swagger/current/swagger.json", "Current API");
});
#endif

Expand All @@ -195,18 +197,18 @@
// Initialize/migrate database.
using (var scope = app.Services.CreateScope())
{
var serviceScope = scope.ServiceProvider;
var serviceScope = scope.ServiceProvider;

// Run database migrations.
using var db = serviceScope.GetRequiredService<AppDbContext>();
db.Database.SetCommandTimeout(TimeSpan.FromMinutes(10));
// Run database migrations.
using var db = serviceScope.GetRequiredService<AppDbContext>();
db.Database.SetCommandTimeout(TimeSpan.FromMinutes(10));
#if KeepTemplateOnly
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
#else
db.Database.Migrate();
db.Database.Migrate();
#endif
new DatabaseSeeder(db).Seed();
new DatabaseSeeder(db).Seed();
}

app.Run();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const router = createRouter({
props: true,
component: () => import("./views/UserProfile.vue"),
},
// #endif
//#endif

// Coalesce admin routes
{
Expand Down Expand Up @@ -78,7 +78,7 @@ function titledAdminPage<
| typeof CAdminEditorPage
//#if AuditLogs
| typeof CAdminAuditLogPage,
//#endif
//#endif
>(component: T) {
return defineComponent({
setup() {
Expand Down

0 comments on commit 281c535

Please sign in to comment.