From 4ff8689de6fdc0846525701f9c747f075add0d5a Mon Sep 17 00:00:00 2001 From: Christian Groothoff Date: Sun, 11 Feb 2018 03:53:52 +0100 Subject: [PATCH] Create /resetDatabase console command for failed automatic data migrations. #21 - Implementation. Some Fixes --- .../Server/ColorUtils.cs | 4 +- .../Server/ConsoleOutput.cs | 2 +- .../Server/ParameterHandler.cs | 10 +- .../EvoMp.Module.DbAccess.csproj | 5 + .../EvoMp.Module.DbAccess/Server/DbAccess.cs | 102 ++++++++++++++---- .../Server/Entity/DoorStateDto.cs | 5 +- .../Server/Entity/VehicleContext.cs | 5 +- .../Server/ExtendedVehicle.cs | 6 +- 8 files changed, 103 insertions(+), 36 deletions(-) diff --git a/EvoMp/EvoMp.Core.ColorHandler/Server/ColorUtils.cs b/EvoMp/EvoMp.Core.ColorHandler/Server/ColorUtils.cs index e628f9a..c0ab312 100644 --- a/EvoMp/EvoMp.Core.ColorHandler/Server/ColorUtils.cs +++ b/EvoMp/EvoMp.Core.ColorHandler/Server/ColorUtils.cs @@ -227,8 +227,8 @@ void BuildControlString() case "...": // FillLineWithSpaces ansiString = ""; // full suffix added later - suffix += string.Empty.PadRight( - Console.WindowWidth - CleanUp(orignalMessage.Replace("\n", "")).Length); + int suffixLength = Console.WindowWidth - CleanUp(orignalMessage.Replace("\n", "")).Length; + suffix += string.Empty.PadRight(Math.Max(suffixLength, 0)); break; case "!00!": // Turn Code Parsing off codeParsingDisabled = true; diff --git a/EvoMp/EvoMp.Core.ConsoleHandler/Server/ConsoleOutput.cs b/EvoMp/EvoMp.Core.ConsoleHandler/Server/ConsoleOutput.cs index bc7b159..a91540f 100644 --- a/EvoMp/EvoMp.Core.ConsoleHandler/Server/ConsoleOutput.cs +++ b/EvoMp/EvoMp.Core.ConsoleHandler/Server/ConsoleOutput.cs @@ -447,7 +447,7 @@ void WriteInput() }); } - Thread.Sleep(10); // Debug + // Thread.Sleep(10); // Debug } diff --git a/EvoMp/EvoMp.Core.Parameter/Server/ParameterHandler.cs b/EvoMp/EvoMp.Core.Parameter/Server/ParameterHandler.cs index 590d7d9..b51e214 100644 --- a/EvoMp/EvoMp.Core.Parameter/Server/ParameterHandler.cs +++ b/EvoMp/EvoMp.Core.Parameter/Server/ParameterHandler.cs @@ -26,12 +26,18 @@ public static void LoadParams() try { for (int i = 1; i < args.Length; i += 2) - _commandLineArgs[args[i].Replace("-", "").ToLower()] = args[i + 1]; + { + if(i + 1 > args.Length) + _commandLineArgs[args[i].Replace("-", "").ToLower()] = args[i + 1]; + else + _commandLineArgs[args[i].Replace("-", "").ToLower()] = ""; + } } - catch (Exception) + catch (Exception e) { ConsoleOutput.WriteLine(ConsoleType.Error, $"Error in Command Line arguments! Len: {args.Length}" + $" Current args are: {string.Join(" ", args)}"); + ConsoleOutput.WriteException($"{e}"); } } diff --git a/EvoMp/EvoMp.Module.DbAccess/EvoMp.Module.DbAccess.csproj b/EvoMp/EvoMp.Module.DbAccess/EvoMp.Module.DbAccess.csproj index f8d97f9..57ce258 100644 --- a/EvoMp/EvoMp.Module.DbAccess/EvoMp.Module.DbAccess.csproj +++ b/EvoMp/EvoMp.Module.DbAccess/EvoMp.Module.DbAccess.csproj @@ -71,6 +71,7 @@ + @@ -86,6 +87,10 @@ {f4b5eda5-1bfb-46fd-920f-febc1ce90ea1} EvoMp.Core.Module + + {EE63F684-46DB-466E-82B2-74F988F3DD4B} + EvoMp.Core.Parameter + {234B271E-7F73-42AA-97CF-C7D9630D841A} EvoMp.Module.CommandHandler diff --git a/EvoMp/EvoMp.Module.DbAccess/Server/DbAccess.cs b/EvoMp/EvoMp.Module.DbAccess/Server/DbAccess.cs index 680fe7c..476bc04 100644 --- a/EvoMp/EvoMp.Module.DbAccess/Server/DbAccess.cs +++ b/EvoMp/EvoMp.Module.DbAccess/Server/DbAccess.cs @@ -1,29 +1,87 @@ using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Linq; using EvoMp.Core.ConsoleHandler.Server; +using EvoMp.Core.Module.Server; +using EvoMp.Core.Parameter.Server; using EvoMp.Module.CommandHandler; namespace EvoMp.Module.DbAccess.Server { - public class DbAccess : IDbAccess - { - public DbAccess(ICommandHandler commandHandler) - { - const string dataBaseName = "EvoMpGtMpServer"; - string dbConnectionString = Environment.GetEnvironmentVariable("EvoMp_dbConnectionString"); - - if (dbConnectionString == null) - Environment.SetEnvironmentVariable("NameOrConnectionString", - "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=" + dataBaseName + - ";Integrated Security=True;" + - "Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;" + - "MultiSubnetFailover=False;MultipleActiveResultSets = True;"); - else - Environment.SetEnvironmentVariable("NameOrConnectionString", - Environment.GetEnvironmentVariable("EvoMp_dbConnectionString")); - - // Write console output - ConsoleOutput.WriteLine(ConsoleType.Database, - $"Database: ~#8effa3~{dataBaseName}"); - } - } + public class DbAccess : IDbAccess + { + public DbAccess(ICommandHandler commandHandler) + { + // Get Database name from Parameter + ParameterHandler.SetDefault("DatabaseName", "EvoMpGtMpServer"); + string dataBaseName = ParameterHandler.GetValue("DatabaseName"); + + SetConnectionString(); + + void SetConnectionString() + { + string dbConnectionString = Environment.GetEnvironmentVariable("EvoMp_dbConnectionString"); + + if (dbConnectionString == null) + Environment.SetEnvironmentVariable("NameOrConnectionString", + "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=" + dataBaseName + + ";Integrated Security=True;" + + "Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;" + + "MultiSubnetFailover=False;MultipleActiveResultSets = True;"); + else + Environment.SetEnvironmentVariable("NameOrConnectionString", + Environment.GetEnvironmentVariable("EvoMp_dbConnectionString")); + } + + // Init reset procedure if database reset wanted. + if (ParameterHandler.GetValue("ResetDatabase") != null) + { + string sqlCommandText = $"DROP DATABASE {dataBaseName}"; + dataBaseName = "Reset"; + SetConnectionString(); + string nameOrConnectionString = Environment.GetEnvironmentVariable("NameOrConnectionString"); + if (nameOrConnectionString != null) + { + SqlConnection connection = new SqlConnection(nameOrConnectionString); + connection.Open(); + SqlCommand sqlCommand = new SqlCommand(sqlCommandText, connection); + sqlCommand.ExecuteNonQuery(); + connection.Close(); + } + } + + // Write console output + ConsoleOutput.WriteLine(ConsoleType.Database, + $"Database: ~#8effa3~{dataBaseName}"); + + // If Database reset -> restart + Shared.OnCoreStartupCompleted += () => + { + if (ParameterHandler.GetValue("ResetDatabase") == null) + return; + + List startArguments = Environment.GetCommandLineArgs().ToList(); + startArguments.RemoveAt(0); + + Process.Start(Environment.GetCommandLineArgs()[0], + $"{string.Join(" ", startArguments).Replace("-ResetDatabase", "")}"); + Process.GetCurrentProcess().Kill(); + }; + } + + + [ConsoleCommand("/resetDatabase", + importantCommand: true, description: + "Wipes the complete Database. (Server restarts 2 Times to fool the Entity Framework Migrations.)")] + public void ResetDatabaseConsoleCommand() + { + List startArguments = Environment.GetCommandLineArgs().ToList(); + startArguments.RemoveAt(0); + + Process.Start(Environment.GetCommandLineArgs()[0], $"{string.Join(" ", startArguments)} -ResetDatabase"); + Process.GetCurrentProcess().Kill(); + } + } } diff --git a/EvoMp/EvoMp.Module.VehicleHandler/Server/Entity/DoorStateDto.cs b/EvoMp/EvoMp.Module.VehicleHandler/Server/Entity/DoorStateDto.cs index f295885..7caadc1 100644 --- a/EvoMp/EvoMp.Module.VehicleHandler/Server/Entity/DoorStateDto.cs +++ b/EvoMp/EvoMp.Module.VehicleHandler/Server/Entity/DoorStateDto.cs @@ -7,13 +7,16 @@ namespace EvoMp.Module.VehicleHandler.Server.Entity [Table("VehicleDoorStates")] public class DoorStateDto { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.None)] + [Column(Order = 0)] public int VehicleId { get; set; } [ForeignKey("VehicleId")] - [Column(Order = 0)] public VehicleDto Vehicle { get; set; } [Key] + [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("Door", Order = 1)] public DoorState Door { get; set; } diff --git a/EvoMp/EvoMp.Module.VehicleHandler/Server/Entity/VehicleContext.cs b/EvoMp/EvoMp.Module.VehicleHandler/Server/Entity/VehicleContext.cs index 4655160..8e25597 100644 --- a/EvoMp/EvoMp.Module.VehicleHandler/Server/Entity/VehicleContext.cs +++ b/EvoMp/EvoMp.Module.VehicleHandler/Server/Entity/VehicleContext.cs @@ -25,18 +25,17 @@ protected override void OnModelCreating(DbModelBuilder modelBuilder) public void FirstInit() { Database.SetInitializer(null); +// Database.SetInitializer(new DropCreateDatabaseAlways()); DbMigrationsConfiguration migratorConfig = new DbMigrationsConfiguration { AutomaticMigrationsEnabled = true, - AutomaticMigrationDataLossAllowed = true + AutomaticMigrationDataLossAllowed = true, }; DbMigrator dbMigrator = new DbMigrator(migratorConfig); - dbMigrator.Update(); Database.Connection.Open(); - } #region Tables diff --git a/EvoMp/EvoMp.Module.VehicleHandler/Server/ExtendedVehicle.cs b/EvoMp/EvoMp.Module.VehicleHandler/Server/ExtendedVehicle.cs index 736a345..a2f5eab 100644 --- a/EvoMp/EvoMp.Module.VehicleHandler/Server/ExtendedVehicle.cs +++ b/EvoMp/EvoMp.Module.VehicleHandler/Server/ExtendedVehicle.cs @@ -125,11 +125,7 @@ public void Save() catch (Exception e) { ConsoleOutput.WriteLine(ConsoleType.Database, "Error on Saving ExtendedVehicle!"); - ConsoleOutput.WriteException(e.Message + e.StackTrace); - - if (e.InnerException != null) - ConsoleOutput.WriteException(e.InnerException.Message + e.InnerException.StackTrace); - + ConsoleOutput.WriteException($"{e}"); // Rollback changes on failure contextTransaction.Rollback(); }