using Microsoft.Win32; using MySql.Data.Entity; using Step.Database.Controllers; using Step.Database.Migrations; using Step.Model.DatabaseModels; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.IO; using System.Linq; using static Step.Config.ServerConfig; using static Step.Model.Constants; using static Step.Utils.ExceptionManager; namespace Step.Database { [DbConfigurationType(typeof(MySqlEFConfiguration))] public class DatabaseContext : DbContext { public DbSet Users { get; set; } public DbSet Machines { get; set; } public DbSet MachinesUsers { get; set; } public DbSet Roles { get; set; } public DbSet FunctionsAccess { get; set; } public DbSet Sessions { get; set; } public DbSet Maintenances { get; set; } public DbSet PerformedMaintenances { get; set; } public static string CONNECTION_STRING = "Server = " + ServerStartupConfig.DatabaseAddress + "; Database=" + DATABASE_NAME +";Uid="+ DATABASE_USER +";Pwd="+ DATABASE_PWD +";"; public DatabaseContext() : base(CONNECTION_STRING) { } public static DatabaseContext Create() { return new DatabaseContext(); } public static void SetUpDbConnectionAndDbConfig() { try { System.Data.Entity.Database.SetInitializer(null); // Make sure database exists. using (var db = new DatabaseContext()) { db.Database.Initialize(false); } var migrator = new DbMigrator(new Configuration()); if (migrator.GetPendingMigrations().Any()) { // Run migrations and seed. migrator.Update(); } FindOrCreateMachineUniqueId(); using (MaintenancesController maintenancesController = new MaintenancesController()) { maintenancesController.CheckDifferencesFromDbAndXml(); } // Get functionality and PLC default false functionality using (FunctionsAccessController functionsAccess = new FunctionsAccessController()) { FunctionsAccessConfig = functionsAccess.FindAll(); AllFunctionalityDisabled = functionsAccess.FindAllFunctionsAndDisableAll(); } } catch (MySql.Data.MySqlClient.MySqlException ex) { if (ex.Number == 0) { //dbContext.Database.Initialize(true); } else if (ex.Number == 1042) // Can't find MySQLServer { Manage(ERROR_LEVEL.FATAL, ex); } else { Manage(ERROR_LEVEL.ERROR, ex); } } catch (Exception ex) { Manage(ERROR_LEVEL.FATAL, ex); } } public static void FindOrCreateMachineUniqueId() { // Find machine unique id in the register string uniqueId = ReadUniqueIdFromRegister(); // If not found if (uniqueId == null || uniqueId == "") { if (!File.Exists("uniqueid.txt")) { uniqueId = Guid.NewGuid().ToString(); // Save uinique id into file File.WriteAllText("uniqueid.txt", uniqueId); // Save uinique id in the registry WriteUniqueIdIntoRegister(uniqueId); } else { // Find machine unique id in the storage file uniqueId = File.ReadAllText("uniqueid.txt"); // If null or empty if (uniqueId == null || uniqueId == "") { // Delete empty file and recreate File.Delete(uniqueId); FindOrCreateMachineUniqueId(); return; } else { WriteUniqueIdIntoRegister(uniqueId); } } } // Set machine info into static server config using (MachinesController machinesController = new MachinesController()) { MachineConfig = machinesController.FindMachineByUniqueId(uniqueId); if (MachineConfig == null) { // Create Machine inside database MachineConfig = machinesController.Create(uniqueId); using (UsersController usersController = new UsersController()) { // Create default CMS user usersController.CreateCmsDefaultUserIfNotExists(MachineConfig.MachineId); } } else { // if config name is different than dabase name, update db if (MachineConfig.Model != NcConfig.NcName) machinesController.UpdateMachineName(MachineConfig.MachineId, NcConfig.NcName); } } } private static void WriteUniqueIdIntoRegister(string uniqueId) { // Get path to the HKEY_LOCAL_MACHINE/SOFTWARE RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE", true); // Create or get ..//CMS/Step subkey key = key.CreateSubKey("Cms").CreateSubKey("Step"); // Set machine unique id Key key.SetValue(REGISTER_MACHINE_ID_KEY_NAME, uniqueId); } private static string ReadUniqueIdFromRegister() { // Get path to the HKEY_LOCAL_MACHINE/SOFTWARE RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE", true); // Get ..//CMS/Step subkey key = key.CreateSubKey("Cms").CreateSubKey("Step"); // Return value return (string)key.GetValue(REGISTER_MACHINE_ID_KEY_NAME); } } }