Files
2021-02-01 14:33:49 +01:00

254 lines
8.9 KiB
C#

using Microsoft.Win32;
using MySql.Data.Entity;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Globalization;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using Thermo.Active.Database.Controllers;
using Thermo.Active.Database.Migrations;
using Thermo.Active.Model.DatabaseModels;
using static Thermo.Active.Config.ServerConfig;
using static Thermo.Active.Model.Constants;
using static Thermo.Active.Utils.ExceptionManager;
namespace Thermo.Active.Database
{
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class DatabaseContext : DbContext
{
public DbSet<UserModel> Users { get; set; }
public DbSet<MachineModel> Machines { get; set; }
public DbSet<MachineUserModel> MachinesUsers { get; set; }
public DbSet<RoleModel> Roles { get; set; }
public DbSet<FunctionAccessModel> FunctionsAccess { get; set; }
public DbSet<SessionModel> Sessions { get; set; }
public DbSet<FavoriteUserSoftkeyModel> FavoriteUserSoftkeys { get; set; }
public DbSet<KeyboardUserSoftKeyModel> KeyboardUserSoftkeys { get; set; }
// Maintenances
public DbSet<MaintenanceModel> Maintenances { get; set; }
public DbSet<PerformedMaintenanceModel> PerformedMaintenances { get; set; }
public DbSet<MaintenanceNoteModel> MaintenancesNotes { get; set; }
public DbSet<MaintenanceFileModel> MaintenanceFiles { get; set; }
// Tool tables
public DbSet<DbNcFamilyModel> Families { get; set; }
public DbSet<QueueItemsModel> Queue { get; set; }
// Alarms
public DbSet<AlarmDescriptionsModel> AlarmDescriptions { get; set; }
public DbSet<AlarmOccurrencesModel> AlarmOccurrences { get; set; }
public DbSet<AlarmUserModel> AlarmUsers { get; set; }
public DbSet<AlarmNoteModel> AlarmsNotes { get; set; }
public DbSet<AlarmFileModel> AlarmFiles { get; set; }
// thermo!
public DbSet<ProdInfoModel> ProdInfo { get; set; }
// Create migration string
public static string CONNECTION_STRING = "Server = " + "localhost" + "; Database=" + DATABASE_NAME + ";Uid=" + DATABASE_USER + ";Pwd=" + DATABASE_PWD + ";";
// 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 bool SetUpDbConnectionAndDbConfig()
{
try
{
String serviceName = getDbServiceName();
if(serviceName.Equals(""))
{
ManageError(ERROR_LEVEL.FATAL, "Database SQL service not found", true);
return false;
}
String serviceRedisName = getRedisServiceName();
if (serviceRedisName.Equals(""))
{
ManageError(ERROR_LEVEL.FATAL, "Database REDIS service not found", true);
return false;
}
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromSeconds(DATABASE_PROCESS_TIMEOUT);
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch (Exception ex)
{
ManageError(ERROR_LEVEL.FATAL, "Database SQL not started", true);
return false;
}
service = new ServiceController(serviceRedisName);
try
{
TimeSpan timeout = TimeSpan.FromSeconds(DATABASE_PROCESS_TIMEOUT);
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch (Exception e)
{
ManageError(ERROR_LEVEL.FATAL, "Database REDIS not started", true);
return false;
}
System.Data.Entity.Database.SetInitializer<DatabaseContext>(null);
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();
}
using (QueueController queueController = new QueueController())
queueController.ReadAndPopulateQueue();
}
catch (Exception ex)
{
ManageException(ERROR_LEVEL.FATAL, ex);
return false;
}
return true;
}
private 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, "cms.service", "cmsserviceonly", "cms", "service", new CultureInfo("it"), ROLE_IDS.CMS_SERVICE);
usersController.CreateCmsDefaultUserIfNotExists(MachineConfig.MachineId, "cms.ut", "cmsufficiotecnico", "cms", "ut", new CultureInfo("it"), ROLE_IDS.CMS_UT);
// Create default CUSTOMER user
usersController.CreateCmsDefaultUserIfNotExists(MachineConfig.MachineId, "admin", "admin", "customer", "admin", Config.ServerConfig.ServerStartupConfig.Language, ROLE_IDS.CUSTOMER_ADMIN);
usersController.CreateCmsDefaultUserIfNotExists(MachineConfig.MachineId, "operator", "operator", "customer", "operator", Config.ServerConfig.ServerStartupConfig.Language, ROLE_IDS.CUSTOMER_OPERATOR);
usersController.CreateCmsDefaultUserIfNotExists(MachineConfig.MachineId, "maintainer", "maintainer", "customer", "maintainer", Config.ServerConfig.ServerStartupConfig.Language, ROLE_IDS.CUSTOMER_MAINTAINER);
}
}
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("Active");
// 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("Active");
// Return value
return (string)key.GetValue(REGISTER_MACHINE_ID_KEY_NAME);
}
private static string getDbServiceName()
{
ServiceController[] services = ServiceController.GetServices();
var service = services.FirstOrDefault(s => s.ServiceName == "MariaDB");
if (service != null)
return service.DisplayName;
service = services.FirstOrDefault(s => s.ServiceName == "MySQL");
if (service != null)
return service.DisplayName;
return "";
}
private static string getRedisServiceName()
{
ServiceController[] services = ServiceController.GetServices();
var service = services.FirstOrDefault(s => s.ServiceName == "Redis");
if (service != null)
return service.DisplayName;
return "";
}
}
}