Fixed removing temp. database file when importing JSON

This commit is contained in:
Thorsten Sommer 2023-02-11 23:03:14 +01:00
parent 18fd1faedd
commit 96823aa948
Signed by: tsommer
GPG Key ID: 371BBA77A02C0108
3 changed files with 46 additions and 32 deletions

View File

@ -1,9 +1,9 @@
using DataModel.Database; using System.Diagnostics;
using DataModel.Database;
using DataModel.Database.Common; using DataModel.Database.Common;
using DataModel.MigrationScripts; using DataModel.MigrationScripts;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DataModel; namespace DataModel;
@ -13,12 +13,10 @@ public static class Setup
private const string DB_READ_WRITE_CREATE_MODE = "ReadWriteCreate"; private const string DB_READ_WRITE_CREATE_MODE = "ReadWriteCreate";
private static string USED_DATA_FILE = string.Empty; private static string USED_DATA_FILE = string.Empty;
private static SetupMaintenance SETUP_MAINTENANCE = new(); public static SetupMaintenance SETUP_MAINTENANCE = new();
public static string DataFile => Setup.USED_DATA_FILE; public static string DataFile => Setup.USED_DATA_FILE;
public static SetupMaintenance Maintenance => Setup.SETUP_MAINTENANCE;
/// <summary> /// <summary>
/// Tries to migrate the database. /// Tries to migrate the database.
/// </summary> /// </summary>
@ -44,15 +42,18 @@ public static class Setup
/// </summary> /// </summary>
public static async Task ImportDataAndAddDatabase(this IServiceCollection serviceCollection, string path2JSONFile) public static async Task ImportDataAndAddDatabase(this IServiceCollection serviceCollection, string path2JSONFile)
{ {
Console.WriteLine($"Importing the data from the JSON file '{path2JSONFile}' into a new database.");
var tempPath = Path.GetTempFileName(); var tempPath = Path.GetTempFileName();
Setup.USED_DATA_FILE = tempPath; Console.WriteLine($"The temporary database file is: {tempPath}");
Setup.SETUP_MAINTENANCE = new(path2JSONFile, true);
serviceCollection.AddDbContext<DataContext>(options => options.UseSqlite($"Filename={tempPath};Mode={DB_READ_WRITE_CREATE_MODE};"), ServiceLifetime.Transient); serviceCollection.AddDbContext<DataContext>(options => options.UseSqlite($"Filename={tempPath};Mode={DB_READ_WRITE_CREATE_MODE};"), ServiceLifetime.Transient);
// Get the database service: // Get the database service:
await using var serviceProvider = serviceCollection.BuildServiceProvider(); await using var serviceProvider = serviceCollection.BuildServiceProvider();
var dbContext = serviceProvider.GetRequiredService<DataContext>(); var dbContext = serviceProvider.GetRequiredService<DataContext>();
Setup.USED_DATA_FILE = tempPath;
Setup.SETUP_MAINTENANCE = new(tempPath, true);
// Migrate the database to create the tables etc.: // Migrate the database to create the tables etc.:
await Setup.PerformDataMigration(dbContext); await Setup.PerformDataMigration(dbContext);
@ -128,17 +129,29 @@ public static class Setup
return dbContext; return dbContext;
} }
public readonly record struct SetupMaintenance(string PathToDataFile = "", bool RemoveTempDatabaseAfterwards = false) : IDisposable public readonly record struct SetupMaintenance(string PathToDataFile = "", bool RemoveTempDatabaseAfterwards = false) : IDisposable
{ {
public void Dispose() public void Dispose()
{ {
if (!this.RemoveTempDatabaseAfterwards) if (!this.RemoveTempDatabaseAfterwards)
return; return;
Console.WriteLine("Removing the temporary database file...");
try try
{ {
File.Delete(this.PathToDataFile); var process = new Process
{
StartInfo = new()
{
FileName = "cmd.exe",
Arguments = $@"/C del /Q /F ""{Setup.SETUP_MAINTENANCE.PathToDataFile}""",
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
Console.WriteLine($"The temporary database file '{this.PathToDataFile}' has been removed.");
} }
catch(Exception e) catch(Exception e)
{ {

View File

@ -2,5 +2,5 @@
public static class Version public static class Version
{ {
public static string Text => $"v0.8.2 (2023-02-11), .NET {Environment.Version}"; public static string Text => $"v0.8.3 (2023-02-11), .NET {Environment.Version}";
} }

View File

@ -60,30 +60,31 @@ internal static class Program
} }
}); });
// Tear down the setup:
using var setupMaintenance = Setup.Maintenance;
// Get the host out of the DI system: // Get the host out of the DI system:
var host = builder.Build(); using (var host = builder.Build())
// Create a service scope:
using (var scope = host.Services.CreateScope())
{ {
// Get a service provider: // Create a service scope:
SERVICE_PROVIDER = scope.ServiceProvider; using (var scope = host.Services.CreateScope())
// Set the service provider to the processor:
ProcessorMeta.ServiceProvider = SERVICE_PROVIDER;
// Apply database migrations:
using (var database = SERVICE_PROVIDER.GetRequiredService<DataContext>())
Setup.PerformDataMigration(database).Wait();
// Start the app:
do
{ {
Application.Run(new Main()); // Get a service provider:
} while (Program.RestartMainApp); SERVICE_PROVIDER = scope.ServiceProvider;
// Set the service provider to the processor:
ProcessorMeta.ServiceProvider = SERVICE_PROVIDER;
// Apply database migrations:
using (var database = SERVICE_PROVIDER.GetRequiredService<DataContext>())
Setup.PerformDataMigration(database).Wait();
// Start the app:
do
{
Application.Run(new Main());
} while (Program.RestartMainApp);
}
} }
// Tear down the setup:
AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => Setup.SETUP_MAINTENANCE.Dispose();
} }
} }