Skip to content

Commit

Permalink
template: misc minor improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
ascott18 committed Oct 1, 2024
1 parent 513db25 commit bf2bdec
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
.FormatType<byte[]>(ShaString)
.Exclude<DataProtectionKey>()
#if TrackingBase
.ExcludeProperty<TrackingBase>(x => new { x.CreatedBy, x.CreatedById, x.CreatedOn, x.ModifiedBy, x.ModifiedById, x.ModifiedOn })
.ExcludeProperty<TrackingBase>(x => new { x.CreatedById, x.CreatedOn, x.ModifiedById, x.ModifiedOn })
#endif
#if Identity
.Format<User>(x => x.PasswordHash, x => "<password changed>")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,20 @@

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 @@ -49,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 @@ -91,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 @@ -104,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 @@ -121,14 +121,14 @@

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.
Expand All @@ -155,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 @@ -197,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();
#endif
new DatabaseSeeder(db).Seed();
ActivatorUtilities.GetServiceOrCreateInstance<DatabaseSeeder>(serviceScope).Seed();
}

app.Run();
Expand Down

0 comments on commit bf2bdec

Please sign in to comment.