-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
628 lines (594 loc) · 23.1 KB
/
Copy pathProgram.cs
File metadata and controls
628 lines (594 loc) · 23.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MyWebApp.Data;
using MyWebApp.Services;
using MyWebApp.Options;
using MyWebApp.Models;
using Npgsql.EntityFrameworkCore.PostgreSQL;
using Microsoft.Extensions.Options;
using System.Linq;
using System.Collections.Generic;
using System;
using System.IO;
using System.Net.Http;
var builder = WebApplication.CreateBuilder(args);
var startupLogger = LoggerFactory.Create(b => b.AddConsole()).CreateLogger("Startup");
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddProvider(new FileLoggerProvider(Path.Combine(builder.Environment.ContentRootPath, "Logs", "app.log")));
// Allow connection string overrides from environment-specific files,
// environment variables, and command-line arguments
builder.Configuration
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
?? "Server=(localdb)\\mssqllocaldb;Database=MyWebAppDb;Trusted_Connection=True;MultipleActiveResultSets=true";
var provider = builder.Configuration["DatabaseProvider"] ?? "SqlServer";
var testOptions = new DbContextOptionsBuilder<ApplicationDbContext>();
switch (provider.ToLowerInvariant())
{
case "postgresql":
case "npgsql":
testOptions.UseNpgsql(connectionString);
break;
case "sqlite":
testOptions.UseSqlite(connectionString);
break;
default:
testOptions.UseSqlServer(connectionString);
break;
}
var needFallback = false;
try
{
using var testCtx = new ApplicationDbContext(testOptions.Options);
needFallback = !testCtx.Database.CanConnect();
}
catch (System.Data.Common.DbException)
{
needFallback = true;
}
catch (InvalidOperationException)
{
needFallback = true;
}
if (needFallback && provider.ToLowerInvariant() != "sqlite")
{
startupLogger.LogWarning("Falling back to SQLite due to database connection failure.");
provider = "Sqlite";
connectionString = "Data Source=mywebapp.db";
}
// Append provider specific defaults
if (provider.Equals("postgresql", StringComparison.OrdinalIgnoreCase) || provider.Equals("npgsql", StringComparison.OrdinalIgnoreCase))
{
if (!connectionString.Contains("Pooling", StringComparison.OrdinalIgnoreCase))
{
connectionString += (connectionString.EndsWith(";") ? string.Empty : ";") +
"Pooling=true;MinPoolSize=1;MaxPoolSize=20;ConnectionIdleLifetime=300;Max Auto Prepare=20;Auto Prepare Min Usages=2";
}
}
else if (provider.Equals("sqlite", StringComparison.OrdinalIgnoreCase))
{
if (!connectionString.Contains("Cache=", StringComparison.OrdinalIgnoreCase))
{
connectionString += (connectionString.EndsWith(";") ? string.Empty : ";") +
"Cache=Shared";
}
}
builder.Services.AddSingleton<QueryMetrics>();
builder.Services.AddSingleton<QueryLoggingInterceptor>();
builder.Services.AddDbContext<MyWebApp.Data.ApplicationDbContext>((sp, options) =>
{
switch (provider.ToLowerInvariant())
{
case "postgresql":
case "npgsql":
options.UseNpgsql(connectionString, npgsql =>
{
npgsql.EnableRetryOnFailure();
npgsql.CommandTimeout(60);
});
break;
case "sqlite":
options.UseSqlite(connectionString);
break;
default:
options.UseSqlServer(connectionString, sql =>
sql.EnableRetryOnFailure(3, TimeSpan.FromSeconds(30), null)
.CommandTimeout(60));
break;
}
options.AddInterceptors(sp.GetRequiredService<QueryLoggingInterceptor>());
}, optionsLifetime: ServiceLifetime.Singleton);
builder.Services.AddDbContextFactory<MyWebApp.Data.ApplicationDbContext>((sp, options) =>
{
switch (provider.ToLowerInvariant())
{
case "postgresql":
case "npgsql":
options.UseNpgsql(connectionString, npgsql =>
{
npgsql.EnableRetryOnFailure();
npgsql.CommandTimeout(60);
});
break;
case "sqlite":
options.UseSqlite(connectionString);
break;
default:
options.UseSqlServer(connectionString, sql =>
sql.EnableRetryOnFailure(3, TimeSpan.FromSeconds(30), null)
.CommandTimeout(60));
break;
}
options.AddInterceptors(sp.GetRequiredService<QueryLoggingInterceptor>());
});
builder.Services.AddControllersWithViews();
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient();
var sessionTimeout = builder.Configuration.GetValue<int>("Session:TimeoutMinutes", 30);
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(sessionTimeout);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<MyWebApp.Services.CacheService>();
builder.Services.AddSingleton<MyWebApp.Services.LayoutService>();
builder.Services.AddSingleton<MyWebApp.Services.TokenRenderService>();
builder.Services.AddSingleton<MyWebApp.Services.HtmlSanitizerService>();
builder.Services.AddSingleton<MyWebApp.Services.ContentProcessingService>();
builder.Services.AddSingleton<MyWebApp.Services.ThemeService>();
builder.Services.AddSingleton<MyWebApp.Services.CaptchaService>();
var smtpSection = builder.Configuration.GetSection("Smtp");
if (!string.IsNullOrWhiteSpace(smtpSection["Host"]))
{
builder.Services.Configure<MyWebApp.Options.SmtpOptions>(smtpSection);
builder.Services.AddSingleton<MyWebApp.Services.IEmailSender, MyWebApp.Services.SmtpEmailSender>();
}
else
{
builder.Services.AddSingleton<MyWebApp.Services.IEmailSender, MyWebApp.Services.LoggingEmailSender>();
}
builder.Services.AddScoped<MyWebApp.Services.SchemaValidator>();
builder.Services.AddOptions<MyWebApp.Options.AdminAuthOptions>()
.Bind(builder.Configuration.GetSection("AdminAuth"))
.Validate(o =>
!string.IsNullOrWhiteSpace(o.Username) &&
!string.IsNullOrWhiteSpace(o.Password),
"Admin credentials required");
builder.Services.AddSingleton<IConfigureOptions<AdminAuthOptions>, AdminAuthOptionsSetup>();
builder.Services.AddSingleton<IPostConfigureOptions<AdminAuthOptions>, AdminAuthOptionsSetup>();
var app = builder.Build();
// Ensure database is created and optimized
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var cacheService = scope.ServiceProvider.GetRequiredService<CacheService>();
try
{
if (db.Database.EnsureCreated())
{
app.Logger.LogInformation("Database schema created.");
}
if (provider.Equals("sqlite", StringComparison.OrdinalIgnoreCase))
{
db.Database.ExecuteSqlRaw("PRAGMA journal_mode=WAL;");
db.Database.ExecuteSqlRaw("PRAGMA synchronous=NORMAL;");
UpgradeDownloadFilesTable(db);
UpgradePageSectionsTable(db);
UpgradePagesTable(db);
UpgradeMediaItemsTable(db);
UpgradeBlockTemplatesTable(db);
UpgradeRolesTable(db);
UpgradePermissionsTable(db);
UpgradeLayoutHeader(db);
}
if (db.Database.CanConnect())
{
cacheService.WarmCache(db);
}
else
{
app.Logger.LogWarning("Could not connect to the database. Schema creation may have failed.");
}
}
catch (System.Data.Common.DbException ex)
{
app.Logger.LogError(ex, "Database initialization failed during startup.");
}
catch (InvalidOperationException ex)
{
app.Logger.LogError(ex, "Database initialization failed during startup.");
}
}
// Verify Quill client library is present
var quillFiles = new[] { "quill.js", "quill.snow.css" };
foreach (var name in quillFiles)
{
var path = Path.Combine(app.Environment.WebRootPath ?? "wwwroot",
"lib", "quill", "dist", name);
if (File.Exists(path))
continue;
app.Logger.LogWarning("Missing Quill asset at {Path}", path);
try
{
var dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
using var http = new HttpClient();
var url = $"https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/{name}";
var data = http.GetByteArrayAsync(url).GetAwaiter().GetResult();
File.WriteAllBytes(path, data);
app.Logger.LogInformation("Downloaded Quill asset {Name} from CDN", name);
}
catch (Exception ex)
{
app.Logger.LogWarning(ex, "Failed to download Quill asset {Name}", name);
}
}
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/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();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(
name: "pages",
pattern: "{*slug}",
defaults: new { controller = "Pages", action = "Show" });
app.Run();
static void UpgradeDownloadFilesTable(ApplicationDbContext db)
{
try
{
using var conn = db.Database.GetDbConnection();
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "PRAGMA table_info('DownloadFiles')";
using var reader = cmd.ExecuteReader();
var columns = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
while (reader.Read())
{
columns.Add(reader.GetString(1));
}
if (!columns.Contains("ContentType"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE DownloadFiles ADD COLUMN ContentType TEXT");
}
if (!columns.Contains("Data"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE DownloadFiles ADD COLUMN Data BLOB");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Schema upgrade failed: {ex.Message}");
}
}
static void UpgradePageSectionsTable(ApplicationDbContext db)
{
try
{
using var conn = db.Database.GetDbConnection();
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='PageSections'";
var exists = cmd.ExecuteScalar() != null;
if (!exists)
{
db.Database.ExecuteSqlRaw(@"CREATE TABLE PageSections (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
PageId INTEGER NOT NULL,
Zone TEXT NOT NULL,
SortOrder INTEGER NOT NULL DEFAULT 0,
Type INTEGER NOT NULL DEFAULT 0,
Html TEXT,
StartDate TEXT,
EndDate TEXT,
PermissionId INTEGER,
FOREIGN KEY(PageId) REFERENCES Pages(Id) ON DELETE CASCADE
)");
db.Database.ExecuteSqlRaw("CREATE INDEX IX_PageSections_PageId_Zone_SortOrder ON PageSections(PageId, Zone, SortOrder)");
db.Database.ExecuteSqlRaw(@"INSERT INTO PageSections (Id, PageId, Zone, SortOrder, Type, Html) VALUES
(1, 1, 'header', 0, 0, '<div class ""container-fluid nav-container""><a class=""logo"" href=""/"">Screen Area Recorder Pro</a><nav class=""site-nav""><a href=""/"">Home</a> {{nav}} <a href=""/Download"">Download</a> <a href=""/Home/Faq"">FAQ</a> <a href=""/Home/Privacy"">Privacy</a> <a href=""/Setup"">Setup</a> <a href=""/Account/Login"">Login</a></nav></div>'),
(2, 1, 'footer', 0, 0, '<div class ""container"">© 2025 - Screen Area Recorder Pro</div>')");
}
else
{
cmd.CommandText = "PRAGMA table_info('PageSections')";
using var reader = cmd.ExecuteReader();
var columns = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
while (reader.Read())
{
columns.Add(reader.GetString(1));
}
reader.Close();
if (columns.Contains("Area") && !columns.Contains("Zone"))
db.Database.ExecuteSqlRaw("ALTER TABLE PageSections RENAME COLUMN Area TO Zone");
if (!columns.Contains("SortOrder"))
db.Database.ExecuteSqlRaw("ALTER TABLE PageSections ADD COLUMN SortOrder INTEGER NOT NULL DEFAULT 0");
if (!columns.Contains("Type"))
db.Database.ExecuteSqlRaw("ALTER TABLE PageSections ADD COLUMN Type INTEGER NOT NULL DEFAULT 0");
if (!columns.Contains("StartDate"))
db.Database.ExecuteSqlRaw("ALTER TABLE PageSections ADD COLUMN StartDate TEXT");
if (!columns.Contains("EndDate"))
db.Database.ExecuteSqlRaw("ALTER TABLE PageSections ADD COLUMN EndDate TEXT");
if (!columns.Contains("PermissionId"))
db.Database.ExecuteSqlRaw("ALTER TABLE PageSections ADD COLUMN PermissionId INTEGER");
cmd.CommandText = "PRAGMA index_list('PageSections')";
using var idx = cmd.ExecuteReader();
var indexes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
while (idx.Read())
{
indexes.Add(idx.GetString(1));
}
idx.Close();
if (indexes.Contains("IX_PageSections_PageId_Area"))
db.Database.ExecuteSqlRaw("DROP INDEX IX_PageSections_PageId_Area");
if (!indexes.Contains("IX_PageSections_PageId_Zone_SortOrder"))
db.Database.ExecuteSqlRaw("CREATE INDEX IX_PageSections_PageId_Zone_SortOrder ON PageSections(PageId, Zone, SortOrder)");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Schema upgrade failed: {ex.Message}");
}
}
static void UpgradePagesTable(ApplicationDbContext db)
{
try
{
using var conn = db.Database.GetDbConnection();
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "PRAGMA table_info('Pages')";
using var reader = cmd.ExecuteReader();
var columns = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
while (reader.Read())
{
columns.Add(reader.GetString(1));
}
if (columns.Contains("HeaderHtml"))
db.Database.ExecuteSqlRaw("ALTER TABLE Pages DROP COLUMN HeaderHtml");
if (columns.Contains("BodyHtml"))
db.Database.ExecuteSqlRaw("ALTER TABLE Pages DROP COLUMN BodyHtml");
if (columns.Contains("FooterHtml"))
db.Database.ExecuteSqlRaw("ALTER TABLE Pages DROP COLUMN FooterHtml");
if (!columns.Contains("Layout"))
{
db.Database.ExecuteSqlRaw(
"ALTER TABLE Pages ADD COLUMN Layout TEXT NOT NULL DEFAULT 'single-column'");
}
if (!columns.Contains("MetaDescription"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE Pages ADD COLUMN MetaDescription TEXT");
}
if (!columns.Contains("MetaKeywords"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE Pages ADD COLUMN MetaKeywords TEXT");
}
if (!columns.Contains("OgTitle"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE Pages ADD COLUMN OgTitle TEXT");
}
if (!columns.Contains("OgDescription"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE Pages ADD COLUMN OgDescription TEXT");
}
if (!columns.Contains("IsPublished"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE Pages ADD COLUMN IsPublished INTEGER NOT NULL DEFAULT 0");
}
if (!columns.Contains("PublishDate"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE Pages ADD COLUMN PublishDate TEXT");
}
if (!columns.Contains("Category"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE Pages ADD COLUMN Category TEXT");
}
if (!columns.Contains("Tags"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE Pages ADD COLUMN Tags TEXT");
}
if (!columns.Contains("FeaturedImage"))
{
db.Database.ExecuteSqlRaw("ALTER TABLE Pages ADD COLUMN FeaturedImage TEXT");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Schema upgrade failed: {ex.Message}");
}
}
static void UpgradeMediaItemsTable(ApplicationDbContext db)
{
try
{
using var conn = db.Database.GetDbConnection();
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='MediaItems'";
var exists = cmd.ExecuteScalar() != null;
if (!exists)
{
db.Database.ExecuteSqlRaw(@"CREATE TABLE MediaItems (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
FileName TEXT NOT NULL,
FilePath TEXT NOT NULL,
ContentType TEXT,
Size INTEGER NOT NULL,
AltText TEXT,
Uploaded TEXT NOT NULL
)");
db.Database.ExecuteSqlRaw("CREATE INDEX IX_MediaItems_FileName ON MediaItems(FileName)");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Schema upgrade failed: {ex.Message}");
}
}
static void UpgradeBlockTemplatesTable(ApplicationDbContext db)
{
try
{
using var conn = db.Database.GetDbConnection();
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='BlockTemplates'";
var exists = cmd.ExecuteScalar() != null;
if (!exists)
{
db.Database.ExecuteSqlRaw(@"CREATE TABLE BlockTemplates (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL,
Html TEXT
)");
db.Database.ExecuteSqlRaw("CREATE UNIQUE INDEX IX_BlockTemplates_Name ON BlockTemplates(Name)");
}
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='BlockTemplateVersions'";
exists = cmd.ExecuteScalar() != null;
if (!exists)
{
db.Database.ExecuteSqlRaw(@"CREATE TABLE BlockTemplateVersions (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
BlockTemplateId INTEGER NOT NULL,
Html TEXT,
Created TEXT NOT NULL,
FOREIGN KEY(BlockTemplateId) REFERENCES BlockTemplates(Id) ON DELETE CASCADE
)");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Schema upgrade failed: {ex.Message}");
}
}
static void UpgradeRolesTable(ApplicationDbContext db)
{
try
{
using var conn = db.Database.GetDbConnection();
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='Roles'";
var exists = cmd.ExecuteScalar() != null;
if (!exists)
{
db.Database.ExecuteSqlRaw(@"CREATE TABLE Roles (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL
)");
db.Database.ExecuteSqlRaw("CREATE UNIQUE INDEX IX_Roles_Name ON Roles(Name)");
db.Database.ExecuteSqlRaw(@"INSERT INTO Roles (Id, Name) VALUES
(1, 'Admin'), (2, 'User'), (3, 'Moderator')");
}
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='UserRoles'";
exists = cmd.ExecuteScalar() != null;
if (!exists)
{
db.Database.ExecuteSqlRaw(@"CREATE TABLE UserRoles (
SiteUserId INTEGER NOT NULL,
RoleId INTEGER NOT NULL,
PRIMARY KEY(SiteUserId, RoleId),
FOREIGN KEY(SiteUserId) REFERENCES SiteUsers(Id) ON DELETE CASCADE,
FOREIGN KEY(RoleId) REFERENCES Roles(Id) ON DELETE CASCADE
)");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Schema upgrade failed: {ex.Message}");
}
}
static void UpgradePermissionsTable(ApplicationDbContext db)
{
try
{
using var conn = db.Database.GetDbConnection();
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='Permissions'";
var exists = cmd.ExecuteScalar() != null;
if (!exists)
{
db.Database.ExecuteSqlRaw(@"CREATE TABLE Permissions (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL
)");
db.Database.ExecuteSqlRaw("CREATE UNIQUE INDEX IX_Permissions_Name ON Permissions(Name)");
}
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='RolePermissions'";
exists = cmd.ExecuteScalar() != null;
if (!exists)
{
db.Database.ExecuteSqlRaw(@"CREATE TABLE RolePermissions (
RoleId INTEGER NOT NULL,
PermissionId INTEGER NOT NULL,
PRIMARY KEY(RoleId, PermissionId),
FOREIGN KEY(RoleId) REFERENCES Roles(Id) ON DELETE CASCADE,
FOREIGN KEY(PermissionId) REFERENCES Permissions(Id) ON DELETE CASCADE
)");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Schema upgrade failed: {ex.Message}");
}
}
static void UpgradeLayoutHeader(ApplicationDbContext db)
{
try
{
var layoutId = db.Pages
.AsNoTracking()
.Where(p => p.Slug == "layout")
.Select(p => p.Id)
.FirstOrDefault();
if (layoutId == 0)
return;
var section = db.PageSections
.FirstOrDefault(s => s.PageId == layoutId && s.Zone == "header");
if (section == null)
return;
if (section.Html != null &&
!section.Html.Contains("{{nav}}", StringComparison.OrdinalIgnoreCase))
{
if (section.Html.Contains("</nav>", StringComparison.OrdinalIgnoreCase))
{
section.Html = section.Html.Replace("</nav>", " {{nav}} </nav>", StringComparison.OrdinalIgnoreCase);
}
else
{
section.Html += " {{nav}}";
}
db.SaveChanges();
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Schema upgrade failed: {ex.Message}");
}
}