Skip to content

Commit

Permalink
Asynchronized DbInitializer; improved debug logs
Browse files Browse the repository at this point in the history
  • Loading branch information
reidst committed Dec 11, 2023
1 parent 02e8b2c commit ef437c8
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 89 deletions.
137 changes: 72 additions & 65 deletions Data/DbInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,31 @@ public static class DbInitializer
}
}

public static void Initialize(ISeeGreenContext context)
public static async Task InitializeAsync(WebApplication app)
{
Console.WriteLine("[DebugLog][DbInitializer] Creating service scope...");
using var scope = app.Services.CreateScope();
Console.WriteLine("[DebugLog][DbInitializer] Getting ISeeGreenContext service...");
ISeeGreenContext context = scope.ServiceProvider.GetRequiredService<ISeeGreenContext>();
Console.WriteLine("[DebugLog][DbInitializer] Context retrieved.");

string seedDbPath = $"{Directory.GetCurrentDirectory()}/wwwroot/seed.db";
Console.WriteLine($"[DebugLog] seedDbPath='{seedDbPath}'");
Console.WriteLine($"[DebugLog][DbInitializer] seedDbPath='{seedDbPath}'");
using SqliteConnection connection = new($"Data Source={seedDbPath}");
Console.WriteLine("[DebugLog] connecting to SQLite seed database...");
connection.Open();
Console.WriteLine("[DebugLog] Connection opened.");
Console.WriteLine("[DebugLog][DbInitializer] connecting to SQLite seed database...");
await connection.OpenAsync();
Console.WriteLine("[DebugLog][DbInitializer] Connection opened.");

if (!context.Categories.Any())
{
Console.WriteLine("[DebugLog] Table 'Categories' is empty, adding seed data...");
Console.WriteLine("[DebugLog][DbInitializer] Table 'Categories' is empty, adding seed data...");
SqliteCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Categories;";
List<Categories> categories = new();
Console.WriteLine("[DebugLog] Executing SELECT command...");
using SqliteDataReader reader = command.ExecuteReader();
Console.WriteLine("[DebugLog] Reading data...");
while (reader.Read())
Console.WriteLine("[DebugLog][DbInitializer] Executing SELECT command...");
using SqliteDataReader reader = await command.ExecuteReaderAsync();
Console.WriteLine("[DebugLog][DbInitializer] Reading data...");
while (await reader.ReadAsync())
{
categories.Add(new Categories
{
Expand All @@ -46,23 +52,23 @@ public static void Initialize(ISeeGreenContext context)
APG4sort = DbCast<long>(reader["APG4sort"]),
});
}
Console.WriteLine($"[DebugLog] Adding {categories.Count} new Categories to the context...");
context.Categories.AddRange(categories.ToArray());
Console.WriteLine("[DebugLog] Saving changes...");
context.SaveChanges();
Console.WriteLine("[DebugLog] Changes saved.");
Console.WriteLine($"[DebugLog][DbInitializer] Adding {categories.Count} new Categories to the context...");
await context.Categories.AddRangeAsync(categories.ToArray());
Console.WriteLine("[DebugLog][DbInitializer] Saving changes...");
await context.SaveChangesAsync();
Console.WriteLine("[DebugLog][DbInitializer] Changes saved.");
}

if (!context.TaxonomicOrders.Any())
{
Console.WriteLine("[DebugLog] Table 'TaxonomicOrders' is empty, adding seed data...");
Console.WriteLine("[DebugLog][DbInitializer] Table 'TaxonomicOrders' is empty, adding seed data...");
SqliteCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM TaxonomicOrders;";
List<TaxonomicOrders> taxonomicOrders = new();
Console.WriteLine("[DebugLog] Executing SELECT command...");
using SqliteDataReader reader = command.ExecuteReader();
Console.WriteLine("[DebugLog] Reading data...");
while (reader.Read())
Console.WriteLine("[DebugLog][DbInitializer] Executing SELECT command...");
using SqliteDataReader reader = await command.ExecuteReaderAsync();
Console.WriteLine("[DebugLog][DbInitializer] Reading data...");
while (await reader.ReadAsync())
{
taxonomicOrders.Add(new TaxonomicOrders
{
Expand All @@ -81,23 +87,23 @@ public static void Initialize(ISeeGreenContext context)
SortLevel6 = (int)DbCast<long>(reader["SortLevel6"]),
});
}
Console.WriteLine($"[DebugLog] Adding {taxonomicOrders.Count} new TaxonomicOrders to the context...");
context.TaxonomicOrders.AddRange(taxonomicOrders.ToArray());
Console.WriteLine("[DebugLog] Saving changes...");
context.SaveChanges();
Console.WriteLine("[DebugLog] Changes saved.");
Console.WriteLine($"[DebugLog][DbInitializer] Adding {taxonomicOrders.Count} new TaxonomicOrders to the context...");
await context.TaxonomicOrders.AddRangeAsync(taxonomicOrders.ToArray());
Console.WriteLine("[DebugLog][DbInitializer] Saving changes...");
await context.SaveChangesAsync();
Console.WriteLine("[DebugLog][DbInitializer] Changes saved.");
}

if (!context.Families.Any())
{
Console.WriteLine("[DebugLog] Table 'Families' is empty, adding seed data...");
Console.WriteLine("[DebugLog][DbInitializer] Table 'Families' is empty, adding seed data...");
SqliteCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Families;";
List<Families> families = new();
Console.WriteLine("[DebugLog] Executing SELECT command...");
using SqliteDataReader reader = command.ExecuteReader();
Console.WriteLine("[DebugLog] Reading data...");
while (reader.Read())
Console.WriteLine("[DebugLog][DbInitializer] Executing SELECT command...");
using SqliteDataReader reader = await command.ExecuteReaderAsync();
Console.WriteLine("[DebugLog][DbInitializer] Reading data...");
while (await reader.ReadAsync())
{
families.Add(new Families
{
Expand All @@ -107,23 +113,23 @@ public static void Initialize(ISeeGreenContext context)
TaxonomicOrderID = DbCast<string?>(reader["TaxonomicOrderID"]),
});
}
Console.WriteLine($"[DebugLog] Adding {families.Count} new Families to the context...");
context.Families.AddRange(families.ToArray());
Console.WriteLine("[DebugLog] Saving changes...");
context.SaveChanges();
Console.WriteLine("[DebugLog] Changes saved.");
Console.WriteLine($"[DebugLog][DbInitializer] Adding {families.Count} new Families to the context...");
await context.Families.AddRangeAsync(families.ToArray());
Console.WriteLine("[DebugLog][DbInitializer] Saving changes...");
await context.SaveChangesAsync();
Console.WriteLine("[DebugLog][DbInitializer] Changes saved.");
}

if (!context.Genera.Any())
{
Console.WriteLine("[DebugLog] Table 'Genera' is empty, adding seed data...");
Console.WriteLine("[DebugLog][DbInitializer] Table 'Genera' is empty, adding seed data...");
SqliteCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Genera;";
List<Genera> genera = new();
Console.WriteLine("[DebugLog] Executing SELECT command...");
using SqliteDataReader reader = command.ExecuteReader();
Console.WriteLine("[DebugLog] Reading data...");
while (reader.Read())
Console.WriteLine("[DebugLog][DbInitializer] Executing SELECT command...");
using SqliteDataReader reader = await command.ExecuteReaderAsync();
Console.WriteLine("[DebugLog][DbInitializer] Reading data...");
while (await reader.ReadAsync())
{
genera.Add(new Genera
{
Expand All @@ -132,23 +138,23 @@ public static void Initialize(ISeeGreenContext context)
FamilyID = DbCast<string?>(reader["FamilyID"]),
});
}
Console.WriteLine($"[DebugLog] Adding {genera.Count} new Genera to the context...");
context.Genera.AddRange(genera.ToArray());
Console.WriteLine("[DebugLog] Saving changes...");
context.SaveChanges();
Console.WriteLine("[DebugLog] Changes saved.");
Console.WriteLine($"[DebugLog][DbInitializer] Adding {genera.Count} new Genera to the context...");
await context.Genera.AddRangeAsync(genera.ToArray());
Console.WriteLine("[DebugLog][DbInitializer] Saving changes...");
await context.SaveChangesAsync();
Console.WriteLine("[DebugLog][DbInitializer] Changes saved.");
}

if (!context.Taxa.Any())
{
Console.WriteLine("[DebugLog] Table 'Taxa' is empty, adding seed data...");
Console.WriteLine("[DebugLog][DbInitializer] Table 'Taxa' is empty, adding seed data...");
SqliteCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Taxa;";
List<Taxa> taxa = new();
Console.WriteLine("[DebugLog] Executing SELECT command...");
using SqliteDataReader reader = command.ExecuteReader();
Console.WriteLine("[DebugLog] Reading data...");
while (reader.Read())
Console.WriteLine("[DebugLog][DbInitializer] Executing SELECT command...");
using SqliteDataReader reader = await command.ExecuteReaderAsync();
Console.WriteLine("[DebugLog][DbInitializer] Reading data...");
while (await reader.ReadAsync())
{
taxa.Add(new Taxa
{
Expand All @@ -164,23 +170,23 @@ public static void Initialize(ISeeGreenContext context)
USDAsynonym = DbCast<string?>(reader["USDAsynonym"]),
});
}
Console.WriteLine($"[DebugLog] Adding {taxa.Count} new Taxa to the context...");
context.Taxa.AddRange(taxa.ToArray());
Console.WriteLine("[DebugLog] Saving changes...");
context.SaveChanges();
Console.WriteLine("[DebugLog] Changes saved.");
Console.WriteLine($"[DebugLog][DbInitializer] Adding {taxa.Count} new Taxa to the context...");
await context.Taxa.AddRangeAsync(taxa.ToArray());
Console.WriteLine("[DebugLog][DbInitializer] Saving changes...");
await context.SaveChangesAsync();
Console.WriteLine("[DebugLog][DbInitializer] Changes saved.");
}

if (!context.Synonyms.Any())
{
Console.WriteLine("[DebugLog] Table 'Synonyms' is empty, adding seed data...");
Console.WriteLine("[DebugLog][DbInitializer] Table 'Synonyms' is empty, adding seed data...");
SqliteCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Synonyms;";
List<Synonyms> synonyms = new();
Console.WriteLine("[DebugLog] Executing SELECT command...");
using SqliteDataReader reader = command.ExecuteReader();
Console.WriteLine("[DebugLog] Reading data...");
while (reader.Read())
Console.WriteLine("[DebugLog][DbInitializer] Executing SELECT command...");
using SqliteDataReader reader = await command.ExecuteReaderAsync();
Console.WriteLine("[DebugLog][DbInitializer] Reading data...");
while (await reader.ReadAsync())
{
synonyms.Add(new Synonyms
{
Expand All @@ -193,12 +199,13 @@ public static void Initialize(ISeeGreenContext context)
Authors = DbCast<string?>(reader["Authors"]),
});
}
Console.WriteLine($"[DebugLog] Adding {synonyms.Count} new Synonyms to the context...");
context.Synonyms.AddRange(synonyms.ToArray());
Console.WriteLine("[DebugLog] Saving changes...");
context.SaveChanges();
Console.WriteLine("[DebugLog] Changes saved.");
Console.WriteLine($"[DebugLog][DbInitializer] Adding {synonyms.Count} new Synonyms to the context...");
await context.Synonyms.AddRangeAsync(synonyms.ToArray());
Console.WriteLine("[DebugLog][DbInitializer] Saving changes...");
await context.SaveChangesAsync();
Console.WriteLine("[DebugLog][DbInitializer] Changes saved.");
}
Console.WriteLine("[DebugLog][DbInitializer] Successfully seeded database.");
}
}
}
49 changes: 25 additions & 24 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,71 +6,72 @@
var builder = WebApplication.CreateBuilder(args);

string aspNetCoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "";
Console.WriteLine($"[DebugLog] ASPNETCORE_ENVIRONMENT='{aspNetCoreEnvironment}'");
Console.WriteLine($"[DebugLog][Program] ASPNETCORE_ENVIRONMENT='{aspNetCoreEnvironment}'");

// Add services to the container.
builder.Services.AddRazorPages();

if (aspNetCoreEnvironment == "Production")
if (aspNetCoreEnvironment == "Development")
{
Console.WriteLine("[DebugLog] Production environment detected, using SQL Server connection string...");
Console.WriteLine("[DebugLog][Program] Development environment detected, using SQLite connection string...");
builder.Services.AddDbContext<ISeeGreenContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("ISeeGreenContextSQLite") ?? throw new InvalidOperationException("Connection string 'ISeeGreenContextSQLite' not found.")));
Console.WriteLine("[DebugLog][Program] ISeeGreenContext added.");
}
else
{
Console.WriteLine("[DebugLog][Program] Non-development environment detected, using SQL Server connection string...");
builder.Services.AddDbContext<ISeeGreenContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("AZURE_SQL_CONNECTIONSTRING") ?? throw new InvalidOperationException("Connection string 'AZURE_SQL_CONNECTIONSTRING' not found.")));

Console.WriteLine("[DebugLog] ISeeGreenContext added, adding StackExchangeRedisCache...");
Console.WriteLine("[DebugLog][Program] ISeeGreenContext added, adding StackExchangeRedisCache...");
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration["AZURE_REDIS_CONNECTIONSTRING"];
options.InstanceName = "SampleInstance";
});
Console.WriteLine("[DebugLog] AddStackExchangeRedisCache completed.");
}
else
{
Console.WriteLine("[DebugLog] Non-production environment detected, using SQLite connection string...");
builder.Services.AddDbContext<ISeeGreenContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("ISeeGreenContextSQLite") ?? throw new InvalidOperationException("Connection string 'ISeeGreenContextSQLite' not found.")));
Console.WriteLine("[DebugLog] ISeeGreenContext added.");
Console.WriteLine("[DebugLog][Program] AddStackExchangeRedisCache completed.");
}

Console.WriteLine("[DebugLog] Adding default identity service...");
Console.WriteLine("[DebugLog][Program] Adding default identity service...");
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ISeeGreenContext>();

Console.WriteLine("[DebugLog] Adding database developer page exception filter...");
Console.WriteLine("[DebugLog][Program] Adding database developer page exception filter...");
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

Console.WriteLine("[DebugLog] Building the WebApplication object...");
Console.WriteLine("[DebugLog][Program] Building the WebApplication object...");
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
Console.WriteLine("[DebugLog] Configuring HTTP request pipeline for development environment...");
Console.WriteLine("[DebugLog][Program] Configuring HTTP request pipeline for development environment...");
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
else
{
Console.WriteLine("[DebugLog] Configuring HTTP request pipeline for non-development environment...");
Console.WriteLine("[DebugLog][Program] Configuring HTTP request pipeline for non-development environment...");
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}

Console.WriteLine("[DebugLog] Creating service scope...");
Console.WriteLine("[DebugLog][Program] Creating service scope...");
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;

Console.WriteLine("[DebugLog] Getting ISeeGreenContext service...");
Console.WriteLine("[DebugLog][Program] Getting ISeeGreenContext service...");
var context = services.GetRequiredService<ISeeGreenContext>();
Console.WriteLine("[DebugLog] Ensuring database has been created...");
Console.WriteLine("[DebugLog][Program] Ensuring database has been created...");
context.Database.EnsureCreated();
// Console.WriteLine("[DebugLog] Starting DbInitializer.Initialize(ISeeGreenContext)...");
// DbInitializer.Initialize(context);
}
Console.WriteLine("[DebugLog] Services have been initialized.");
Console.WriteLine("[DebugLog][Program] Services have been initialized.");

Console.WriteLine("[DebugLog][Program] Starting asynchronous DbInitializer.Initialize(ISeeGreenContext)...");
Task _seedTask = DbInitializer.InitializeAsync(app);

app.UseHttpsRedirection();
app.UseStaticFiles();
Expand All @@ -81,5 +82,5 @@

app.MapRazorPages();

Console.WriteLine("[DebugLog] Running WebApplication...");
Console.WriteLine("[DebugLog][Program] Running WebApplication...");
app.Run();

0 comments on commit ef437c8

Please sign in to comment.