Skip to content
This repository has been archived by the owner on Apr 27, 2021. It is now read-only.

Commit

Permalink
Create /resetDatabase console command for failed automatic data migra…
Browse files Browse the repository at this point in the history
…tions. #21 - Implementation. Some Fixes
  • Loading branch information
Ruffo324 committed Feb 11, 2018
1 parent e2c31d9 commit 4ff8689
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 36 deletions.
4 changes: 2 additions & 2 deletions EvoMp/EvoMp.Core.ColorHandler/Server/ColorUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion EvoMp/EvoMp.Core.ConsoleHandler/Server/ConsoleOutput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ void WriteInput()
});
}

Thread.Sleep(10); // Debug
// Thread.Sleep(10); // Debug
}


Expand Down
10 changes: 8 additions & 2 deletions EvoMp/EvoMp.Core.Parameter/Server/ParameterHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
}
}

Expand Down
5 changes: 5 additions & 0 deletions EvoMp/EvoMp.Module.DbAccess/EvoMp.Module.DbAccess.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
</ItemGroup>
<ItemGroup>
<Compile Include="Server\DbAccess.cs" />
Expand All @@ -86,6 +87,10 @@
<Project>{f4b5eda5-1bfb-46fd-920f-febc1ce90ea1}</Project>
<Name>EvoMp.Core.Module</Name>
</ProjectReference>
<ProjectReference Include="..\EvoMp.Core.Parameter\EvoMp.Core.Parameter.csproj">
<Project>{EE63F684-46DB-466E-82B2-74F988F3DD4B}</Project>
<Name>EvoMp.Core.Parameter</Name>
</ProjectReference>
<ProjectReference Include="..\EvoMp.Module.CommandHandler\EvoMp.Module.CommandHandler.csproj">
<Project>{234B271E-7F73-42AA-97CF-C7D9630D841A}</Project>
<Name>EvoMp.Module.CommandHandler</Name>
Expand Down
102 changes: 80 additions & 22 deletions EvoMp/EvoMp.Module.DbAccess/Server/DbAccess.cs
Original file line number Diff line number Diff line change
@@ -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<string> 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<string> startArguments = Environment.GetCommandLineArgs().ToList();
startArguments.RemoveAt(0);

Process.Start(Environment.GetCommandLineArgs()[0], $"{string.Join(" ", startArguments)} -ResetDatabase");
Process.GetCurrentProcess().Kill();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,17 @@ protected override void OnModelCreating(DbModelBuilder modelBuilder)
public void FirstInit()
{
Database.SetInitializer<VehicleContext>(null);
// Database.SetInitializer<VehicleContext>(new DropCreateDatabaseAlways<VehicleContext>());

DbMigrationsConfiguration migratorConfig = new DbMigrationsConfiguration<VehicleContext>
{
AutomaticMigrationsEnabled = true,
AutomaticMigrationDataLossAllowed = true
AutomaticMigrationDataLossAllowed = true,
};

DbMigrator dbMigrator = new DbMigrator(migratorConfig);

dbMigrator.Update();
Database.Connection.Open();

}

#region Tables
Expand Down
6 changes: 1 addition & 5 deletions EvoMp/EvoMp.Module.VehicleHandler/Server/ExtendedVehicle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down

0 comments on commit 4ff8689

Please sign in to comment.