Files
2024-06-20 13:15:12 +02:00

4086 lines
164 KiB
C#

using EgwCoreLib.Utils;
using MailKit.Search;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NLog;
using Org.BouncyCastle.Asn1.Pkcs;
using StackExchange.Redis;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using System.Text;
using WebDoorCreator.Core;
using WebDoorCreator.Data.Controllers;
using WebDoorCreator.Data.DbModels;
using WebDoorCreator.Data.DTO;
namespace WebDoorCreator.Data.Services
{
public class WebDoorCreatorService
{
#region Public Fields
public static WebDoorCreatorController dbController = null!;
#endregion Public Fields
#region Public Constructors
public WebDoorCreatorService(IConfiguration configuration, IConnectionMultiplexer redisConnMult, IEmailSender emailSender)
{
Log.Info("WebDoorCreatorService starting...");
_configuration = configuration;
_emailSender = emailSender;
// Conf cache
redisConn = redisConnMult;
redisDb = this.redisConn.GetDatabase();
// json serializer... FIX errore loop circolare https://www.ryadel.com/en/jsonserializationexception-self-referencing-loop-detected-error-fix-entity-framework-asp-net-core/
JSSettings = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
// cod app
CodApp = _configuration["CodApp"];
// Conf DB
string connStr = _configuration.GetConnectionString("WDC.DB");
if (string.IsNullOrEmpty(connStr))
{
Log.Info("ConnString empty!");
}
else
{
dbController = new WebDoorCreatorController(configuration);
}
// conf log
logTimingEnable = configuration.GetValue<bool>("RuntimeOpt:LogTimingEnable");
statSampleSize = configuration.GetValue<int>("RuntimeOpt:StatSampleSize");
// conf serializzatore DDF...
string vers = _configuration.GetValue<string>("ConfDDF:VersNumber");
bool remDoorOp = _configuration.GetValue<bool>("ConfDDF:RemoveDoorOps");
var headRows = _configuration.GetSection("ConfDDF:Header").Get<List<string>>();
var footRows = _configuration.GetSection("ConfDDF:Footer").Get<List<string>>();
currDdfConv = new DDF.Converter(vers, remDoorOp, headRows, footRows);
// chiudo log
Log.Info("WebDoorCreatorService started!");
}
#endregion Public Constructors
#region Public Properties
public string CodApp { get; set; } = "";
#endregion Public Properties
#region Public Methods
/// <summary>
/// Update company
/// </summary>
/// <param name="currRec"></param>
/// <returns></returns>
public async Task<bool> CompanyAddMod(CompanyModel currRec)
{
var dbResult = await dbController.CompanyAddMod(currRec);
try
{
// elimino cache redis...
RedisValue pattern = new RedisValue($"{Constants.rKeyCompany}");
bool answ = await ExecFlushRedisPattern(pattern);
await Task.Delay(1);
}
catch (Exception exc)
{
Log.Error($"Exception during CompanyAddMod: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Company list filtered by company id
/// </summary>
/// <param name="id">Id to filter (0=ALL)</param>
/// <returns></returns>
public async Task<List<CompanyModel>> CompanyGetByKey(int id)
{
string source = "DB";
List<CompanyModel> dbResult = new List<CompanyModel>();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyCompany}:{id}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<CompanyModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<CompanyModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.CompanyGetByKey(id);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<CompanyModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"CompanyGetAll | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during CompanyGetByKey: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Conta i componenti missing presenti sul DB ma non su FS
/// </summary>
/// <param name="defaultPath"></param>
/// <returns></returns>
public async Task<int> CompoCountMissing(string defaultPath)
{
await Task.Delay(1);
int numMissing = 0;
// ciclo x tutti gli oggetti "FOLDER" della tabella
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
// recupero dizionario componenti - directory
Dictionary<string, string> DictCompoDir = getCompoDict(defaultPath);
var listTemplate = await ListValuesGetAll("*", "template");
if (listTemplate != null && listTemplate.Count > 0)
{
// ciclo elenco template...
foreach (var item in listTemplate)
{
string fPath = Path.Combine(defaultPath, item.TableName, item.Value);
if (DictCompoDir.ContainsKey(item.TableName))
{
fPath = Path.Combine(DictCompoDir[item.TableName], item.Value);
}
// se non contiene "." aggiungo ".lua"
if (!item.Label.Contains("."))
{
fPath += ".lua";
}
// controllo se esiste...
if (!File.Exists(fPath))
{
numMissing++;
Log.Debug($"Found missing file: {fPath}");
}
}
}
sw.Stop();
TimeSpan ts = sw.Elapsed;
Log.Debug($"CompoCountMissing in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during CompoCountMissing: {exc}{Environment.NewLine}");
}
return numMissing;
}
/// <summary>
/// Conta i componenti missing presenti sul DB ma non su FS
/// </summary>
/// <param name="defaultPath"></param>
/// <returns></returns>
public async Task<bool> CompoFixMissing(string defaultPath)
{
bool fixDone = false;
int numFixed = 0;
await Task.Delay(1);
// ciclo x tutti gli oggetti "FOLDER" della tabella
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
// recupero dizionario componenti - directory
Dictionary<string, string> DictCompoDir = getCompoDict(defaultPath);
var listTemplate = await ListValuesGetAll("*", "template");
if (listTemplate != null && listTemplate.Count > 0)
{
// ciclo elenco template...
foreach (var item in listTemplate)
{
string fPath = Path.Combine(defaultPath, item.TableName, item.Value);
if (DictCompoDir.ContainsKey(item.TableName))
{
fPath = Path.Combine(DictCompoDir[item.TableName], item.Value);
}
// se non contiene "." aggiungo ".lua"
if (!item.Label.Contains("."))
{
fPath += ".lua";
}
// controllo se esiste...
if (!File.Exists(fPath))
{
var fDir = Path.GetDirectoryName(fPath);
// verifico directory...
if(!Directory.Exists(fDir))
{
Directory.CreateDirectory(fDir);
}
// creo file...
var newFile = File.Create(fPath);
Log.Info($"Created missing file: {fPath}");
newFile.Close();
numFixed++;
}
}
}
sw.Stop();
TimeSpan ts = sw.Elapsed;
Log.Debug($"CompoFixMissing | {numFixed} fixed in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during CompoFixMissing: {exc}{Environment.NewLine}");
}
fixDone = numFixed > 0;
return fixDone;
}
/// <summary>
/// Getting a list of all the active components
/// </summary>
/// <param name="rootPath">Path to start</param>
/// <returns></returns>
public async Task<List<string>> CompoGetAllActive(string rootPath)
{
await Task.Delay(1);
List<string> listActiveCompo = new List<string>();
try
{
//estraggo la lista di componenti che sono attive per il cliente
IniFile fIni = new IniFile(rootPath);
string compoDDF = fIni.ReadString("CompoOrder", "CompoDDFOrder", "CONFIG");
var compoDDFList = compoDDF.Split(",");
foreach (string compo in compoDDFList)
{
listActiveCompo.Add(compo.Trim());
}
}
catch (Exception exc)
{
Log.Error($"Exception during CompoGetAllActive: {exc}{Environment.NewLine}");
}
return listActiveCompo;
}
/// <summary>
/// Setting all the component list
/// </summary>
/// <param name="rootPath">Path to start</param>
/// <returns></returns>
public async Task<bool> CompoListSetAll(string rootPath)
{
bool fatto = false;
string compoName = "";
string sizeVal = "";
List<GraphicParamsModel> listGraphicParams = new List<GraphicParamsModel>();
List<ListValuesTempModel> listValues = new List<ListValuesTempModel>();
ListValuesTempModel Values = new ListValuesTempModel();
try
{
List<string> listActiveCompo = await CompoGetAllActive(Path.Combine(rootPath, @"Default.ini"));
List<HardwareModel> listCompoS = new List<HardwareModel>();
// estraggo tutte le sotto directory della cartella \EgtData\Doors\EgtCompoBase\Compo
string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.TopDirectoryOnly);
// elenco obj da inserire
List<DoorOpTypeModel> ListObjDOT = new List<DoorOpTypeModel>();
string[] DefaultFile = Directory.GetFiles(rootPath, "Default.ini");
IniFile fIniDef = new IniFile(DefaultFile[0]);
ListValuesTempModel listValObj = new ListValuesTempModel()
{
TableName = "Properties",
FieldName = "DoorDef",
Value = "Properties",
Label = "Properties",
Ordinal = 1,
DefaultVal = "Maple, Oak, Pine, Birch, Walnut",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "Finishing",
FieldName = "DoorDef",
Value = "Finishing",
Label = "Finishing",
Ordinal = 1,
DefaultVal = "Varnishing, Veneer",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "All",
FieldName = "OrderStep",
Value = "10",
Label = "Door Draft",
Ordinal = 10,
DefaultVal = "#EF6C00",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "All",
FieldName = "OrderStep",
Value = "20",
Label = "Sent to DCA",
Ordinal = 20,
DefaultVal = "#FBC02D",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "All",
FieldName = "OrderStep",
Value = "30",
Label = "Approved By Maker",
Ordinal = 30,
DefaultVal = "#2962FF",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "All",
FieldName = "OrderStep",
Value = "40",
Label = "Approved By Customer",
Ordinal = 40,
DefaultVal = "#673AB7",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "All",
FieldName = "OrderStep",
Value = "50",
Label = "ERP",
Ordinal = 50,
DefaultVal = "#00B8D4",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "All",
FieldName = "OrderStep",
Value = "60",
Label = "In Production",
Ordinal = 60,
DefaultVal = "#43A047",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "All",
FieldName = "OrderStep",
Value = "70",
Label = "Delivered",
Ordinal = 70,
DefaultVal = "#AEEA00",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "All",
FieldName = "DoorDefStep",
Value = "10",
Label = "Door",
Ordinal = 10,
DefaultVal = "#448AFF",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "All",
FieldName = "DoorDefStep",
Value = "20",
Label = "Hardware",
Ordinal = 20,
DefaultVal = "#448AFF",
InputType = ""
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "All",
FieldName = "DoorDefStep",
Value = "30",
Label = "Report",
Ordinal = 30,
DefaultVal = "#448AFF",
InputType = ""
};
listValues.Add(listValObj);
// parto con obj base
sizeVal = fIniDef.ReadString("Size", "Width", "0.0");
listValObj = new ListValuesTempModel()
{
TableName = "Size",
FieldName = "DoorDef",
Value = "Width",
Label = "50001",
Ordinal = 1,
DefaultVal = sizeVal,
InputType = "TextBox",
isSerializable = true
};
listValues.Add(listValObj);
sizeVal = fIniDef.ReadString("Size", "Height", "0.0");
listValObj = new ListValuesTempModel()
{
TableName = "Size",
FieldName = "DoorDef",
Value = "Height",
Label = "50002",
Ordinal = 2,
DefaultVal = sizeVal,
InputType = "TextBox",
isSerializable = true
};
listValues.Add(listValObj);
sizeVal = fIniDef.ReadString("Size", "Thickness", "0.0");
listValObj = new ListValuesTempModel()
{
TableName = "Size",
FieldName = "DoorDef",
Value = "Thickness",
Label = "50003",
Ordinal = 3,
DefaultVal = sizeVal,
InputType = "TextBox",
isSerializable = true
};
listValues.Add(listValObj);
sizeVal = fIniDef.ReadString("Size", "SwingList", "UNDEF");
listValObj = new ListValuesTempModel()
{
TableName = "Swing",
FieldName = "DoorDef",
Value = "Swing",
Label = "50004",
Ordinal = 1,
DefaultVal = sizeVal,
InputType = "TextBox",
isSerializable = true
};
listValues.Add(listValObj);
//sizeVal = fIniDef.ReadString("Edge", "EdgeTypeList", "UNDEF");
StringBuilder edgesList = new StringBuilder();
for (int x = 1; x <= 11; x++)
{
var edge = fIniDef.ReadString("Edge", $"EdgeType{x}", "UNDEF");
if (x != 11)
{
edgesList.Append($"{edge.Split("/")[0]},");
}
else
{
edgesList.Append($"{edge.Split("/")[0]}");
}
}
listValObj = new ListValuesTempModel()
{
TableName = "Profiles",
FieldName = "DoorDef",
Value = "lockedge",
Label = "50005",
Ordinal = 1,
DefaultVal = "",
InputType = "",
isSerializable = true
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "Profiles",
FieldName = "DoorDef",
Value = "hingeedge",
Label = "50006",
Ordinal = 2,
DefaultVal = "",
InputType = "",
isSerializable = true
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "Profiles",
FieldName = "DoorDef",
Value = "top",
Label = "50007",
Ordinal = 3,
DefaultVal = "",
InputType = "",
isSerializable = true
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "Profiles",
FieldName = "DoorDef",
Value = "bottom",
Label = "50008",
Ordinal = 4,
DefaultVal = "",
InputType = "",
isSerializable = true
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "Profiles",
FieldName = "DoorDef",
Value = "type",
Label = "50424",
Ordinal = 5,
DefaultVal = edgesList.ToString(),
InputType = "ComboBox",
isSerializable = true
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "Profiles",
FieldName = "DoorDef",
Value = "machining",
Label = "90312",
Ordinal = 6,
DefaultVal = "ON,OFF",
InputType = "ComboBox",
isSerializable = true
};
listValues.Add(listValObj);
listValObj = new ListValuesTempModel()
{
TableName = "Profiles",
FieldName = "DoorDef",
Value = "overmaterial",
Label = "90312",
Ordinal = 7,
DefaultVal = "0.1",
InputType = "ComboBox",
isSerializable = true
};
listValues.Add(listValObj);
int i = 0;
foreach (string dir in dirs)
{
int numPar = 1;
int numHead = 1;
// scansione della directory...
string[] files = Directory.GetFiles(dir, "Config.ini");
compoName = "";
//iterazione per cercare tutti numPar file "Config.ini" nelle sotto directory
foreach (string file in files)
{
//leggo tutte le linee del file
List<string> lines = File.ReadAllLines(file).ToList();
IniFile fIni = new IniFile(file);
Guid opCode = Guid.NewGuid();
//cerco la sezione del file ed estraggo il nome del componente
compoName = fIni.ReadString("Compo", "Name", "COMPONAME");
//cerco la sezione del file ed estraggo se numPar template sono attivi per il seguente componente
var isActive = fIni.ReadString("Template", "IsActive", "1");
string layerName = fIni.ReadString("Layer", "LayerName", "LAYER");
// lo slash indica l'alias
var compoNameSplit = compoName.Split("/");
var compoAcArray = listActiveCompo.ToArray();
var x = Array.FindIndex(compoAcArray, row => row == compoNameSplit[0]);
if (listActiveCompo.Contains(compoNameSplit[0].ToString()))
{
//creo il componente (padre)
listValObj = new ListValuesTempModel()
{
TableName = $"{compoNameSplit[0]}".Trim(),
FieldName = "Hardware",
Value = $"{compoNameSplit[0]}",
Label = $"{compoNameSplit[1]}",
Ordinal = x,
DefaultVal = " ",
InputType = " "
};
//HardwareModel compoConfig = new HardwareModel() { compoName = $"{compoNameSplit[0]}", compoAlias = compoNameSplit[1].ToString(), compoLayerName = layerName, compoTemplateIsActive = compoTemplateIsActive };
//await dbController.CompoAdd(compoConfig);
//listCompoS.Add(compoConfig);
listValues.Add(listValObj);
i++;
//cerco all'interno del file tutte le sezioni che contengono "[Graphic" così da poter prendere il nome della sezione ES: [Graphic parameters1] = Graphic parameters1
var lineToSearch = lines.Where(x => x.Contains("[Graphic")).ToList();
numHead = 1;
foreach (var match in lineToSearch)
{
var listV = await GraphicParamsGetAll(file, match, numHead, numPar, $"{compoNameSplit[0]}");
foreach (var item in listV)
{
listValues.Add(item);
}
numHead++;
}
numPar++;
}
}
}
fatto = await dbController.ListValuesAdd(listValues);
}
catch (Exception exc)
{
Log.Error($"Exception during CompoListSetAll: {exc}{Environment.NewLine}");
}
return fatto;
}
/// <summary>
/// Lista configurazione
/// </summary>
/// <returns></returns>
public async Task<List<ConfigModel>> ConfigGetAll()
{
string source = "DB";
List<ConfigModel>? dbResult = new List<ConfigModel>();
try
{
string currKey = $"{Constants.rKeyConfig}:Table";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<ConfigModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<ConfigModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.ConfigGetAll();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<ConfigModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ConfigGetAll | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"ConfigGetAll during CompoListSetAll: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Recupera una singola chaive di config da cache/DB
/// </summary>
/// <param name="chiave"></param>
/// <returns></returns>
public async Task<ConfigModel?> ConfigGetKey(string chiave)
{
string source = "DB";
// cerco in cache direttamente la chiave... altrimenti da redis/db
ConfigModel? keyResult = null;
try
{
string currKey = $"{Constants.rKeyConfig}:Dict:{chiave}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<ConfigModel>(rawData);
if (tempResult == null)
{
keyResult = new ConfigModel();
}
else
{
keyResult = tempResult;
}
keyResult = JsonConvert.DeserializeObject<ConfigModel>(rawData);
}
else
{
var listConfig = await ConfigGetAll();
keyResult = listConfig.FirstOrDefault(x => x.chiave == chiave);
rawData = JsonConvert.SerializeObject(keyResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ConfigGetKey | {chiave} | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during ConfigGetKey: {exc}{Environment.NewLine}");
}
return await Task.FromResult(keyResult);
}
public async Task<int> createDoor(int idOrd, string userId, string currMeaUnit)
{
int answ = 0;
try
{
// conto le porte x questo ordine e uso x chiamata successiva...
var door4ord = await DoorGetByOrderId(idOrd);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
int numDoors = door4ord?.Count + 1 ?? 1;
List<DoorOpModel> listOp = new List<DoorOpModel>();
DateTime adesso = DateTime.Now;
// creo una nuova porta...
DoorModel newDoor = new DoorModel()
{
OrderId = idOrd,
MeasureUnit = currMeaUnit,
UserIdIns = userId,
UserIdMod = userId,
UserIdLock = userId,
DateIns = adesso,
DateMod = adesso,
DateLockExpiry = adesso.AddHours(1),
DoorDescript = $"ORD {idOrd} | Door {numDoors:00}",
DoorExtCode = $"ORD {idOrd} | Ext Code --",
Quantity = 1,
UnitCost = 0,
ParentId = 1
};
// chiamo metodo x insert...
var doorId = await DoorInsert(newDoor);
// aggiungo le lavorazioni standard...
var doorOpList = await DoorOpGetDefault();
var listRecordEdge = await ListValuesGetAll("Profiles", "DoorDef");
var listRecordSizing = await ListValuesGetAll("Size", "DoorDef");
var listRecordSwing = await ListValuesGetAll("Swing", "DoorDef");
var listRecordProperties = await ListValuesGetAll("Properties", "DoorDef");
var listRecordFinishing = await ListValuesGetAll("Finishing", "DoorDef");
ListValuesModel? profCurrType = null;
ListValuesModel? profCurrMach = null;
ListValuesModel? profCurrOverMat = null;
if (listRecordEdge != null)
{
profCurrType = listRecordEdge.Where(x => x.Value == "type").FirstOrDefault();
profCurrMach = listRecordEdge.Where(x => x.Value == "machining").FirstOrDefault();
profCurrOverMat = listRecordEdge.Where(x => x.Value == "overmaterial").FirstOrDefault();
}
Dictionary<string, Dictionary<string, List<string>>> itemsDictDef = new Dictionary<string, Dictionary<string, List<string>>>();
Dictionary<string, Dictionary<string, string>> itemsDictAct = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, List<string>> paramsDict = new Dictionary<string, List<string>>();
Dictionary<string, string> actDict = new Dictionary<string, string>();
List<string> listDefVal = new List<string>();
List<string> listDefValCurrMach = new List<string>();
List<string> listDefValOverMat = new List<string>();
List<string> defaultParamsList = new List<string>();
#region Gestione Properties
if (listRecordProperties != null)
{
foreach (var item in listRecordProperties)
{
foreach (var param in item.DefaultVal.Split(","))
{
listDefVal.Add(param.Trim());
if (!actDict.ContainsKey(item.Value))
{
actDict.Add(item.Value, item.DefaultVal.Trim().Split(",")[0]);
paramsDict.Add(item.Value, listDefVal);
}
//itemsDict.Add(itemOld.Value, paramsDict);
//paramsDict.Clear();
}
//listDefVal = new List<string>() { itemOld.DefaultVal.Trim() };
}
itemsDictDef.Add("Properties", paramsDict);
itemsDictAct.Add("Properties", actDict);
//defaultParamsList.Add(listDefVal);
}
var jsonDef = JsonConvert.SerializeObject(itemsDictDef);
var jsonAct = JsonConvert.SerializeObject(itemsDictAct);
DoorOpModel doorOpToAdd = new DoorOpModel()
{
DateIns = adesso,
DateMod = adesso,
UserIdIns = userId,
UserIdMod = userId,
ObjectId = "Properties",
DoorId = doorId,
JsoncConfigVal = jsonDef,
JsoncActVal = jsonAct,
userConfirm = userId,
DtConfirm = adesso
};
listOp.Add(doorOpToAdd);
#endregion Gestione Properties
paramsDict.Clear();
actDict.Clear();
itemsDictDef.Clear();
itemsDictAct.Clear();
listDefVal.Clear();
#region Gestione Finishing
if (listRecordFinishing != null)
{
foreach (var item in listRecordFinishing)
{
foreach (var param in item.DefaultVal.Split(","))
{
listDefVal.Add(param.Trim());
if (!actDict.ContainsKey(item.Value))
{
actDict.Add(item.Value, item.DefaultVal.Trim().Split(",")[0]);
paramsDict.Add(item.Value, listDefVal);
}
//itemsDict.Add(itemOld.Value, paramsDict);
//paramsDict.Clear();
}
//listDefVal = new List<string>() { itemOld.DefaultVal.Trim() };
}
itemsDictDef.Add("Finishing", paramsDict);
itemsDictAct.Add("Finishing", actDict);
//defaultParamsList.Add(listDefVal);
}
jsonDef = JsonConvert.SerializeObject(itemsDictDef);
jsonAct = JsonConvert.SerializeObject(itemsDictAct);
doorOpToAdd = new DoorOpModel()
{
DateIns = adesso,
DateMod = adesso,
UserIdIns = userId,
UserIdMod = userId,
ObjectId = "Finishing",
DoorId = doorId,
JsoncConfigVal = jsonDef,
JsoncActVal = jsonAct,
userConfirm = userId,
DtConfirm = adesso
};
listOp.Add(doorOpToAdd);
#endregion Gestione Finishing
paramsDict.Clear();
actDict.Clear();
itemsDictDef.Clear();
itemsDictAct.Clear();
listDefVal.Clear();
#region Gestione sizing
if (listRecordSizing != null)
{
foreach (var item in listRecordSizing)
{
listDefVal = new List<string>() { item.DefaultVal.Trim() };
if (!actDict.ContainsKey(item.Value))
{
actDict.Add(item.Value, item.DefaultVal.Trim());
paramsDict.Add(item.Value, listDefVal);
}
}
itemsDictDef.Add("Size", paramsDict);
itemsDictAct.Add("Size", actDict);
//defaultParamsList.Add(listDefVal);
}
jsonDef = JsonConvert.SerializeObject(itemsDictDef);
jsonAct = JsonConvert.SerializeObject(itemsDictAct);
doorOpToAdd = new DoorOpModel()
{
DateIns = adesso,
DateMod = adesso,
UserIdIns = userId,
UserIdMod = userId,
ObjectId = "Size",
DoorId = doorId,
JsoncConfigVal = jsonDef,
JsoncActVal = jsonAct,
userConfirm = userId,
DtConfirm = adesso
};
listOp.Add(doorOpToAdd);
#endregion Gestione sizing
paramsDict.Clear();
actDict.Clear();
itemsDictDef.Clear();
itemsDictAct.Clear();
listDefVal.Clear();
#region Gestione Swing
if (listRecordSwing != null)
{
foreach (var item in listRecordSwing)
{
foreach (var param in item.DefaultVal.Split(","))
{
listDefVal.Add(param.Trim());
if (!actDict.ContainsKey(item.Value))
{
actDict.Add(item.Value, item.DefaultVal.Trim().Split(",")[0]);
paramsDict.Add(item.Value, listDefVal);
}
//itemsDict.Add(itemOld.Value, paramsDict);
//paramsDict.Clear();
}
//listDefVal = new List<string>() { itemOld.DefaultVal.Trim() };
}
itemsDictDef.Add("Swing", paramsDict);
itemsDictAct.Add("Swing", actDict);
//defaultParamsList.Add(listDefVal);
}
jsonDef = JsonConvert.SerializeObject(itemsDictDef);
jsonAct = JsonConvert.SerializeObject(itemsDictAct);
doorOpToAdd = new DoorOpModel()
{
DateIns = adesso,
DateMod = adesso,
UserIdIns = userId,
UserIdMod = userId,
ObjectId = "Swing",
DoorId = doorId,
JsoncConfigVal = jsonDef,
JsoncActVal = jsonAct,
userConfirm = userId,
DtConfirm = adesso
};
listOp.Add(doorOpToAdd);
#endregion Gestione Swing
paramsDict.Clear();
actDict.Clear();
itemsDictDef.Clear();
itemsDictAct.Clear();
listDefVal.Clear();
#region Gestione Profiles
if (listRecordEdge != null)
{
listDefVal.Clear();
if (profCurrType != null)
{
foreach (var param in profCurrType.DefaultVal.Split(","))
{
listDefVal.Add(param.Trim());
if (!actDict.ContainsKey(profCurrType.Value))
{
actDict.Add(profCurrType.Value, param.Trim());
paramsDict.Add(profCurrType.Value, listDefVal);
//listDefVal.Clear();
}
//itemsDict.Add(itemOld.Value, paramsDict);
//paramsDict.Clear();
}
if (profCurrMach != null)
{
//listDefVal.Clear();
foreach (var param in profCurrMach.DefaultVal.Split(","))
{
listDefValCurrMach.Add(param.Trim());
if (!actDict.ContainsKey(profCurrMach.Value))
{
paramsDict.Add(profCurrMach.Value, listDefValCurrMach);
actDict.Add(profCurrMach.Value, profCurrMach.DefaultVal.Trim().Split(",")[0]);
//listDefVal.Clear();
}
//itemsDict.Add(itemOld.Value, paramsDict);
//paramsDict.Clear();
}
}
if (profCurrOverMat != null)
{
//listDefVal.Clear();
if (!paramsDict.ContainsKey(profCurrOverMat.Value))
{
listDefValOverMat.Add(profCurrOverMat.DefaultVal.Trim());
paramsDict.Add(profCurrOverMat.Value, listDefValOverMat);
actDict.Add(profCurrOverMat.Value, profCurrOverMat.DefaultVal.Trim());
}
}
}
foreach (var item in listRecordEdge.Where(x => x.Value != "type" && x.Value != "machining" && x.Value != "overmaterial"))
{
if (!itemsDictDef.ContainsKey(item.Value))
{
itemsDictDef.Add(item.Value, paramsDict);
}
if (!itemsDictAct.ContainsKey(item.Value))
{
itemsDictAct.Add(item.Value, actDict);
}
//defaultParamsList.Add(listDefVal);
//defaultDict.Add(itemOld.Label, listDefVal);
}
}
//actDict.Add(HwToShow.TableName, actParamsList);
jsonDef = JsonConvert.SerializeObject(itemsDictDef);
jsonAct = JsonConvert.SerializeObject(itemsDictAct);
doorOpToAdd = new DoorOpModel()
{
DateIns = adesso,
DateMod = adesso,
UserIdIns = userId,
UserIdMod = userId,
ObjectId = "Profiles",
DoorId = doorId,
JsoncConfigVal = jsonDef,
JsoncActVal = jsonAct,
userConfirm = userId,
DtConfirm = adesso
};
listOp.Add(doorOpToAdd);
#endregion Gestione Profiles
// salvo Door OP associate
bool fatto = await DoorOpInsert(doorId, listOp);
if (fatto)
{
answ = doorId;
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"createDoor | {doorId} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during createDoor: {exc}{Environment.NewLine}");
}
return answ;
}
public string DecriptData(string encData)
{
return SteamCrypto.DecryptString(encData, Constants.passPhrase);
}
/// <summary>
/// Clone a copy of the door in the specified order
/// </summary>
/// <param name="doorId">Record id to edit or add</param>
/// <param name="doorCode">Code associated to door</param>
/// <param name="doorDescr">Description for the door</param>
/// <param name="orderId">Destination order where door must be placed</param>
/// <param name="userName">userName for cloning</param>
/// <param name="isClone">
/// true = cloning a door and save TypeId from orig, false = save to template order
/// </param>
/// <returns></returns>
public async Task<int> DoorCloneToOrder(int doorId, string doorCode, string doorDescr, int orderId, string userName, bool isClone)
{
int newDoorId = 0;
var doorOps2Add = new List<DoorOpModel>();
try
{
var CurrDoor = await DoorGetByKey(doorId);
var DoorOpsList = await DoorOpGetByDoorId(doorId);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
if (DoorOpsList != null)
{
var doorOps2Clone = DoorOpsList?.Where(x => x.DoorId == doorId).ToList();
//var door2Clone = CurrDoor;
if (CurrDoor != null)
{
var doorToAdd = CurrDoor.ObjClone(userName);
// imposto dati per la porta...
doorToAdd.OrderId = orderId;
doorToAdd.ParentId = isClone ? CurrDoor.DoorId : 1;
doorToAdd.Quantity = 1;
doorToAdd.DoorExtCode = doorCode;
doorToAdd.DoorDescript = doorDescr;
// salvo!
newDoorId = await DoorInsert(doorToAdd);
if (newDoorId != 0 && doorOps2Clone != null)
{
foreach (var item in doorOps2Clone)
{
var doorOp2Add = item.ObjClone(userName, newDoorId);
doorOps2Add.Add(doorOp2Add);
}
// salvo!
await DoorOpInsert(newDoorId, doorOps2Add);
}
}
}
// await dbController.DoorModQty(NewQty, doorId, isAdd); svuoto cache
await DoorFlushCache(doorId);
await DoorOpFlushCache(doorId);
await OrderDetailFlushCache(orderId);
await OrdersFlushCache();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorCloneToOrder | {doorId} | {orderId} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorCloneToOrder: {exc}{Environment.NewLine}");
}
return newDoorId;
}
/// <summary>
/// CElimina record posta
/// </summary>
/// <param name="currRec"></param>
/// <returns></returns>
public async Task<bool> DoorDelete(DoorModel currRec)
{
bool answ = false;
try
{
int DoorId = currRec.DoorId;
int OrderId = currRec.OrderId;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// elimino sul DB
answ = await dbController.DoorDelete(DoorId);
// svuoto cache
await DoorFlushCache(DoorId);
await DoorOpFlushCache(DoorId);
await OrderDetailFlushCache(OrderId);
await OrdersFlushCache();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorDelete | {DoorId} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorDelete: {exc}{Environment.NewLine}");
}
return answ;
}
/// <summary>
/// Clean redis DOORS cache
/// </summary>
/// <param name="DoorId">0 = all</param>
/// <returns></returns>
public async Task<bool> DoorFlushCache(int DoorId)
{
bool answ = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
RedisValue pattern = new RedisValue($"{Constants.rKeyDoor}:*");
if (DoorId > 0)
{
pattern = new RedisValue($"{Constants.rKeyDoor}:{DoorId}:*");
}
answ = await ExecFlushRedisPattern(pattern);
pattern = new RedisValue($"{Constants.rKeyDoorsByOrder}:*");
answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorDelete | {DoorId} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorFlushCache: {exc}{Environment.NewLine}");
}
return answ;
}
/// <summary>
/// Doors key (DoorId)
/// </summary>
public async Task<List<DoorModel>?> DoorGet2Del()
{
List<DoorModel>? dbResult = new List<DoorModel>();
try
{
Stopwatch sw = new Stopwatch();
if (logTimingEnable)
{
sw.Start();
}
dbResult = dbController.DoorGet2Del();
if (dbResult == null)
{
dbResult = new List<DoorModel>();
}
if (logTimingEnable)
{
sw.Stop();
// gestione statistiche
await ProcStatLog("DoorGet2Del", sw.Elapsed, 2, 1);
}
}
catch (Exception exc)
{
Log.Error($"Exception during DoorGet2Del: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Doors key (DoorId)
/// </summary>
public async Task<DoorModel?> DoorGetByKey(int doorId)
{
string source = "DB";
DoorModel? dbResult = new DoorModel();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyDoor}:Single:{doorId}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<DoorModel>(rawData);
if (tempResult == null)
{
dbResult = new DoorModel();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.DoorGetByKey(doorId);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new DoorModel();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorGetByKey | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorGetByKey: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Doors list by numRec
/// </summary>
public async Task<List<DoorModel>?> DoorGetByOrderId(int orderId)
{
string source = "DB";
List<DoorModel>? dbResult = new List<DoorModel>();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyDoorsByOrder}:{orderId}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<DoorModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<DoorModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.DoorsGetByOrderId(orderId);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<DoorModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorGetByOrderId | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorGetByOrderId: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Doors list, last in desc order
/// </summary>
public async Task<List<DoorModel>?> DoorGetLast(int numRec)
{
string source = "DB";
List<DoorModel>? dbResult = new List<DoorModel>();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyDoorLast}:{numRec}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<DoorModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<DoorModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.DoorsGetLast(numRec);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, FastCache);
}
if (dbResult == null)
{
dbResult = new List<DoorModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorGetLast | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorGetLast: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Add door
/// </summary>
/// <param name="newRec"></param>
/// <returns></returns>
public async Task<int> DoorInsert(DoorModel newRec)
{
int dbResult = 0;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.DoorInsert(newRec);
// elimino cache redis dati ordine...
await OrderDetailFlushCache(newRec.OrderId);
await OrdersFlushCache();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorInsert | {newRec.DoorId} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorInsert: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Eliminazione DoorOP
/// </summary>
/// <param name="currDoorOp"></param>
/// <returns></returns>
public async Task<bool> DoorOpDelete(DoorOpModel currDoorOp)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.DoorOpDelete(currDoorOp);
// elimino cache redis dati porta...
bool answ = await DoorOpFlushCache(currDoorOp.DoorId);
answ = answ && await DoorFlushCache(currDoorOp.DoorId);
// elimino cache redis dati ordine...
answ = answ && await OrdersFlushCache();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpDelete | {currDoorOp.DoorOpId} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpDelete: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Eliminazione DoorOP list
/// </summary>
/// <param name="currDoorOpList"></param>
/// <returns></returns>
public async Task<bool> DoorOpDeleteRange(List<DoorOpModel> currDoorOpList)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.DoorOpDeleteRange(currDoorOpList);
// elimino cache redis dati porta...
foreach (var item in currDoorOpList)
{
bool answ = await DoorOpFlushCache(item.DoorId);
answ = answ && await DoorFlushCache(item.DoorId);
// elimino cache redis dati ordine...
answ = answ && await OrdersFlushCache();
}
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpDeleteRange in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpDeleteRange: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Clean redis DOORS OP cache
/// </summary>
/// <param name="DoorId">0 = all</param>
/// <returns></returns>
public async Task<bool> DoorOpFlushCache(int DoorId)
{
bool answ = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
RedisValue pattern = new RedisValue($"{Constants.rKeyDoorOp}*");
if (DoorId > 0)
{
pattern = new RedisValue($"{Constants.rKeyDoorOp}:{DoorId}*");
}
answ = await ExecFlushRedisPattern(pattern);
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpFlushCache in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpFlushCache: {exc}{Environment.NewLine}");
}
return answ;
}
/// <summary>
/// Doors list by numRec
/// </summary>
public async Task<List<DoorOpModel>> DoorOpGetByDoorId(int DoorId)
{
string source = "DB";
List<DoorOpModel>? dbResult = new List<DoorOpModel>();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyDoorOp}:{DoorId}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<DoorOpModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<DoorOpModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.DoorOpGetByDoorId(DoorId);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<DoorOpModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpGetByDoorId | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpFlushCache: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Doors list by numRec
/// </summary>
public async Task<DoorOpModel> DoorOpGetById(int doorOpId)
{
await Task.Delay(1);
string source = "DB";
DoorOpModel? dbResult = new DoorOpModel();
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = dbController.DoorOpGetById(doorOpId);
if (dbResult == null)
{
dbResult = new DoorOpModel();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpGetById | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpGetById: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Create DDF from doorId
/// </summary>
public async Task<string> DoorOpGetDDF(int DoorId)
{
string resultDDF = "";
List<string> ordListVal = new List<string>();
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var listOpAll = await DoorOpGetByDoorId(DoorId);
if (listOpAll != null)
{
List<DoorOpModel> listOp = listOpAll.Where(x => x.userConfirm != "" && x.DtConfirm != null).ToList();
if (listOp != null)
{
// chiamo metodo x avewre DDF serializzato
var CurrentCompoOrder = await ListValuesGetAll("*", "Hardware");
if (CurrentCompoOrder != null)
{
foreach (var item in CurrentCompoOrder.OrderBy(x => x.Ordinal).ToList())
{
ordListVal.Add(item.TableName);
}
}
// riordino
listOp = listOp.OrderBy(d => ordListVal.IndexOf(d.ObjectId)).ToList();
// converto in DDF!
resultDDF = currDdfConv.GetSerialized(listOp);
}
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpGetDDF | in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpGetDDF: {exc}{Environment.NewLine}");
}
return resultDDF;
}
/// <summary>
/// lista DoorOpList necessarie all'init
/// </summary>
/// <returns></returns>
public async Task<List<DoorOpTypeModel>> DoorOpGetDefault()
{
List<DoorOpTypeModel>? dbResult = new List<DoorOpTypeModel>();
string source = "DB";
try
{
// cerco da cache
string currKey = $"{Constants.rKeyDoorOpType}:DEFAULT";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.DoorOpTypeGetDefault();
if (dbResult == null)
{
dbResult = new List<DoorOpTypeModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpGetDefault | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpGetDefault: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Restitusice i CurrVals + GraphParams aggiornati dati valori Folder/template
/// </summary>
/// <param name="ObjectId">Obj x cui è richiesto il ricalcolo parametri</param>
/// <param name="currVal">Dizionario dei valori attuali</param>
/// <param name="currParams">Dizionario di obj x GraphParams</param>
/// <returns></returns>
public async Task<(Dictionary<string, string>, Dictionary<string, List<string>>)> DoorOpGetUpdatedVals(string ObjectId, Dictionary<string, string> currVal, Dictionary<string, List<string>> currParams, string currTemplShape)
{
await Task.Delay(1);
// duplico oggetti da tornare
Dictionary<string, string> currValUpd = new Dictionary<string, string>();
Dictionary<string, List<string>> currParamsUpd = new Dictionary<string, List<string>>();
string default2Design = "";
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// cerco il setup del template selezionato
var listRecordTmp = await ListValuesGetAll(ObjectId, currTemplShape);
if (listRecordTmp != null && currVal.ContainsKey("Folder") && currVal.ContainsKey(currTemplShape))
{
string actKey = currVal[currTemplShape];
var firstTemplate = listRecordTmp.Where(x => x.Value == actKey).FirstOrDefault();
if (firstTemplate != null)
{
if (firstTemplate.DefaultVal != "")
{
default2Design = firstTemplate.DefaultVal;
}
else
{
default2Design = "1";
}
}
// elimino dai valori di setup e attuali quanto non sia template/folder...
currValUpd = currVal.Where(x => x.Key == "Folder" || x.Key == currTemplShape).ToDictionary(x => x.Key, x => x.Value);
// preparo setup valori
List<string> listDefVal = new List<string>();
var listRecordGP = await ListValuesGetAll(ObjectId, $"Graphic Parameters{default2Design}");
if (listRecordGP != null)
{
foreach (var item in listRecordGP)
{
if (item.isSerializable && item.DefaultVal.Contains(","))
{
listDefVal = item.DefaultVal.Trim().Split(",").ToList();
currValUpd.Add(item.Value.Trim(), item.DefaultVal.Trim().Split(",")[0].Split("/")[0]);
}
else
{
if (item.DefaultVal.Contains("/"))
{
listDefVal = new List<string>() { item.DefaultVal.Trim().Split("/")[0] };
currValUpd.Add(item.Value.Trim(), item.DefaultVal.Trim().Split("/")[0]);
}
else
{
listDefVal = new List<string>() { item.DefaultVal.Trim() };
currValUpd.Add(item.Value.Trim(), item.DefaultVal.Trim());
}
}
//defaultParamsList.Add(listDefVal);
currParamsUpd.Add(item.Value.Trim(), listDefVal);
}
}
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpGetUpdatedVals in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpGetUpdatedVals: {exc}{Environment.NewLine}");
}
return (currValUpd, currParamsUpd);
}
/// <summary>
/// Add doorOP list
/// </summary>
/// <param name="DoorId"></param>
/// <param name="newOpList"></param>
/// <returns></returns>
public async Task<bool> DoorOpInsert(int DoorId, List<DoorOpModel> newOpList)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.DoorOpInsert(newOpList);
// elimino cache redis dati porta...
bool answ = await DoorOpFlushCache(DoorId);
answ = answ && await DoorFlushCache(DoorId);
// elimino cache redis dati ordine...
answ = answ && await OrdersFlushCache();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpInsert in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpInsert: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Effettua il setup dei Graph parameters date info template selezionato
/// </summary>
/// <param name="currDoorOp"></param>
/// <returns></returns>
public async Task<DoorOpModel> DoorOpSetupGraphParams(DoorOpModel currDoorOp)
{
string default2Design = "";
Dictionary<string, string>? actDict = new Dictionary<string, string>();
Dictionary<string, string>? actDictNew = new Dictionary<string, string>();
Dictionary<string, List<string>>? defaultDictNew = new Dictionary<string, List<string>>();
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// per prima cosa deserializzo i valori attuali dal record...
if (!string.IsNullOrEmpty(currDoorOp.JsoncActVal))
{
actDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(currDoorOp.JsoncActVal);
// verifico di avere valori validi
if (actDict != null)
{
// cerco il setup del template selezionato
var listRecordTmp = await ListValuesGetAll(currDoorOp.ObjectId, "template");
if (listRecordTmp != null && actDict.ContainsKey("Folder") && (actDict.ContainsKey("template") || actDict.ContainsKey("shape")))
{
string actKey = actDict["template"];// Path.Combine(actDict["Folder"], actDict["template"]);
var firstTemplate = listRecordTmp.Where(x => x.Value == actKey).FirstOrDefault();
if (firstTemplate != null)
{
if (firstTemplate.DefaultVal != "")
{
default2Design = firstTemplate.DefaultVal;
}
else
{
default2Design = "1";
}
}
// elimino dai valori di setup e attuali quanto non sia template/folder...
actDictNew = actDict.Where(x => x.Key == "Folder" || x.Key == "template").ToDictionary(x => x.Key, x => x.Value);
// preparo setup valori
List<string> listDefVal = new List<string>();
var listRecordGP = await ListValuesGetAll(currDoorOp.ObjectId, $"Graphic Parameters{default2Design}");
if (listRecordGP != null)
{
foreach (var item in listRecordGP)
{
if (item.isSerializable && item.DefaultVal.Contains(","))
{
listDefVal = item.DefaultVal.Trim().Split(",").ToList();
actDictNew.Add(item.Value.Trim(), item.DefaultVal.Trim().Split(",")[0].Split("/")[0]);
}
else
{
if (item.DefaultVal.Contains("/"))
{
listDefVal = new List<string>() { item.DefaultVal.Trim().Split("/")[0] };
actDictNew.Add(item.Value.Trim(), item.DefaultVal.Trim().Split("/")[0]);
}
else
{
listDefVal = new List<string>() { item.DefaultVal.Trim() };
actDictNew.Add(item.Value.Trim(), item.DefaultVal.Trim());
}
}
//defaultParamsList.Add(listDefVal);
defaultDictNew.Add(item.Value.Trim(), listDefVal);
}
}
// ri-serializzo e salvo!
currDoorOp.JsoncActVal = JsonConvert.SerializeObject(actDictNew);
currDoorOp.JsoncConfigVal = JsonConvert.SerializeObject(defaultDictNew);
}
}
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpSetupGraphParams in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpSetupGraphParams: {exc}{Environment.NewLine}");
}
return currDoorOp;
}
/// <summary>
/// Bulk add door op types
/// </summary>
/// <param name="currRecList"></param>
/// <returns></returns>
public async Task<bool> DoorOpTypeAddRange(List<DoorOpTypeModel> currRecList)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string rootPathNew = _configuration.GetValue<string>("CompoBaseDirs:NewCompoDir");
string rootPathOld = _configuration.GetValue<string>("CompoBaseDirs:CurrCompoDir");
dbResult = await dbController.DoorOpTypeAddRange(currRecList);
foreach (var item in currRecList)
{
var pathSplit = item.OpCode.Split("\\");
var allDirectories = Directory.GetDirectories(rootPathNew, $"{pathSplit[pathSplit.Length - 3]}\\{pathSplit[pathSplit.Length - 2]}", SearchOption.AllDirectories);
foreach (string dir in allDirectories)
{
string dirToCreate = dir.Replace(rootPathNew, rootPathOld);
Directory.CreateDirectory(dirToCreate);
}
var allFiles = Directory.GetFiles(Path.Combine(rootPathNew, pathSplit[pathSplit.Length - 3], pathSplit[pathSplit.Length - 2]), pathSplit.Last(), SearchOption.AllDirectories);
foreach (string newPath in allFiles)
{
File.Copy(newPath, newPath.Replace(rootPathNew, rootPathOld), true);
}
}
// elimino cache redis dati porta...
bool answ = await ExecFlushRedisPattern(Constants.rKeyDoorOpType);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpTypeAddRange in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpTypeAddRange: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Doors list by numRec
/// </summary>
public async Task<List<DoorOpTypeModel>?> DoorOpTypeGetAll()
{
await Task.Delay(1);
string source = "DB";
List<DoorOpTypeModel>? dbResult = new List<DoorOpTypeModel>();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyDoorOpType}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = dbController.DoorOpTypeGetAll();
if (dbResult == null)
{
dbResult = new List<DoorOpTypeModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpTypeGetAll | {source} in: {ts.TotalMilliseconds} ms"); stopWatch.Stop();
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpTypeGetAll: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Door Operation Types
/// </summary>
public async Task<List<DoorOpTypeModel>?> DoorOpTypeGetByHwCode(string hwCode, int parentId)
{
string source = "DB";
List<DoorOpTypeModel>? dbResult = new List<DoorOpTypeModel>();
string currKey = "";
try
{
// cerco da cache
if (hwCode == "*")
{
currKey = $"{Constants.rKeyDoorOpType}";
}
else
{
currKey = $"{Constants.rKeyDoorOpType}:{hwCode}";
}
if (hwCode == "*" && parentId == -1)
{
// extracting entire set
currKey = $"{Constants.rKeyDoorOpType}";
}
else if (hwCode != "*" && parentId == -1)
{
currKey = $"{Constants.rKeyDoorOpType}:{hwCode}";
}
else if (hwCode == "*" && parentId >= 0)
{
currKey = $"{Constants.rKeyDoorOpType}:{parentId}";
}
else if (hwCode != "*" && parentId >= 0)
{
currKey = $"{Constants.rKeyDoorOpType}:{hwCode}:{parentId}";
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<DoorOpTypeModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<DoorOpTypeModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.DoorOpTypeGetFiltered(hwCode, parentId);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<DoorOpTypeModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpTypeGetByHwCode | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpTypeGetByHwCode: {exc}{Environment.NewLine}");
}
return dbResult;
}
public async Task<List<DoorOpTypeModel>> DoorOpTypeGetByPath(string path)
{
string source = "DB";
List<DoorOpTypeModel>? dbResult = new List<DoorOpTypeModel>();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyDoorOpType}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<DoorOpTypeModel>>(rawData)?.Where(x => x.OpCode.StartsWith(path)).ToList();
if (tempResult == null)
{
dbResult = new List<DoorOpTypeModel>();
}
else
{
dbResult = tempResult;
}
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpTypeGetByPath | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpTypeGetByPath: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Aggiornamento DoorOP
/// </summary>
/// <param name="currDoorOps"></param>
/// <returns></returns>
public async Task<bool> DoorOpUpdate(List<DoorOpModel> currDoorOps)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.DoorOpUpdate(currDoorOps);
// elimino cache redis dati porta...
bool answ = await DoorOpFlushCache(currDoorOps.FirstOrDefault()!.DoorId);
answ = answ && await DoorFlushCache(currDoorOps.FirstOrDefault()!.DoorId);
// elimino cache redis dati ordine...
answ = answ && await OrdersFlushCache();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorOpUpdate in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorOpUpdate: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Update costing for dictionary of doors
/// </summary>
/// <param name="DoorUnitCosts"></param>
/// <returns></returns>
public async Task<bool> DoorUpdateCosts(Dictionary<int, decimal> DoorUnitCosts)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.DoorUpdateCosts(DoorUnitCosts);
// elimino cache redis dati porte...
bool answ = false;
foreach (var item in DoorUnitCosts)
{
answ = await DoorFlushCache(item.Key);
}
// elimino cache redis dati ordine...
answ = answ && await OrdersFlushCache();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorUpdateCosts in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorUpdateCosts: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Update or add door
/// </summary>
/// <param name="currRec"></param>
/// <returns></returns>
public async Task<bool> DoorUpsert(DoorModel currRec)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.DoorUpsert(currRec);
// elimino cache redis dati porta...
bool answ = await DoorFlushCache(currRec.DoorId);
// elimino cache redis dati ordine...
answ = answ && await OrdersFlushCache();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DoorUpsert | {currRec.DoorId} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during DoorUpsert: {exc}{Environment.NewLine}");
}
return dbResult;
}
public string EncriptData(string rawData)
{
return SteamCrypto.EncryptString(rawData, Constants.passPhrase);
}
public async Task<bool> FlushCustomPattern(string keyWord)
{
await Task.Delay(1);
RedisValue pattern = new RedisValue($"{Constants.redisBaseAddr}:{keyWord}:*");
bool answ = await ExecFlushRedisPattern(pattern);
return answ;
}
public async Task<bool> FlushRedisCache()
{
await Task.Delay(1);
RedisValue pattern = new RedisValue($"{Constants.redisBaseAddr}*");
bool answ = await ExecFlushRedisPattern(pattern);
return answ;
}
public async Task<List<ListValuesTempModel>> GraphicParamsGetAll(string file, string match, int n, int i, string HwCode)
{
await Task.Delay(1);
List<ListValuesTempModel> listValuesTemp = new List<ListValuesTempModel>();
ListValuesTempModel listValObj = new ListValuesTempModel();
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
IniFile fIni = new IniFile(file);
//cerco il contenuto delle sezioni
var graphicParamsName = fIni.ReadSection(match.Substring(1, match.Length - 2));
//controllo se tra numPar numeri di graphic params vi è un buco ES: Graphic parameters1 Graphic parameters3 se il buco c'è salto tutti numPar parametri che stanno dopo il buco ==> tengo conto solo di Graphic parameters1
if (int.Parse(match.Substring(match.Length - 2, 1)) == n)
{
int ordinal = 1;
foreach (string param in graphicParamsName)
{
string compoParams = fIni.ReadString(match.Substring(1, match.Length - 2), $"{param.Split("=")[0]}", "CONFIG"); //cerco il parametro nella sezione
var compoParamsSplit = compoParams.Split(";");
string CompoParamName = "";
string CompoParamAlias = "";
if (param.Split("=")[0].StartsWith("Param"))
{
if (compoParamsSplit[1].Contains("/"))
{
CompoParamName = compoParamsSplit[1].Split("/")[0];
CompoParamAlias = compoParamsSplit[1].Split("/")[1];
}
else if (compoParamsSplit[1].Contains(" "))
{
CompoParamName = compoParamsSplit[1].Split(" ")[1];
//CompoParamAlias = compoParamsSplit[1].Split(" ")[1];
}
//creo nuovo oggetto parametro che conterrà anche il nome del componente per creare relazione
listValObj = new ListValuesTempModel()
{
TableName = $"{HwCode}".Trim(),
FieldName = match.Substring(1, match.Length - 2),
Value = CompoParamName,
Label = CompoParamAlias,
Ordinal = ordinal,
DefaultVal = param.Split("=")[1].Split(";")[2],
InputType = param.Split("=")[1].Split(";")[0],
isSerializable = true
};
if (listValuesTemp.Where(x => x.TableName == listValObj.TableName && x.FieldName == listValObj.FieldName && x.Value == listValObj.Value).Count() == 0 && listValObj.TableName != null && listValObj.FieldName != null && listValObj.Value != null)
{
listValuesTemp.Add(listValObj);
ordinal++;
}
else
{
Log.Error($"GraphicParamsGetAll | Duplicated key: {listValObj.TableName} {listValObj.FieldName} {listValObj.Value} ");
}
}
else
{
}
}
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"GraphicParamsGetAll | {file} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during GraphicParamsGetAll: {exc}{Environment.NewLine}");
}
return listValuesTemp;
}
/// <summary>
/// Estraggo tutte le lingue disponibili per questa applicazione
/// </summary>
/// <returns></returns>
public async Task<List<LanguageModel>?> LanguageGetAll()
{
string source = "DB";
List<LanguageModel>? dbResult = new List<LanguageModel>();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyLanguage}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<LanguageModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<LanguageModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.LanguageGetAll();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<LanguageModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"LanguageGetAll | {source} in: {ts.TotalMilliseconds} ms"); stopWatch.Stop();
}
catch (Exception exc)
{
Log.Error($"Exception during LanguageGetAll: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// List values
/// </summary>
public async Task<List<ListValuesModel>?> ListValuesGetAll(string tableName, string fieldName)
{
string source = "DB";
List<ListValuesModel>? dbResult = new List<ListValuesModel>();
string currKey = "";
try
{
// cerco da cache
currKey = $"{Constants.rKeyListValues}:{tableName}:{fieldName}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<ListValuesModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<ListValuesModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.ListValuesGetAll(tableName, fieldName);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<ListValuesModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ListValuesGetAll | {source} in: {ts.TotalMilliseconds} ms"); stopWatch.Stop();
}
catch (Exception exc)
{
Log.Error($"Exception during ListValuesGetAll: {exc}{Environment.NewLine}");
}
return dbResult;
}
public async Task<bool> ListValuesLuaNgeInsert(string defaultPath)
{
await Task.Delay(1);
List<ListValuesTempModel> values = new List<ListValuesTempModel>();
List<DoorOpTypeModel> doorOpTypesList = new List<DoorOpTypeModel>();
MD5 md5 = MD5.Create();
bool answ = false;
try
{
// ciclo nelle directories usando la colonna opcode
string compoCode = "";
string compoTempOrShape = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string[] hwDirectories = Directory.GetDirectories(defaultPath);
int ordin = 1;
foreach (var hw in hwDirectories)
{
string[] iniFiles = Directory.GetFiles(hw, "Config.ini");
string[] templateDirectories = Directory.GetDirectories(hw);
foreach (string templateDirectory in templateDirectories)
{
var tName = templateDirectory.Split("\\");
//var fName = templateDirectory.Split("\\");
foreach (var file in iniFiles)
{
List<string> lines = File.ReadAllLines(file).ToList();
IniFile fIni = new IniFile(file);
var compoName = fIni.ReadString("Compo", "Name", "COMPONAME");
var compoT = fIni.ReadString("Template", "Name", "TEMPSHAPE");
compoCode = compoName.Split("/")[0].Trim();
compoTempOrShape = compoT.Split("/")[0].Trim();
}
string[] templateFiles = Directory.GetFiles(templateDirectory);
if (templateFiles.Length > 0)
{
ListValuesTempModel folderNames = new ListValuesTempModel()
{
TableName = $"{compoCode}".Replace(" ", "_"),
FieldName = "Folder",
Value = @$"{tName[tName.Length - 1]}",
Label = @$"{tName[tName.Length - 1]}",
Ordinal = 0,
DefaultVal = " ",
InputType = " ",
};
values.Add(folderNames);
}
foreach (string templateFile in templateFiles)
{
FileInfo fi = new FileInfo(templateFile);
string defGpNum = "";
var lines = File.ReadAllLines(templateFile).ToList();
foreach (var line in lines)
{
if (line.StartsWith("--") && line.Contains("Default"))
{
if (line.Split("=")[1] != null)
{
defGpNum = line.Split("=")[1];
}
else
{
defGpNum = " ";
}
}
}
var fileName = "";
if (Path.GetFileName(templateFile).Split(".")[1] == "lua")
{
fileName = Path.GetFileName(templateFile).Split(".")[0];
}
else
{
fileName = Path.GetFileName(templateFile);
}
ListValuesTempModel temp = new ListValuesTempModel()
{
TableName = $"{compoCode}".Replace(" ", "_"),
FieldName = compoTempOrShape,
Value = @$"{tName[tName.Length - 1]}\{fileName}",
Label = fileName,
Ordinal = ordin,
DefaultVal = defGpNum,
InputType = " ",
};
var fileContent = File.ReadAllBytes(templateFile);
var hash = md5.ComputeHash(fileContent);
var oldMD5 = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
if (values.Where(x => x.TableName == temp.TableName && x.FieldName == temp.FieldName && x.Value == temp.Value).Count() == 0 && temp.TableName != null && temp.FieldName != null && temp.Value != null)
{
values.Add(temp);
ordin++;
}
else
{
Log.Error($"ListValuesLuaNgeInsert | Duplicated key: {temp.TableName} {temp.FieldName} {temp.Value} ");
}
}
}
}
answ = await dbController.ListValuesAdd(values);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ListValuesLuaNgeInsert in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during ListValuesLuaNgeInsert: {exc}{Environment.NewLine}");
}
return answ;
}
/// <summary>
/// Add new order
/// </summary>
/// <param name="currRec"></param>
/// <returns></returns>
public async Task<int> OrderAdd(OrderModel currRec)
{
int dbResult = 0;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.OrderAdd(currRec);
// elimino cache redis...
RedisValue pattern = new RedisValue($"{Constants.rKeyOrderStatus}:*");
bool answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"OrderAdd | {currRec.OrderExtCode} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during OrderAdd: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Clean REDIS order detail data in cache
/// </summary>
/// <param name="OrderId">0 = all</param>
/// <returns></returns>
public async Task<bool> OrderDetailFlushCache(int OrderId)
{
RedisValue pattern = new RedisValue($"{Constants.rKeyDoorsByOrder}:*");
if (OrderId > 0)
{
pattern = new RedisValue($"{Constants.rKeyDoorsByOrder}:{OrderId}");
}
bool answ = await ExecFlushRedisPattern(pattern);
return answ;
}
/// <summary>
/// Order (content) cloning
/// </summary>
/// <param name="OrdIdSrc"></param>
/// <param name="OrdIdDest"></param>
/// <param name="UsrIdMod"></param>
/// <returns></returns>
public async Task<bool> OrderDuplicate(int OrdIdSrc, int OrdIdDest, string UsrIdMod)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.OrderDuplicate(OrdIdSrc, OrdIdDest, UsrIdMod);
// elimino cache redis...
RedisValue pattern = new RedisValue($"{Constants.rKeyOrderStatus}:*");
bool answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"OrderDuplicate | {OrdIdSrc} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during OrderDuplicate: {exc}{Environment.NewLine}");
}
return dbResult;
}
public async Task<List<OrderModel>?> OrderGetByCompStatus(int CompanyId, int StatusId)
{
string source = "DB";
List<OrderModel>? dbResult = new List<OrderModel>();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyOrderByComp}:{CompanyId}:{StatusId}"; ;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<OrderModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<OrderModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.OrderGetByCompStatus(CompanyId, StatusId);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<OrderModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"OrderGetByCompStatus | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during OrderGetByCompStatus: {exc}{Environment.NewLine}");
}
return dbResult;
}
public async Task<OrderModel?> OrderGetByKey(int orderId)
{
string source = "DB";
OrderModel? dbResult = new OrderModel();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyOrderDetail}:{orderId}"; ;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<OrderModel>(rawData);
if (tempResult == null)
{
dbResult = new OrderModel();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.OrderGetByKey(orderId);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, LongCache);
}
if (dbResult == null)
{
dbResult = new OrderModel();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"OrderGetByKey | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during OrderGetByKey: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Remove order
/// </summary>
/// <param name="OrdId"></param>
/// <returns></returns>
public async Task<bool> OrderRem(int OrdId)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.OrderRem(OrdId);
// elimino cache redis...
RedisValue pattern = new RedisValue($"{Constants.rKeyOrderStatus}:*");
bool answ = await ExecFlushRedisPattern(pattern);
pattern = new RedisValue($"{Constants.rKeyOrderByComp}:*");
answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"OrderRem | {OrdId} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during OrderRem: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Clean redis ORDERS cache
/// </summary>
/// <returns></returns>
public async Task<bool> OrdersFlushCache()
{
RedisValue pattern = new RedisValue($"{Constants.rKeyOrderStatus}:*");
bool answ = await ExecFlushRedisPattern(pattern);
return answ;
}
public async Task<List<OrderStatusViewModel>?> OrderStatusGetFilt(int companyId, int orderStatus, DateTime dataFrom, DateTime dataTo)
{
string source = "DB";
List<OrderStatusViewModel>? dbResult = new List<OrderStatusViewModel>();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyOrderStatus}:{companyId}:{orderStatus}:{dataFrom:yyyyMMdd}:{dataTo:yyyyMMdd}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<OrderStatusViewModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<OrderStatusViewModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
var rawResult = dbController.OrderStatusGetAll(companyId, orderStatus, dataFrom, dataTo);
// ordino desc in ram...
dbResult = rawResult.OrderByDescending(x => x.OrderId).ToList();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<OrderStatusViewModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"OrderStatusGetFilt | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during OrderStatusGetFilt: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Updating an order code/description
/// </summary>
/// <param name="orderId"></param>
/// <param name="newCode"></param>
/// <param name="newDescript"></param>
/// <returns></returns>
public async Task<bool> OrderUpdateDescript(int orderId, string newCode, string newDescript)
{
var dbResult = await dbController.OrderUpdateDescript(orderId, newCode, newDescript);
// elimino cache redis dati ordine...
bool answ = await FlushRedisCache();
return dbResult;
}
/// <summary>
/// Updating an order promised date
/// </summary>
/// <param name="orderId"></param>
/// <param name="dateProm"></param>
/// <returns></returns>
public async Task<bool> OrderUpdatePromDate(int orderId, DateTime dateProm)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = await dbController.OrderUpdatePromDate(orderId, dateProm);
// elimino cache redis dati ordine...
bool answ = await FlushRedisCache();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"OrderUpdatePromDate | {orderId} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during OrderUpdatePromDate: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Updating an order status
/// </summary>
/// <param name="orderId"></param>
/// <param name="newStatus"></param>
/// <returns></returns>
public async Task<bool> OrderUpdateStatus(int orderId, int newStatus)
{
bool dbResult = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = dbResult = await dbController.OrderUpdateStatus(orderId, newStatus);
// elimino cache redis dati ordine...
bool answ = await ExecFlushRedisPattern($"{Constants.rKeyOrderStatus}:*");
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"OrderUpdateStatus | {orderId} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during OrderUpdateStatus: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Graphic parameters list by hw id
/// </summary>
public async Task<List<GraphicParamsModel>?> ParamGetByHwId(int hwId)
{
string source = "DB";
List<GraphicParamsModel>? dbResult = new List<GraphicParamsModel>();
// cerco da cache
try
{
string currKey = $"{Constants.rKeyGraphicParameters}:{hwId}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<GraphicParamsModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<GraphicParamsModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.ParamGetByHwId(hwId);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<GraphicParamsModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ParamGetByHwId | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during ParamGetByHwId: {exc}{Environment.NewLine}");
}
return dbResult;
}
public async Task<bool> populateHws()
{
bool answ = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string rootPath = _configuration.GetValue<string>("CompoBaseDirs:NewCompoDir");
List<string> listActiveCompo = await CompoGetAllActive(Path.Combine(rootPath, @"Default.ini"));
string[] dirs = Directory.GetDirectories(rootPath);
List<DoorOpTypeModel> doorOpTypesList = new List<DoorOpTypeModel>();
foreach (string dir in dirs)
{
string compoCode = "";
string[] templateDirectories = Directory.GetDirectories(dir);
string[] iniFiles = Directory.GetFiles(dir, "Config.ini");
foreach (var file in iniFiles)
{
List<string> lines = File.ReadAllLines(file).ToList();
IniFile fIni = new IniFile(file);
var compoName = fIni.ReadString("Compo", "Name", "COMPONAME");
var compoT = fIni.ReadString("Template", "Name", "TEMPSHAPE");
compoCode = compoName.Split("/")[0].Trim();
}
if (listActiveCompo.Contains(compoCode))
{
DoorOpTypeModel tempHwType = new DoorOpTypeModel()
{
ParentId = 0,
Description = $"Hardware Type {compoCode.Replace(" ", "_")}",
OpCode = @$"{dir}",
HasHw = true,
IsConcrete = true,
HwCode = $"{compoCode}".Replace(" ", "_")
};
doorOpTypesList.Add(tempHwType);
}
}
//scrivo su db hws
//*await dbController.DoorOpTypeAddRange(doorOpTypesList);
string currKey = $"{Constants.rKeyDoorOpType}";
string rawData = JsonConvert.SerializeObject(doorOpTypesList, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, LongCache);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"populateHws in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during populateHws: {exc}{Environment.NewLine}");
}
return answ;
}
/// <summary>
/// Dati x print report ordini
/// </summary>
/// <param name="orderId"></param>
/// <returns></returns>
public async Task<List<PrtRepOrderModel>?> PreRepOrderGetByKey(int orderId)
{
string source = "DB";
List<PrtRepOrderModel>? dbResult = new List<PrtRepOrderModel>();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyOrderStatus}:{orderId}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<PrtRepOrderModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<PrtRepOrderModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
var rawResult = dbController.PreRepOrderGetByKey(orderId);
// ordino desc in ram...
dbResult = rawResult.OrderByDescending(x => x.OrderId).ToList();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraFastCache);
}
if (dbResult == null)
{
dbResult = new List<PrtRepOrderModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"PreRepOrderGetByKey | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during populateHws: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Get single hash record
/// </summary>
/// <param name="currKey">Redis Key for Hashlist</param>
/// <param name="chiave">Requested key on list</param>
/// <returns>Value as Int</returns>
public async Task<int> RedHashGetInt(RedisKey currKey, string chiave)
{
int result = 0;
Stopwatch sw = new Stopwatch();
if (logTimingEnable)
{
sw.Start();
}
var hasVal = await redisDb.HashExistsAsync(currKey, chiave);
if (hasVal)
{
var rawRes = await redisDb.HashGetAsync(currKey, chiave);
if (rawRes.HasValue)
{
int.TryParse($"{rawRes}", out result);
}
}
if (logTimingEnable)
{
sw.Stop();
// gestione statistiche
await ProcStatLog("RedHashGetInt", sw.Elapsed, 0, 0.3);
}
return result;
}
/// <summary>
/// Get single hash record
/// </summary>
/// <param name="currKey">Redis Key for Hashlist</param>
/// <param name="chiave">Requested key on list</param>
/// <param name="doTimeLog">Execute time log processing</param>
/// <returns>Value as string</returns>
public async Task<string> RedHashGetString(RedisKey currKey, string chiave, bool doTimeLog)
{
string result = "";
Stopwatch sw = new Stopwatch();
if (logTimingEnable && doTimeLog)
{
sw.Start();
}
var hasVal = await redisDb.HashExistsAsync(currKey, chiave);
if (hasVal)
{
var rawRes = await redisDb.HashGetAsync(currKey, chiave);
if (rawRes.HasValue)
{
result = $"{rawRes}";
}
}
if (logTimingEnable && doTimeLog)
{
sw.Stop();
// gestione statistiche
await ProcStatLog("RedHashGetString", sw.Elapsed, 0, 0.3);
}
return result;
}
/// <summary>
/// Remove for single hash record
/// </summary>
/// <param name="currKey">Chiave redis della Hashlist</param>
/// <param name="chiave">Chiave nella HashList</param>
/// <returns>Esito rimozione</returns>
public async Task<bool> RedHashRemove(RedisKey currKey, string chiave)
{
bool fatto = false;
Stopwatch sw = new Stopwatch();
if (logTimingEnable)
{
sw.Start();
}
fatto = await redisDb.HashDeleteAsync(currKey, chiave);
if (logTimingEnable)
{
sw.Stop();
// gestione statistiche
await ProcStatLog("RedHashRemove", sw.Elapsed, 0, 0.3);
}
return fatto;
}
/// <summary>
/// Effettua upsert in HasList redis
/// </summary>
/// <param name="currKey">Chiave redis della Hashlist</param>
/// <param name="chiave">Chiave nella HashList</param>
/// <param name="valore">Valore da salvare</param>
/// <param name="doTimeLog">Gestione log time abilitata</param>
/// <returns>Num record nella HashList</returns>
public async Task<long> RedHashUpsert(RedisKey currKey, string chiave, string valore, bool doTimeLog = true)
{
long numReq = 0;
Stopwatch sw = new Stopwatch();
if (logTimingEnable && doTimeLog)
{
sw.Start();
}
await redisDb.HashSetAsync(currKey, chiave, valore);
numReq = await redisDb.HashLengthAsync(currKey);
if (logTimingEnable && doTimeLog)
{
sw.Stop();
// gestione statistiche
await ProcStatLog("RedHashUpsert", sw.Elapsed, 0, 0.3);
}
return numReq;
}
/// <summary>
/// Bulk delete chiavi su redis
/// </summary>
/// <param name="doorId"></param>
/// <returns></returns>
public async Task<bool> RedisBulkDelByDoorId(int doorId)
{
await FlushCustomPattern($"Cache:Door:{doorId}");
await FlushCustomPattern($"CalcRequests:CacheDDF:{doorId}");
await FlushCustomPattern($"CalcRequests:CacheSVG:{doorId}");
await FlushCustomPattern($"CalcRequests:Errors:{doorId}");
return true;
}
/// <summary>
/// roles list
/// </summary>
public async Task<List<AspNetRoles>?> RolesGetAll()
{
string source = "DB";
List<AspNetRoles>? dbResult = new List<AspNetRoles>();
try
{
// cerco da cache
string currKey = Constants.rKeyRoles;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<AspNetRoles>>(rawData);
if (tempResult == null)
{
dbResult = new List<AspNetRoles>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.RolesGetAll();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<AspNetRoles>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"RolesGetAll | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during RolesGetAll: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Esegue scansione dir richeista
/// </summary>
/// <param name="rootPath"></param>
/// <param name="useCache">indica se leggere da cache Redis(true) o da FS (false)</param>
/// <returns></returns>
public async Task<Dictionary<string, FileDTO>> scanSrcDestDir(string rootPath, bool useCache)
{
await Task.Delay(1);
string mode = "FS";
string currKey = $"{Constants.rKeyDirsScan}:{rootPath}";
string? rawData = "";
List<FileDTO> dirAFiles = new List<FileDTO>();
Dictionary<string, FileDTO> filesDict = new Dictionary<string, FileDTO>();
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
if (useCache)
{
mode = "cache";
rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
var rawList = JsonConvert.DeserializeObject<Dictionary<string, FileDTO>>(rawData);
if (rawList != null)
{
filesDict = rawList;
}
}
}
else
{
string[] dirs = Directory.GetDirectories(rootPath);
using (MD5 md5 = MD5.Create())
{
foreach (var dir in dirs)
{
string[] iniFiles = Directory.GetFiles(dir, "Config.ini");
string compoCode = "";
foreach (var file in iniFiles)
{
List<string> lines = File.ReadAllLines(file).ToList();
IniFile fIni = new IniFile(file);
var compoName = fIni.ReadString("Compo", "Name", "COMPONAME");
var compoT = fIni.ReadString("Template", "Name", "TEMPSHAPE");
compoCode = compoName.Split("/")[0].Trim();
}
string[] templateDirectories = Directory.GetDirectories(dir);
foreach (var tplDir in templateDirectories)
{
string[] tpls = Directory.GetFiles(tplDir, "*");
//var archiviedFiles = dbController.DoorOpTypeGetByPath(tplDir);
foreach (var tpl in tpls)
{
FileInfo fi = new FileInfo(tpl);
var fileName = Path.GetFileName(tpl).Split("\\")[Path.GetFileName(tpl).Split("\\").Length - 1];
var fileContent = File.ReadAllBytes(tpl);
var hash = md5.ComputeHash(fileContent);
var newMD5 = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
FileDTO currFileInfo = new FileDTO()
{
//FileBaseDir = tplDir,
//FileAbsPath = fi.FullName,
FileRelPath = fileName,
FileDim = fi.Length,
FileMD5 = newMD5,
lastModTime = fi.LastWriteTime
};
string relDirPath = fi.FullName.Replace($"{rootPath}\\", "");
var src = relDirPath.Split("\\").ToArray();
//var src = fi.FullName.Split("\\").Skip(6).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var line in src)
{
if (src.Last().ToString() == line)
{
sb.Append($"{line}");
}
else
{
sb.Append($"{line}\\");
}
}
if (!filesDict.ContainsKey(sb.ToString()))
{
filesDict.Add(sb.ToString(), currFileInfo);
}
}
}
}
}
rawData = JsonConvert.SerializeObject(filesDict);
await redisDb.StringSetAsync(currKey, rawData);
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"scanSrcDestDir | {mode} | done in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during scanSrcDestDir: {exc}{Environment.NewLine}");
}
return filesDict;
}
/// <summary>
/// Restituisce dati statistica richiesta
/// </summary>
/// <param name="statName">Nome statistica</param>
/// <returns></returns>
public async Task<ExecStats> StatGetAsync(string statName)
{
ExecStats answ = new ExecStats(0, new TimeSpan());
RedisKey currKey = new RedisKey(Constants.STATS_DATA);
// cerco nella hashTable...
var rawData = await RedHashGetString(currKey, statName, false);
// se c'è rileggo ed aggiorno
if (!string.IsNullOrEmpty(rawData))
{
var currStat = JsonConvert.DeserializeObject<ExecStats>(rawData);
if (currStat != null)
{
answ = currStat;
}
}
return answ;
}
/// <summary>
/// Resetta dati statistica esecuzione x log restituendo i valori precedentemente contenuti
/// </summary>
/// <param name="statName">Nome statistica</param>
/// <returns></returns>
public async Task<ExecStats> StatReset(string statName)
{
RedisKey currKey = new RedisKey(Constants.STATS_DATA);
ExecStats answ = await StatGetAsync(statName);
// ora rimuovo valore
await RedHashRemove(currKey, statName);
return answ;
}
/// <summary>
/// Effettua upsert dati statistica esecuzione x log
/// </summary>
/// <param name="statName">Nome statistica</param>
/// <param name="duration">Durata esecuzione come timespan</param>
/// <param name="evMultipl">moltiplicatore soglia x log statistica (default = 1)</param>
/// <returns></returns>
public async Task<bool> StatUpsert(string statName, TimeSpan duration, double evMultipl)
{
bool answ = false;
RedisKey currKey = new RedisKey(Constants.STATS_DATA);
// cerco nella hashTable...
var rawData = await RedHashGetString(currKey, statName, false);
// di default inizializzo a null...
ExecStats newStat = new ExecStats(1, duration);
// se c'è rileggo ed aggiorno
if (!string.IsNullOrEmpty(rawData))
{
var currStat = JsonConvert.DeserializeObject<ExecStats>(rawData);
if (currStat != null)
{
currStat.NumCall++;
currStat.TotalTime += duration;
newStat = currStat;
}
}
// ora aggiorno su redis
rawData = JsonConvert.SerializeObject(newStat);
var numRec = await RedHashUpsert(currKey, statName, rawData, false);
// verifico se da considerare superato limite sample
answ = newStat.NumCall >= (int)(statSampleSize * evMultipl);
return answ;
}
/// <summary>
/// Update company
/// </summary>
/// <param name="currRec"></param>
/// <returns></returns>
public async Task<bool> UserAddMod(AspNetUsers currRec)
{
var dbResult = await dbController.UserAddMod(currRec);
// elimino cache redis...
RedisValue pattern = new RedisValue($"{Constants.rKeyCompany}");
bool answ = await ExecFlushRedisPattern(pattern);
await Task.Delay(1);
return dbResult;
}
/// <summary>
/// Users roles list
/// </summary>
public async Task<List<AspNetUsers>?> UsersGetAll()
{
string source = "DB";
List<AspNetUsers>? dbResult = new List<AspNetUsers>();
try
{
// cerco da cache
string currKey = Constants.rKeyUsers;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<AspNetUsers>>(rawData);
if (tempResult == null)
{
dbResult = new List<AspNetUsers>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.UsersGetAll();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<AspNetUsers>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"UsersGetAll | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during UsersGetAll: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Users roles list
/// </summary>
public async Task<AspNetUsers> UsersGetById(string userId)
{
string source = "DB";
AspNetUsers dbResult = new AspNetUsers();
try
{
// cerco da cache
string currKey = $"{Constants.rKeyUsers}:{userId}";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<AspNetUsers>(rawData);
if (tempResult == null)
{
dbResult = new AspNetUsers();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.UsersGetById(userId);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new AspNetUsers();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"UsersGetById | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during UsersGetById: {exc}{Environment.NewLine}");
}
return dbResult;
}
/// <summary>
/// Users roles list
/// </summary>
public async Task<List<UsersViewModel>?> UserViewGetAll()
{
string source = "DB";
List<UsersViewModel>? dbResult = new List<UsersViewModel>();
try
{
// cerco da cache
string currKey = Constants.rKeyUsersView;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<List<UsersViewModel>>(rawData);
if (tempResult == null)
{
dbResult = new List<UsersViewModel>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.UserViewGetAll();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new List<UsersViewModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"UserViewGetAll | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during UserViewGetAll: {exc}{Environment.NewLine}");
}
return dbResult;
}
public async Task<VocabularyTempModel?> VocLemmaFindByKeys(string lingua, string lemma)
{
string source = "DB";
VocabularyTempModel? dbResult = new VocabularyTempModel();
try
{
// cerco da cache
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string currKey = $"{Constants.rKeyVocLemma}:{lingua}:{lemma}";
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<VocabularyTempModel>(rawData);
if (tempResult == null)
{
dbResult = new VocabularyTempModel();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = await dbController.VocLemmaFindByKeys(lingua, lemma);
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new VocabularyTempModel();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"VocLemmaFindByKeys | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during VocLemmaFindByKeys: {exc}{Environment.NewLine}");
}
return dbResult;
}
public async Task<Dictionary<string, Dictionary<string, string>>?> VocLemmaGetAll()
{
string source = "DB";
Dictionary<string, Dictionary<string, string>>? dbResult = new Dictionary<string, Dictionary<string, string>>();
try
{
// cerco da cache
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string currKey = $"{Constants.rKeyVocLemma}";
string? rawData = await redisDb.StringGetAsync(currKey);
if (!string.IsNullOrEmpty(rawData))
{
source = "REDIS";
var tempResult = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(rawData);
if (tempResult == null)
{
dbResult = new Dictionary<string, Dictionary<string, string>>();
}
else
{
dbResult = tempResult;
}
}
else
{
dbResult = dbController.VocLemmaGetAll();
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
}
if (dbResult == null)
{
dbResult = new Dictionary<string, Dictionary<string, string>>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"VocLemmaGetAll | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during VocLemmaGetAll: {exc}{Environment.NewLine}");
}
return dbResult;
}
public async Task<bool> VocLemmaInsert()
{
bool fatto = false;
List<VocabularyTempModel> VocLemmas = new List<VocabularyTempModel>();
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
fatto = await dbController.VocLemmaInsert();
RedisValue pattern = new RedisValue($"{Constants.rKeyVocLemma}");
bool answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"VocLemmaInsert in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during VocLemmaInsert: {exc}{Environment.NewLine}");
}
return fatto;
}
public async Task<List<VocabularyTempModel>> VocLemmaInsertPrepare(string rootPath)
{
//bool fatto = false;
await Task.Delay(1);
List<VocabularyTempModel> VocLemmas = new List<VocabularyTempModel>();
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string[] files = Directory.GetFiles(rootPath, "*");
string lang = "";
foreach (string file in files)
{
var fileName = file.Split(".");
//lang = fileName[0].Split("\\").TakeLast(1).ToString().Substring(fileName[0].Length - 2, 2);
//leggo tutte le linee del file
List<string> lines = File.ReadAllLines(file).ToList();
foreach (var line in lines)
{
if (!line.StartsWith("//") && line != "")
{
string[] lineSplit = line.Split("=");
if (lineSplit[0] == "0")
{
if (lineSplit[1] != "ENG")
{
lang = lineSplit[1];
}
else
{
lang = "EN";
}
}
//string trad = "";
if (lineSplit.Length != 1)
{
VocabularyTempModel newVocLemma = new VocabularyTempModel()
{
Lingua = lang,
Lemma = lineSplit[0],
Traduzione = lineSplit[1]
};
VocLemmas.Add(newVocLemma);
}
}
}
}
await dbController.VocLemmaInsertPrepare(VocLemmas);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"VocLemmaInsertPrepare in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during VocLemmaInsertPrepare: {exc}{Environment.NewLine}");
}
return VocLemmas;
}
public async Task<bool> VocLemmaSetConf(string lingua, string lemma, bool isConf)
{
bool fatto = false;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
fatto = await dbController.VocLemmaSetConf(lingua, lemma, isConf);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"VocLemmaSetConf in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during VocLemmaSetConf: {exc}{Environment.NewLine}");
}
return fatto;
}
public async Task<Dictionary<string, Dictionary<string, string>>> VocLemmaTEMPGetAll()
{
await Task.Delay(1);
string source = "DB";
Dictionary<string, Dictionary<string, string>> dbResult = new Dictionary<string, Dictionary<string, string>>();
try
{
// cerco da cache
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
dbResult = dbController.VocLemmaTEMPGetAll();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"VocLemmaGetAll | {source} in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during VocLemmaGetAll: {exc}{Environment.NewLine}");
}
return dbResult;
}
#endregion Public Methods
#region Protected Properties
protected WebDoorCreator.Data.DDF.Converter currDdfConv { get; set; } = null!;
#endregion Protected Properties
#region Protected Methods
protected Dictionary<string, string> getCompoDict(string defaultPath)
{
///dizionario componenti - directory
Dictionary<string, string> DictCompoDir = new Dictionary<string, string>();
// in primis cerco le directory fisiche e la loro rappresentazione come nome componente...
string[] hwDirectories = Directory.GetDirectories(defaultPath);
foreach (var hw in hwDirectories)
{
string[] iniFiles = Directory.GetFiles(hw, "Config.ini");
if (iniFiles != null && iniFiles.Length > 0)
{
List<string> lines = File.ReadAllLines(iniFiles[0]).ToList();
IniFile fIni = new IniFile(iniFiles[0]);
var compoName = fIni.ReadString("Compo", "Name", "COMPONAME");
string compoCode = compoName.Split("/")[0].Trim();
// aggiungo al dizionari
if (!DictCompoDir.ContainsKey(compoCode))
{
DictCompoDir.Add(compoCode, hw);
}
}
}
return DictCompoDir;
}
#endregion Protected Methods
#region Private Fields
private static IConfiguration _configuration = null!;
private static JsonSerializerSettings? JSSettings;
private static Logger Log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Dimensione campione da registrare e trascrivere in log
/// </summary>
private static int statSampleSize = 1;
private readonly IEmailSender _emailSender;
/// <summary>
/// Durata cache lunga IN SECONDI
/// </summary>
private int cacheTtlLong = 60 * 5;
/// <summary>
/// Durata cache breve IN SECONDI
/// </summary>
private int cacheTtlShort = 60 * 1;
/// <summary>
/// abilitazione time log con stopwatch
/// </summary>
private bool logTimingEnable = false;
/// <summary>
/// Oggetto per connessione a REDIS
/// </summary>
private IConnectionMultiplexer redisConn;
/// <summary>
/// Oggetto DB redis da impiegare x chiamate R/W
/// </summary>
private IDatabase redisDb = null!;
private Random rnd = new Random();
#endregion Private Fields
#region Private Properties
/// <summary>
/// Durata cache breve (1 min circa + perturbazione percentuale +/-10%)
/// </summary>
private TimeSpan FastCache
{
get => TimeSpan.FromSeconds(cacheTtlShort * rnd.Next(900, 1100) / 1000);
}
/// <summary>
/// Durata cache lunga (+ perturbazione percentuale +/-10%)
/// </summary>
private TimeSpan LongCache
{
get => TimeSpan.FromSeconds(cacheTtlLong * rnd.Next(900, 1100) / 1000);
}
/// <summary>
/// Durata cache molto breve (10 sec circa + perturbazione percentuale +/-10%)
/// </summary>
private TimeSpan UltraFastCache
{
get => TimeSpan.FromSeconds(cacheTtlShort / 6 * rnd.Next(900, 1100) / 1000);
}
/// <summary>
/// Durata cache lunga (+ perturbazione percentuale +/-10%)
/// </summary>
private TimeSpan UltraLongCache
{
get => TimeSpan.FromSeconds(cacheTtlLong * 10 * rnd.Next(900, 1100) / 1000);
}
#endregion Private Properties
#region Private Methods
/// <summary>
/// Esegue flush memoria redis dato pattern
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
private async Task<bool> ExecFlushRedisPattern(RedisValue pattern)
{
bool answ = false;
var listEndpoints = redisConn.GetEndPoints();
foreach (var endPoint in listEndpoints)
{
//var server = redisConnAdmin.GetServer(listEndpoints[0]);
var server = redisConn.GetServer(endPoint);
if (server != null)
{
var keyList = server.Keys(redisDb.Database, pattern);
foreach (var item in keyList)
{
await redisDb.KeyDeleteAsync(item);
}
answ = true;
}
}
return answ;
}
/// <summary>
/// Processa log statistiche:
/// - accumula dati
/// - se superata soglia (soglia x evMultipl) registra log
/// </summary>
/// <param name="statName">nome statistica</param>
/// <param name="elapsed">durata evento tracciato</param>
/// <param name="logLevReq">
/// livello richiesto: 0:trace, 1:debug, 2:info, 3:warn, 4:error, 5: fatal, 6: off
/// </param>
/// <param name="evMultipl">moltiplicatore soglia x log statistica (default = 1)</param>
/// <returns></returns>
private async Task ProcStatLog(string statName, TimeSpan elapsed, int logLevReq, double evMultipl)
{
bool doWrite = await StatUpsert(statName, elapsed, evMultipl);
if (doWrite)
{
// recupero e resetto
ExecStats statRec = await StatReset(statName);
string logMsg = $"Eseguito {statName} x {statRec.NumCall} | {statRec.AvgTime.TotalMilliseconds:N3}ms";
switch (logLevReq)
{
case 0:
Log.Trace(logMsg);
break;
case 1:
Log.Debug(logMsg);
break;
case 2:
Log.Info(logMsg);
break;
case 3:
Log.Warn(logMsg);
break;
case 4:
Log.Error(logMsg);
break;
case 5:
Log.Fatal(logMsg);
break;
case 6:
default:
Log.Error(logMsg);
break;
}
}
}
#endregion Private Methods
#if false
public async Task<List<DoorOpTypeModel>> scanAndCompare()
{
List<DoorOpTypeModel> doorOpTypesList = new List<DoorOpTypeModel>();
List<int> tempStats = new List<int>();
List<DoorOpTypeModel> archiviedFiles = new List<DoorOpTypeModel>();
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string rootPathNew = _configuration.GetValue<string>("CompoBaseDirs:NewCompoDir");
string rootPathOld = _configuration.GetValue<string>("CompoBaseDirs:CurrCompoDir");
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
string newMD5 = "";
var oldFiles = await scanSrcDestDir(rootPathOld);
var newFiles = await scanSrcDestDir(rootPathNew);
long currFileDim = 0;
DateTime currFileLastMod = DateTime.Now;
// ciclo sui file in area NEW x confrontare con old
foreach (var itemNew in newFiles)
{
currFileDim = itemNew.FileDim;
currFileLastMod = itemNew.lastModTime;
newMD5 = itemNew.FileMD5;
var currTpl = oldFiles.Where(t => t.FileRelPath == itemNew.FileRelPath.Replace("NewComp", "CurComp") && t.FileMD5 == itemNew.FileMD5).FirstOrDefault();
if (currTpl != null)
{
// verifica sul DB
archiviedFiles = await DoorOpTypeGetByPath(currTpl.FileBaseDir);
var path2Search = archiviedFiles
.Where(x => x.OpCode == currTpl.FileAbsPath)
.FirstOrDefault();
tempStats.Add(0);
if (path2Search == null)
{
}
else if (path2Search.FileMD5 != newMD5 || path2Search.FileDim != currFileDim || path2Search.LastMod != currFileLastMod)
{
path2Search.FileDim = currFileDim;
path2Search.FileMD5 = newMD5;
path2Search.LastMod = currFileLastMod;
path2Search.Description = "modded";
path2Search.status = 2;
//await dbController.DoorOpTypeUpdate(path2Search);
}
}
else
{
DoorOpTypeModel tempTpl = new DoorOpTypeModel()
{
ParentId = 0,
//-.-------Description = $"Template for {itemNew.HwCode}",
OpCode = @$"{itemNew.FileAbsPath.Replace("NewComp", "CurComp")}",
HasHw = true,
IsConcrete = true,
//HwCode = itemNew.HwCode,
FileDim = currFileDim,
FileMD5 = newMD5,
LastMod = currFileLastMod,
status = 1
};
doorOpTypesList.Add(tempTpl);
oldFiles.Add(itemNew);
}
}
string currKey = $"{Constants.rKeyDoorOpType}";
string rawData = JsonConvert.SerializeObject(doorOpTypesList, JSSettings);
await redisDb.StringSetAsync(currKey, rawData, LongCache);
archiviedFiles.Clear();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"scanAndCompare in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during scanAndCompare: {exc}{Environment.NewLine}");
}
return doorOpTypesList;
}
#endif
/// <summary>
/// Esegue scansione dir richeista
/// </summary>
/// <param name="rootPath"></param>
/// <returns></returns>
#if false
public async Task<List<FileDTO>> scanSrcDestDir(string rootPath)
{
await Task.Delay(1);
List<FileDTO> dirAFiles = new List<FileDTO>();
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string[] dirs = Directory.GetDirectories(rootPath);
using (MD5 md5 = MD5.Create())
{
foreach (var dir in dirs)
{
string[] iniFiles = Directory.GetFiles(dir, "Config.ini");
string compoCode = "";
foreach (var file in iniFiles)
{
List<string> lines = File.ReadAllLines(file).ToList();
IniFile fIni = new IniFile(file);
var compoName = fIni.ReadString("Compo", "Name", "COMPONAME");
var compoT = fIni.ReadString("Template", "Name", "TEMPSHAPE");
compoCode = compoName.Split("/")[0].Trim();
}
string[] templateDirectories = Directory.GetDirectories(dir);
foreach (var tplDir in templateDirectories)
{
string[] tpls = Directory.GetFiles(tplDir, "*");
var archiviedFiles = dbController.DoorOpTypeGetByPath(tplDir);
foreach (var tpl in tpls)
{
FileInfo fi = new FileInfo(tpl);
var fileName = Path.GetFileName(tpl).Split("\\")[Path.GetFileName(tpl).Split("\\").Length - 1];
var fileContent = File.ReadAllBytes(tpl);
var hash = md5.ComputeHash(fileContent);
var newMD5 = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
FileDTO currFileInfo = new FileDTO()
{
HwCode = compoCode.Replace(" ", "_"),
FileBaseDir = tplDir,
FileAbsPath = fi.FullName,
FileRelPath = fileName,
FileDim = fi.Length,
FileMD5 = newMD5,
lastModTime = fi.LastWriteTime
};
dirAFiles.Add(currFileInfo);
}
}
}
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"scanSrcDestDir in: {ts.TotalMilliseconds} ms");
}
catch (Exception exc)
{
Log.Error($"Exception during scanSrcDestDir: {exc}{Environment.NewLine}");
}
return dirAFiles;
}
#endif
}
}