From 0fce9bbe049a7cdb3670202324117a9b3b3f2002 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Sat, 8 Jun 2024 12:31:20 +0200 Subject: [PATCH] Update con test vari x data syncro --- .../Controllers/LogMachineController.cs | 50 ++---- EgwProxy.MagMan/DataSyncro.cs | 135 ++++++++++----- EgwProxy.MagMan/RestPayload.cs | 45 +++-- MagMan.Core/MagMan.Core.csproj | 4 +- MagMan.Core/RestPayload.cs | 21 ++- MagMan.Data.Admin/MagMan.Data.Admin.csproj | 18 +- MagMan.Data.Admin/Services/MTAdminService.cs | 2 +- .../Controllers/TenantController.cs | 153 +++++++++++------ MagMan.Data.Tenant/DbConfig.cs | 6 +- MagMan.Data.Tenant/MagMan.Data.Tenant.csproj | 20 ++- MagMan.Data.Tenant/MagManContext.cs | 4 +- .../20240502115056_AddStoredProc01.cs | 2 + MagMan.Data.Tenant/Services/TenantService.cs | 88 ++++++---- .../SqlScripts/Stored/stp_mergeLogMachine.sql | 38 +++++ .../Stored/stp_removeLogMachine.sql | 22 +++ MagMan.UI/Controllers/LogMachineController.cs | 47 +++++- MagMan.UI/MagMan.UI.csproj | 11 +- MagMan.UI/appsettings.json | 1 + Resources/ChangeLog.html | 2 +- Resources/VersNum.txt | 2 +- Resources/manifest.xml | 2 +- TestConsoleApp/MagmanController.cs | 4 +- TestConsoleApp/Program.cs | 154 ++++++++++++------ 23 files changed, 563 insertions(+), 268 deletions(-) create mode 100644 MagMan.Data.Tenant/SqlScripts/Stored/stp_mergeLogMachine.sql create mode 100644 MagMan.Data.Tenant/SqlScripts/Stored/stp_removeLogMachine.sql diff --git a/EgwProxy.DataLayer/Controllers/LogMachineController.cs b/EgwProxy.DataLayer/Controllers/LogMachineController.cs index 2a9eff7..cc7af0e 100644 --- a/EgwProxy.DataLayer/Controllers/LogMachineController.cs +++ b/EgwProxy.DataLayer/Controllers/LogMachineController.cs @@ -3,6 +3,7 @@ using EgwProxy.MagMan.DTO; using NLog; using System; using System.Collections.Generic; +using System.Collections.Concurrent; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -82,7 +83,7 @@ namespace EgwProxy.DataLayer.Controllers { var currRec = localDbCtx .DbSetLogMac - .Where(x => x.DtSent == null && x.LogDbId == item.LogDbId) + .Where(x => (x.DtSent == null || x.DtSent < new DateTime(2000, 1, 1)) && x.LogDbId == item.LogDbId) .FirstOrDefault(); if (currRec != null) { @@ -107,59 +108,28 @@ namespace EgwProxy.DataLayer.Controllers { // init vars bool fatto = false; - int prodId = 0; + List> listBatch = new List>(); // vado sul DB using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING)) { // retrieve var list2proc = localDbCtx - .DbSetLogMac - .Where(x => x.ProjCloudId == 0 && ((int)x.EvType == 1 || (int)x.EvType == 2)) - .OrderBy(x => x.DtEvent) - .ToList(); + .DbSetLogMac + .Where(x => x.ProjCloudId == 0 && ((int)x.EvType == 1 || (int)x.EvType == 2)) + .OrderBy(x => x.DtEvent) + .ToList(); // se ci sono... if (list2proc != null && list2proc.Count > 0) { - // recupero elenco PROD - List prodList = localDbCtx - .DbSetProd - .AsNoTracking() - .ToList(); - - foreach (var item in list2proc) - { - prodId = 0; - // cerco valore - string[] dataList = item.VarValue.Split(';'); - if (dataList != null && dataList.Count() > 0) - { - int.TryParse(dataList[0], out prodId); - // se trovato - if (prodId > 0) - { - // salvo il valore prodId - item.ProdId = prodId; - // cerco il projCloudId in elenco - var projRec = prodList.Where(x => x.ProdId == prodId).FirstOrDefault(); - if (projRec != null) - { - item.ProjCloudId = projRec.ProjCloudId; - } - // indico modificato - localDbCtx.Entry(item).State = System.Data.Entity.EntityState.Modified; - } - } - } - // salvo - localDbCtx.SaveChanges(); - // registro - fatto = true; + // chiamo stored... + localDbCtx.Database.ExecuteSqlCommand("call stp_LogMachineFixPid"); } } // risultato return fatto; } + #endregion Public Methods #region Private Fields diff --git a/EgwProxy.MagMan/DataSyncro.cs b/EgwProxy.MagMan/DataSyncro.cs index 35a88b6..120f3a6 100644 --- a/EgwProxy.MagMan/DataSyncro.cs +++ b/EgwProxy.MagMan/DataSyncro.cs @@ -377,6 +377,49 @@ namespace EgwProxy.MagMan return await Task.FromResult(answ); } + /// + /// Invio richiesta cancellazione set dati log macchina + /// + /// Data inizio set da eliminare + /// Data fine set da eliminare + /// + public bool LogMachineRemoveRange(DateTime dtStart, DateTime dtEnd) + { + bool answ = false; + try + { + // chiamo update online + using (RestClient client = new RestClient(rcOptions)) + { + string MKeyEnc = HttpUtility.UrlEncode(RestToken); + // impacchetto dati x invio... + RestPayload.PeriodData newPayload = new RestPayload.PeriodData() + { + DtEnd = dtEnd, + DtStart = dtStart + }; + var jsonBody = JsonConvert.SerializeObject(newPayload); + var request = new RestRequest($"LogMachine/remove/{MKeyEnc}", Method.Post).AddJsonBody(jsonBody); + var response = client.Post(request); + // controllo risposta + if (response.StatusCode == HttpStatusCode.OK) + { + Log.Debug($"LogMachineRemoveRange | Response StatusCode: {response.StatusCode} | content: {response.Content}"); + answ = true; + } + else + { + Log.Error($"LogMachineRemoveRange | Response StatusCode: {response.StatusCode} | content: {response.Content}"); + } + } + } + catch (Exception exc) + { + Log.Error($"LogMachineRemoveRange | Eccezione {Environment.NewLine}{exc.Message}"); + } + return answ; + } + /// /// Invio elenco LogMachine da tab locale /// @@ -387,29 +430,36 @@ namespace EgwProxy.MagMan bool answ = false; if (rec2send != null && rec2send.Count > 0) { - // cerco online - using (RestClient client = new RestClient(rcOptions)) + try { - string MKeyEnc = HttpUtility.UrlEncode(RestToken); - // impacchetto dati x invio... - RestPayload.LogData newPayload = new RestPayload.LogData() + // chiamo update online + using (RestClient client = new RestClient(rcOptions)) { - LogList = rec2send - }; - var jsonBody = JsonConvert.SerializeObject(newPayload); - var request = new RestRequest($"LogMachine/upsert/{MKeyEnc}", Method.Post).AddJsonBody(jsonBody); - var response = client.Post(request); - // controllo risposta - if (response.StatusCode == HttpStatusCode.OK) - { - Log.Debug($"LogMachineSend | #rec: {rec2send.Count} | Response StatusCode: {response.StatusCode} | content: {response.Content}"); - answ = true; - } - else - { - Log.Error($"LogMachineSend | #rec: {rec2send.Count} | Response StatusCode: {response.StatusCode} | content: {response.Content}"); + string MKeyEnc = HttpUtility.UrlEncode(RestToken); + // impacchetto dati x invio... + RestPayload.LogData newPayload = new RestPayload.LogData() + { + LogList = rec2send + }; + var jsonBody = JsonConvert.SerializeObject(newPayload); + var request = new RestRequest($"LogMachine/upsert/{MKeyEnc}", Method.Post).AddJsonBody(jsonBody); + var response = client.Post(request); + // controllo risposta + if (response.StatusCode == HttpStatusCode.OK) + { + Log.Debug($"LogMachineSend | #rec: {rec2send.Count} | Response StatusCode: {response.StatusCode} | content: {response.Content}"); + answ = true; + } + else + { + Log.Error($"LogMachineSend | #rec: {rec2send.Count} | Response StatusCode: {response.StatusCode} | content: {response.Content}"); + } } } + catch (Exception exc) + { + Log.Error($"LogMachineSend | Eccezione {Environment.NewLine}{exc.Message}"); + } } return answ; } @@ -422,29 +472,36 @@ namespace EgwProxy.MagMan public async Task LogMachineSendAsync(List rec2send) { bool answ = false; - // cerco online - using (RestClient client = new RestClient(rcOptions)) + try { - string MKeyEnc = HttpUtility.UrlEncode(RestToken); - // impacchetto dati x invio... - RestPayload.LogData newPayload = new RestPayload.LogData() + // chiamo update online + using (RestClient client = new RestClient(rcOptions)) { - LogList = rec2send - }; - var jsonBody = JsonConvert.SerializeObject(newPayload); - var request = new RestRequest($"LogMachine/upsert/{MKeyEnc}", Method.Post).AddJsonBody(jsonBody); - var response = await client.PostAsync(request); - // controllo risposta - if (response.StatusCode == HttpStatusCode.OK) - { - Log.Debug($"LogMachineSendAsync | #rec: {rec2send.Count} | Response StatusCode: {response.StatusCode} | content: {response.Content}"); - answ = true; - } - else - { - Log.Error($"LogMachineSendAsync | #rec: {rec2send.Count} | Response StatusCode: {response.StatusCode} | content: {response.Content}"); + string MKeyEnc = HttpUtility.UrlEncode(RestToken); + // impacchetto dati x invio... + RestPayload.LogData newPayload = new RestPayload.LogData() + { + LogList = rec2send + }; + var jsonBody = JsonConvert.SerializeObject(newPayload); + var request = new RestRequest($"LogMachine/upsert/{MKeyEnc}", Method.Post).AddJsonBody(jsonBody); + var response = await client.PostAsync(request); + // controllo risposta + if (response.StatusCode == HttpStatusCode.OK) + { + Log.Debug($"LogMachineSendAsync | #rec: {rec2send.Count} | Response StatusCode: {response.StatusCode} | content: {response.Content}"); + answ = true; + } + else + { + Log.Error($"LogMachineSendAsync | #rec: {rec2send.Count} | Response StatusCode: {response.StatusCode} | content: {response.Content}"); + } } } + catch (Exception exc) + { + Log.Error($"LogMachineSendAsync | Eccezione {Environment.NewLine}{exc.Message}"); + } return await Task.FromResult(answ); } @@ -940,7 +997,7 @@ namespace EgwProxy.MagMan /// private string apiUrl = $""; - private int callTimeout = 500; + private int callTimeout = 10000; /// /// Opzioni standard di chiamata diff --git a/EgwProxy.MagMan/RestPayload.cs b/EgwProxy.MagMan/RestPayload.cs index 0341b4f..17cf11d 100644 --- a/EgwProxy.MagMan/RestPayload.cs +++ b/EgwProxy.MagMan/RestPayload.cs @@ -35,6 +35,18 @@ namespace EgwProxy.MagMan #endregion Public Properties } + public class LogData + { + #region Public Properties + + /// + /// Elenco record log x invio POST + /// + public List LogList { get; set; } + + #endregion Public Properties + } + public class Materials { #region Public Properties @@ -47,6 +59,16 @@ namespace EgwProxy.MagMan #endregion Public Properties } + public class PeriodData + { + #region Public Properties + + public DateTime DtEnd { get; set; } = DateTime.Now; + public DateTime DtStart { get; set; } = DateTime.Now; + + #endregion Public Properties + } + public class Projects { #region Public Properties @@ -60,6 +82,11 @@ namespace EgwProxy.MagMan { #region Public Properties + /// + /// DataOra richiesta (data-ora del client) + /// + public DateTime DtReq { get; set; } = DateTime.Now; + /// /// ID progetto univoco su Cloud /// @@ -70,11 +97,6 @@ namespace EgwProxy.MagMan /// public ProjResState ReqState { get; set; } = ProjResState.ND; - /// - /// DataOra richiesta (data-ora del client) - /// - public DateTime DtReq { get; set; } = DateTime.Now; - /// /// Elenco Risorse x invio POST /// @@ -83,19 +105,6 @@ namespace EgwProxy.MagMan #endregion Public Properties } - - public class LogData - { - #region Public Properties - - /// - /// Elenco record log x invio POST - /// - public List LogList { get; set; } - - #endregion Public Properties - } - #endregion Public Classes } } \ No newline at end of file diff --git a/MagMan.Core/MagMan.Core.csproj b/MagMan.Core/MagMan.Core.csproj index d5ebabd..87bd767 100644 --- a/MagMan.Core/MagMan.Core.csproj +++ b/MagMan.Core/MagMan.Core.csproj @@ -12,8 +12,8 @@ - - + + diff --git a/MagMan.Core/RestPayload.cs b/MagMan.Core/RestPayload.cs index 9037417..4ac35f0 100644 --- a/MagMan.Core/RestPayload.cs +++ b/MagMan.Core/RestPayload.cs @@ -35,6 +35,7 @@ namespace MagMan.Core #endregion Public Properties } + public class LogData { #region Public Properties @@ -59,6 +60,16 @@ namespace MagMan.Core #endregion Public Properties } + public class PeriodData + { + #region Public Properties + + public DateTime DtEnd { get; set; } = DateTime.Now; + public DateTime DtStart { get; set; } = DateTime.Now; + + #endregion Public Properties + } + public class Projects { #region Public Properties @@ -72,6 +83,11 @@ namespace MagMan.Core { #region Public Properties + /// + /// DataOra richiesta (data-ora del client) + /// + public DateTime DtReq { get; set; } = DateTime.Now; + /// /// ID progetto univoco su cloud /// @@ -82,11 +98,6 @@ namespace MagMan.Core /// public ProjResState ReqState { get; set; } = ProjResState.ND; - /// - /// DataOra richiesta (data-ora del client) - /// - public DateTime DtReq { get; set; } = DateTime.Now; - /// /// Elenco Risorse x invio POST /// diff --git a/MagMan.Data.Admin/MagMan.Data.Admin.csproj b/MagMan.Data.Admin/MagMan.Data.Admin.csproj index c143d27..c465325 100644 --- a/MagMan.Data.Admin/MagMan.Data.Admin.csproj +++ b/MagMan.Data.Admin/MagMan.Data.Admin.csproj @@ -19,22 +19,22 @@ - - - - + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + diff --git a/MagMan.Data.Admin/Services/MTAdminService.cs b/MagMan.Data.Admin/Services/MTAdminService.cs index 02d4bf4..5a32fe1 100644 --- a/MagMan.Data.Admin/Services/MTAdminService.cs +++ b/MagMan.Data.Admin/Services/MTAdminService.cs @@ -68,7 +68,7 @@ namespace MagMan.Data.Admin.Services Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); string? rawData = await redisDb.StringGetAsync(currKey); - if (!string.IsNullOrEmpty(rawData)) + if (!string.IsNullOrEmpty(rawData) && rawData.Length > 2) { source = "REDIS"; var tempResult = JsonConvert.DeserializeObject>(rawData); diff --git a/MagMan.Data.Tenant/Controllers/TenantController.cs b/MagMan.Data.Tenant/Controllers/TenantController.cs index 5430cb9..26efc57 100644 --- a/MagMan.Data.Tenant/Controllers/TenantController.cs +++ b/MagMan.Data.Tenant/Controllers/TenantController.cs @@ -4,6 +4,7 @@ using MagMan.Data.Tenant.DbModels; using MagMan.Data.Tenant.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; +using MySqlConnector; using NLog; using NLog.LayoutRenderers; using System; @@ -14,6 +15,7 @@ using System.Text; using System.Threading.Tasks; using System.Xml; using static MagMan.Core.Enums; +using static MagMan.Core.RestPayload; using static Microsoft.EntityFrameworkCore.DbLoggerCategory; namespace MagMan.Data.Tenant.Controllers @@ -234,44 +236,6 @@ namespace MagMan.Data.Tenant.Controllers return done; } - /// - /// Riattiva Item da magazzino - /// - /// Stringa connessione (variabile x cliente) - /// Item da riattivare - /// - public bool ItemReactiv(string connString, RawItemModel rec2del) - { - bool done = false; - using (MagManContext dbCtx = new MagManContext(connString)) - { - try - { - var currData = dbCtx - .DbSetItems - .Where(x => x.RawItemId == rec2del.RawItemId) - .FirstOrDefault(); - if (currData != null) - { - // riattivazione logica... - currData.IsActive = true; - // registro modifica RawItem - dbCtx.Entry(currData).State = EntityState.Modified; - - dbCtx.SaveChanges(); - done = true; - } - } - catch (Exception exc) - { - Log.Error($"Eccezione in ItemReactiv{Environment.NewLine}{exc}"); - } - } - return done; - } - - - /// /// Converte il DTO in ItemModel /// @@ -423,6 +387,42 @@ namespace MagMan.Data.Tenant.Controllers return done; } + /// + /// Riattiva Item da magazzino + /// + /// Stringa connessione (variabile x cliente) + /// Item da riattivare + /// + public bool ItemReactiv(string connString, RawItemModel rec2del) + { + bool done = false; + using (MagManContext dbCtx = new MagManContext(connString)) + { + try + { + var currData = dbCtx + .DbSetItems + .Where(x => x.RawItemId == rec2del.RawItemId) + .FirstOrDefault(); + if (currData != null) + { + // riattivazione logica... + currData.IsActive = true; + // registro modifica RawItem + dbCtx.Entry(currData).State = EntityState.Modified; + + dbCtx.SaveChanges(); + done = true; + } + } + catch (Exception exc) + { + Log.Error($"Eccezione in ItemReactiv{Environment.NewLine}{exc}"); + } + } + return done; + } + /// /// Converte lista ItemModel in DTO /// @@ -584,31 +584,78 @@ namespace MagMan.Data.Tenant.Controllers return dbResult; } - public int LogMacUpdate(string connString, List recList) + /// + /// Elimina un range di dati dal DB per poter inserire in blocco + /// + /// + /// Key di riferimento + /// Id Macchina + /// Data inizio set da eliminare + /// Data fine set da eliminare + /// + public int LogMacRemoveRange(string connString, int keyNum, int machineId, DateTime dtStart, DateTime dtEnd) { int numMod = 0; using (MagManContext dbCtx = new MagManContext(connString)) { try { - // verifico record x data/progetto... - foreach (var item in recList) + // eseguo stored + string sqlCommand = $"CALL stp_removeLogMachine ({keyNum}, {machineId}, '{dtStart:yyyy-MM-dd HH:mm:ss.fff}', '{dtEnd:yyyy-MM-dd HH:mm:ss.fff}');"; + dbCtx.Database.ExecuteSqlRaw(sqlCommand); + } + catch (Exception exc) + { + Log.Error($"Eccezione in LogMacRemoveRange{Environment.NewLine}{exc}"); + } + } + return numMod; + } + + public int LogMacUpdate(string connString, List recList) + { + bool useStored = true; + int numMod = 0; + using (MagManContext dbCtx = new MagManContext(connString)) + { + try + { + if (useStored) { - // cerco - var recOld = dbCtx - .DbSetLogMac - .Where(x => x.DtEvent == item.DtEvent && x.ProjDbId == item.ProjDbId && x.MachineID == item.MachineID) - .FirstOrDefault(); - if (recOld == null) + // eseguo stored x ogni record... + foreach (var item in recList) { - dbCtx - .DbSetLogMac - .Add(item); - numMod++; + string sqlCommand = $"CALL stp_mergeLogMachine ({item.KeyNum}, {item.MachineID}, {item.ProjDbId}, '{item.DtEvent:yyyy-MM-dd HH:mm:ss.fff}', {(int)item.EvType}, '{item.SupervId}', '{item.VarValue}');"; + dbCtx.Database.ExecuteSqlRaw(sqlCommand); } } - // salvo su DB - dbCtx.SaveChanges(); + else + { + // verifico record x data/progetto... + foreach (var item in recList) + { + // cerco + var recOld = dbCtx + .DbSetLogMac + .Where(x => x.KeyNum == item.KeyNum + && x.MachineID == item.MachineID + && x.ProjDbId == item.ProjDbId + && x.DtEvent == item.DtEvent + && x.EvType == item.EvType + && x.SupervId == item.SupervId + && x.VarValue == item.VarValue) + .FirstOrDefault(); + if (recOld == null) + { + dbCtx + .DbSetLogMac + .Add(item); + numMod++; + } + } + // salvo su DB + dbCtx.SaveChanges(); + } } catch (Exception exc) { diff --git a/MagMan.Data.Tenant/DbConfig.cs b/MagMan.Data.Tenant/DbConfig.cs index 16ac909..9e0fe38 100644 --- a/MagMan.Data.Tenant/DbConfig.cs +++ b/MagMan.Data.Tenant/DbConfig.cs @@ -33,7 +33,8 @@ namespace MagMan.Data.Tenant public static string CustomerConnString(string server, int nKey) { string dbName = $"MagMan_{nKey:000000}"; - return $"server={server};port=3306;database={dbName};uid={DATABASE_USER};pwd={DATABASE_PWD};sslmode=None"; + return $"server={server};port=3306;database={dbName};uid={DATABASE_USER};pwd={DATABASE_PWD};sslmode=None;Connection Lifetime=10;"; + //LoadBalance=RoundRobin;Pooling=true; } public static bool ExecMigrationMain(string connString) @@ -48,7 +49,8 @@ namespace MagMan.Data.Tenant { DATABASE_SERV = server; DATABASE_NAME = $"MagMan_{nKey:000000}"; - CONNECTION_STRING = $"server={DATABASE_SERV};port=3306;database={DATABASE_NAME};uid={DATABASE_USER};pwd={DATABASE_PWD};sslmode=None"; + CONNECTION_STRING = $"server={DATABASE_SERV};port=3306;database={DATABASE_NAME};uid={DATABASE_USER};pwd={DATABASE_PWD};sslmode=None;Connection Lifetime=10;"; + //LoadBalance=RoundRobin;Pooling=true; } #endregion Public Methods diff --git a/MagMan.Data.Tenant/MagMan.Data.Tenant.csproj b/MagMan.Data.Tenant/MagMan.Data.Tenant.csproj index 4ff9a12..e1c3380 100644 --- a/MagMan.Data.Tenant/MagMan.Data.Tenant.csproj +++ b/MagMan.Data.Tenant/MagMan.Data.Tenant.csproj @@ -21,20 +21,20 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + @@ -47,6 +47,12 @@ + + Always + + + Always + Always diff --git a/MagMan.Data.Tenant/MagManContext.cs b/MagMan.Data.Tenant/MagManContext.cs index d71e39d..5a82e4c 100644 --- a/MagMan.Data.Tenant/MagManContext.cs +++ b/MagMan.Data.Tenant/MagManContext.cs @@ -76,8 +76,8 @@ namespace MagMan.Data.Tenant { // commentato x test su cluster in ufficio #if DEBUG - //connString = "Server=localhost;port=3306;database=MagMan_000470;uid=MagMan_DbUser;pwd=viad@nte16!;sslmode=None;"; - connString = "Server=mdb03.ufficio;port=3306;database=MagMan_000470;uid=MagMan_DbUser;pwd=viad@nte16!;sslmode=None;"; + ////connString = "Server=localhost;port=3306;database=MagMan_000470;uid=MagMan_DbUser;pwd=viad@nte16!;sslmode=None;"; + //connString = "Server=mdb03.ufficio;port=3306;database=MagMan_000470;uid=MagMan_DbUser;pwd=viad@nte16!;sslmode=None;"; #endif var serverVersion = ServerVersion.AutoDetect(connString); optionsBuilder.UseMySql(connString, serverVersion, options => options.EnableRetryOnFailure( diff --git a/MagMan.Data.Tenant/Migrations/20240502115056_AddStoredProc01.cs b/MagMan.Data.Tenant/Migrations/20240502115056_AddStoredProc01.cs index e353def..c275924 100644 --- a/MagMan.Data.Tenant/Migrations/20240502115056_AddStoredProc01.cs +++ b/MagMan.Data.Tenant/Migrations/20240502115056_AddStoredProc01.cs @@ -11,12 +11,14 @@ namespace MagMan.Data.Tenant.Migrations { // aggiunta stored addStored(migrationBuilder, "stp_recalcDailyMGP"); + addStored(migrationBuilder, "stp_mergeLogMachine"); } protected override void Down(MigrationBuilder migrationBuilder) { // rimozione stored remStored(migrationBuilder, "stp_recalcDailyMGP"); + remStored(migrationBuilder, "stp_mergeLogMachine"); } private void addView(MigrationBuilder migrationBuilder, string objName) diff --git a/MagMan.Data.Tenant/Services/TenantService.cs b/MagMan.Data.Tenant/Services/TenantService.cs index dbc8ba4..547322a 100644 --- a/MagMan.Data.Tenant/Services/TenantService.cs +++ b/MagMan.Data.Tenant/Services/TenantService.cs @@ -233,33 +233,6 @@ namespace MagMan.Data.Tenant.Services return fatto; } - - /// - /// Riattiva Item da magazzino + refresh cache - /// - /// Key di riferimento - /// Item da riattivare - /// - public async Task ItemReactiv(int nKey, RawItemModel rec2react) - { - bool fatto = false; - string cString = ConnString(nKey); - try - { - fatto = dbController.ItemReactiv(cString, rec2react); - if (fatto) - { - await FlushRedisCache(); - } - } - catch (Exception exc) - { - Log.Error($"Error during ItemReactiv:{Environment.NewLine}{exc}"); - } - return fatto; - } - - /// /// Converte il DTO in ItemModel, colmando eventuale mancante nelle note dell'item /// @@ -496,6 +469,31 @@ namespace MagMan.Data.Tenant.Services return fatto; } + /// + /// Riattiva Item da magazzino + refresh cache + /// + /// Key di riferimento + /// Item da riattivare + /// + public async Task ItemReactiv(int nKey, RawItemModel rec2react) + { + bool fatto = false; + string cString = ConnString(nKey); + try + { + fatto = dbController.ItemReactiv(cString, rec2react); + if (fatto) + { + await FlushRedisCache(); + } + } + catch (Exception exc) + { + Log.Error($"Error during ItemReactiv:{Environment.NewLine}{exc}"); + } + return fatto; + } + /// /// Update record Item + refresh cache /// @@ -598,6 +596,34 @@ namespace MagMan.Data.Tenant.Services return dbResult; } + /// + /// Aggiunge/Modifica un record Resource + /// + /// Key di riferimento + /// Num Chiave record + /// Id Macchina + /// Data inizio set da eliminare + /// Data fine set da eliminare + /// + public async Task LogMacRemoveRange(int nKey, int machineId, DateTime dtStart, DateTime dtEnd) + { + int nUpdated = 0; + string cString = ConnString(nKey); + try + { + nUpdated = dbController.LogMacRemoveRange(cString, nKey, machineId, dtStart, dtEnd); + if (nUpdated > 0) + { + await FlushRedisCache(); + } + } + catch (Exception exc) + { + Log.Error($"Error during LogMacRemoveRange:{Environment.NewLine}{exc}"); + } + return nUpdated; + } + /// /// Aggiunge/Modifica un record Resource /// @@ -606,12 +632,12 @@ namespace MagMan.Data.Tenant.Services /// public async Task LogMacUpdate(int nKey, List recList) { - int newId = 0; + int nUpdated = 0; string cString = ConnString(nKey); try { - newId = dbController.LogMacUpdate(cString, recList); - if (newId > 0) + nUpdated = dbController.LogMacUpdate(cString, recList); + if (nUpdated > 0) { await FlushRedisCache(); } @@ -620,7 +646,7 @@ namespace MagMan.Data.Tenant.Services { Log.Error($"Error during LogMacUpdate:{Environment.NewLine}{exc}"); } - return newId; + return nUpdated; } /// diff --git a/MagMan.Data.Tenant/SqlScripts/Stored/stp_mergeLogMachine.sql b/MagMan.Data.Tenant/SqlScripts/Stored/stp_mergeLogMachine.sql new file mode 100644 index 0000000..cf94b9a --- /dev/null +++ b/MagMan.Data.Tenant/SqlScripts/Stored/stp_mergeLogMachine.sql @@ -0,0 +1,38 @@ +DROP PROCEDURE IF EXISTS `stp_mergeLogMachine`; + +CREATE DEFINER=`steamware`@`10.74.%` PROCEDURE `stp_mergeLogMachine`( + IN `pKeyNum` INT, + IN `pMachineID` INT, + IN `pProjDbId` INT, + IN `pDtEvent` DATETIME, + IN `pEvType` INT, + IN `pSupervId` VARCHAR(250), + IN `pVarValue` VARCHAR(250) +) +LANGUAGE SQL +NOT DETERMINISTIC +CONTAINS SQL +SQL SECURITY DEFINER +COMMENT 'Inserimento record in table LogMachine qualora non esistesse' +BEGIN + + # do x scontata cancellazione, creo nuovo record! + INSERT INTO LogMachine(KeyNum, MachineID, ProjDbId, DtEvent, EvType, SupervId, VarValue) + VALUES (pKeyNum, pMachineID, pProjDbId, pDtEvent, pEvType, pSupervId, pVarValue); + + ## creo record se non fosse già presente + #INSERT INTO LogMachine(KeyNum, MachineID, ProjDbId, DtEvent, EvType, SupervId, VarValue) + #SELECT src.* FROM + #(SELECT pKeyNum AS KeyNum , pMachineID AS MachineID, pProjDbId AS ProjDbId, pDtEvent AS DtEvent, pEvType AS EvType, pSupervId AS SupervId, pVarValue AS VarValue) as src + # LEFT OUTER JOIN LogMachine tgt ON + # tgt.KeyNum = src.KeyNum + # AND tgt.MachineID = src.MachineID + # AND tgt.ProjDbId = src.ProjDbId + # AND tgt.DtEvent = src.DtEvent + # AND tgt.EvType = src.EvType + # AND tgt.SupervId = src.SupervId + # AND tgt.VarValue = src.VarValue + #WHERE tgt.DbId IS NULL; + ##ON DUPLICATE KEY UPDATE DbId = DbId; + +END \ No newline at end of file diff --git a/MagMan.Data.Tenant/SqlScripts/Stored/stp_removeLogMachine.sql b/MagMan.Data.Tenant/SqlScripts/Stored/stp_removeLogMachine.sql new file mode 100644 index 0000000..ec3791e --- /dev/null +++ b/MagMan.Data.Tenant/SqlScripts/Stored/stp_removeLogMachine.sql @@ -0,0 +1,22 @@ +DROP PROCEDURE IF EXISTS `stp_removeLogMachine`; + +CREATE DEFINER=`steamware`@`10.74.%` PROCEDURE `stp_removeLogMachine`( + IN `pKeyNum` INT, + IN `pMachineID` INT, + IN `pDtMin` DATETIME, + IN `pDtMax` DATETIME +) +LANGUAGE SQL +NOT DETERMINISTIC +CONTAINS SQL +SQL SECURITY DEFINER +COMMENT 'Rimozione in blocco record da Key+Macchina+Periodo table LogMachine' +BEGIN + + # elimino intervallo + DELETE + FROM LogMachine + WHERE KeyNum = pKeyNum + AND MachineID = pMachineID + AND (DtEvent >= pDtMin AND DtEvent <= pDtMax); +END \ No newline at end of file diff --git a/MagMan.UI/Controllers/LogMachineController.cs b/MagMan.UI/Controllers/LogMachineController.cs index d81b9c9..1ae5962 100644 --- a/MagMan.UI/Controllers/LogMachineController.cs +++ b/MagMan.UI/Controllers/LogMachineController.cs @@ -80,6 +80,51 @@ namespace MagMan.UI.Controllers return ListRecords; } + /// + /// Processa una chiamata POST per esecuzione chiamata remove range + /// PUT: api/Inventory/upsert/00000000-0000-0000-0000-000000000000 + /// + /// token comunicazione + /// ID del progetto creato da usare come CloudId + [HttpPost("remove/{id}")] + public async Task remove(string id, [FromBody] RestPayload.PeriodData rawData) + { + int answ = 0; + // verifico ci sia valore + if (!string.IsNullOrEmpty(id) && rawData != null) + { + // in primis recupero codice chiave da token... + int nKey = await MTAdmService.MainKeyByToken(id); + int machId = 0; + var machList = await MTAdmService.MachineGetByToken(id); + if (machList != null && machList.Count > 0) + { + var dbResult = machList + .Where(x => x.MainKey == nKey) + .FirstOrDefault(); + if (dbResult != null) + { + machId = dbResult.MachineID; + } + } + if (nKey > 0) + { + try + { + // rimuovo! + answ = await TService.LogMacRemoveRange(nKey, machId, rawData.DtStart, rawData.DtEnd); + } + catch (Exception exc) + { + Log.Error($"LogMachineController.remove | Errore in fase esecuzione richiesta{Environment.NewLine}{exc}"); + } + // resetto cache redis + await MTAdmService.FlushRedisCache(); + } + } + return answ; + } + /// /// Processa una chiamata POST per l'invio di un oggetto di upsert progetto /// PUT: api/Inventory/upsert/00000000-0000-0000-0000-000000000000 @@ -147,4 +192,4 @@ namespace MagMan.UI.Controllers #endregion Private Properties } -} +} \ No newline at end of file diff --git a/MagMan.UI/MagMan.UI.csproj b/MagMan.UI/MagMan.UI.csproj index 995c63f..7af9fbf 100644 --- a/MagMan.UI/MagMan.UI.csproj +++ b/MagMan.UI/MagMan.UI.csproj @@ -2,7 +2,7 @@ net6.0 - 1.0.2405.2316 + 1.0.2406.0812 enable enable true @@ -40,11 +40,10 @@ - - - - - + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/MagMan.UI/appsettings.json b/MagMan.UI/appsettings.json index 6055da9..b9939c0 100644 --- a/MagMan.UI/appsettings.json +++ b/MagMan.UI/appsettings.json @@ -17,6 +17,7 @@ "DbConfig": { //"Server": "localhost", //"Server": "mdb03.ufficio", + //"Server": "mdb01.ufficio,mdb02.ufficio,mdb03.ufficio", "Server": "mdb.ufficio", "nKey": "K0000", "sKey": "M@g4zz1no" diff --git a/Resources/ChangeLog.html b/Resources/ChangeLog.html index d09e7f9..c445468 100644 --- a/Resources/ChangeLog.html +++ b/Resources/ChangeLog.html @@ -1,6 +1,6 @@ MagMan - Wood Warehouse Management System -

Versione: 1.0.2405.2316

+

Versione: 1.0.2406.0812


Note di rilascio:
  • diff --git a/Resources/VersNum.txt b/Resources/VersNum.txt index 2fbede5..78a1c10 100644 --- a/Resources/VersNum.txt +++ b/Resources/VersNum.txt @@ -1 +1 @@ -1.0.2405.2316 +1.0.2406.0812 diff --git a/Resources/manifest.xml b/Resources/manifest.xml index 0e22a91..fd03eed 100644 --- a/Resources/manifest.xml +++ b/Resources/manifest.xml @@ -1,6 +1,6 @@ - 1.0.2405.2316 + 1.0.2406.0812 http://nexus.steamware.net/repository/SWS/MagMan/stable/0/MagMan.UI.zip http://nexus.steamware.net/repository/SWS/MagMan/stable/0/ChangeLog.html false diff --git a/TestConsoleApp/MagmanController.cs b/TestConsoleApp/MagmanController.cs index 8972f1c..d8600c3 100644 --- a/TestConsoleApp/MagmanController.cs +++ b/TestConsoleApp/MagmanController.cs @@ -6,6 +6,7 @@ using NLog.Fluent; using System; using System.Collections.Generic; using System.Linq; +using System.Net.Configuration; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; @@ -96,7 +97,8 @@ namespace DemoApp List recList = lmDbContr.GetUnsentAsc(num2send); // controllo ci sia qulcosa da inviare... if (recList.Count > 0) - { + { + // fintanto che ce ne sono procedo... while (numSent < num2send) { diff --git a/TestConsoleApp/Program.cs b/TestConsoleApp/Program.cs index e08961c..5b3bff5 100644 --- a/TestConsoleApp/Program.cs +++ b/TestConsoleApp/Program.cs @@ -3,6 +3,7 @@ using EgwProxy.MagMan; using EgwProxy.MagMan.DTO; using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -11,27 +12,30 @@ namespace DemoApp { internal class Program { + #region Private Methods - - static async Task Main(string[] args) + private static async Task Main(string[] args) { // indica se eseguire step check syncro remota dati via REST bool testSync = false; // indica se eseguire step check syncro dati LOG da DB a REST remoti bool testDbLog = true; - // num chiave - int keyNum = 470; + //// num chiave SAM + //int keyNum = 470; + // num chiave Lovato + int keyNum = 656; #if DEBUG // Indirizzo server (DEBUG) string servAddr = "localhost:7207"; - // token di auth nostro + // token di auth egalware //string commToken = "e7a81d7a-6fb4-412e-b361-cac7dda517d6"; + // token di auth Lovato string commToken = "79840ba7-00c1-407f-8372-5b60238c04fa"; #else // Indirizzo server (RELEASE) - string servAddr = "magman.egalware.com"; + string servAddr = "magman.egalware.com"; // token di auth string commToken = "22fa4426-6670-41ad-ac2b-d7b5c3dfe849"; @@ -44,7 +48,7 @@ namespace DemoApp Console.WriteLine(sep); Console.WriteLine(); string answ = ""; - DataSyncro commLib = new DataSyncro(servAddr, commToken); + DataSyncro commLib = new DataSyncro(servAddr, commToken, 15000); Console.WriteLine("Premere ENT per check ping"); answ = Console.ReadLine(); bool servOk = commLib.CheckRemote(); @@ -53,12 +57,11 @@ namespace DemoApp // se richiesto eseguo tutto sennò salto if (testSync) { - Console.WriteLine("Premere un tasto per lettura archivio materiali"); answ = Console.ReadLine(); // leggo materiali - var matList = commLib.MaterialsGet(); - if (matList != null) + var matList = await commLib.MaterialsGetAsync(); + if (matList != null && matList.Count > 0) { foreach (var item in matList) { @@ -76,12 +79,16 @@ namespace DemoApp Console.WriteLine(); } } + else + { + Console.WriteLine("No materials found!"); + } Console.WriteLine("Enter to next step"); answ = Console.ReadLine(); // leggo inventario - var inventList = commLib.InventoryGet(0); - if (inventList != null) + var inventList = await commLib.InventoryGetAsync(0); + if (inventList != null && inventList.Count > 0) { foreach (var itemMat in inventList) { @@ -113,13 +120,16 @@ namespace DemoApp Console.WriteLine(); } } + else + { + Console.WriteLine("No inventory found!"); + } Console.WriteLine("Enter to next step"); answ = Console.ReadLine(); - // leggo projectList - var projList = commLib.ProjectGet(keyNum); - if (projList != null) + var projList = await commLib.ProjectGetAsync(keyNum); + if (projList != null && projList.Count > 0) { foreach (var itemProj in projList) { @@ -137,31 +147,37 @@ namespace DemoApp Console.WriteLine(); } } - - Console.WriteLine("Enter to next step: numb of proj to read"); - answ = Console.ReadLine(); - int projId = 1; - int.TryParse(answ, out projId); - var singleProj = commLib.ProjectGetSingle(projId); - if (singleProj != null) + else { - Console.WriteLine(sep); - Console.WriteLine($"Proj {projId} data:"); - Console.WriteLine($"MachineId: {singleProj.MachineCloudId}"); - Console.WriteLine($"Key: {singleProj.KeyNum}"); - Console.WriteLine($"ProjLocalId: {singleProj.ProjLocalId}"); - Console.WriteLine($"ProjExtId: {singleProj.ProjExtId}"); - Console.WriteLine($"BTL filename: {singleProj.BTLFileName}"); - Console.WriteLine($"PType: {singleProj.PType}"); - Console.WriteLine($"Machine: {singleProj.Machine}"); - Console.WriteLine($"Descript: {singleProj.ProjDescription}"); - Console.WriteLine($"Proc time est/real: {singleProj.ProcTimeEst:N1} / {singleProj.ProcTimeReal:N1}"); - Console.WriteLine(sep); - Console.WriteLine(); + Console.WriteLine("No Proj found!"); } + if (projList != null && projList.Count > 0) + { + Console.WriteLine("Enter to next step: numb of proj to read"); + answ = Console.ReadLine(); - answ = Console.ReadLine(); + int projId = 1; + int.TryParse(answ, out projId); + var singleProj = commLib.ProjectGetSingle(projId); + if (singleProj != null) + { + Console.WriteLine(sep); + Console.WriteLine($"Proj {projId} data:"); + Console.WriteLine($"MachineId: {singleProj.MachineCloudId}"); + Console.WriteLine($"Key: {singleProj.KeyNum}"); + Console.WriteLine($"ProjLocalId: {singleProj.ProjLocalId}"); + Console.WriteLine($"ProjExtId: {singleProj.ProjExtId}"); + Console.WriteLine($"BTL filename: {singleProj.BTLFileName}"); + Console.WriteLine($"PType: {singleProj.PType}"); + Console.WriteLine($"Machine: {singleProj.Machine}"); + Console.WriteLine($"Descript: {singleProj.ProjDescription}"); + Console.WriteLine($"Proc time est/real: {singleProj.ProcTimeEst:N1} / {singleProj.ProcTimeReal:N1}"); + Console.WriteLine(sep); + Console.WriteLine(); + } + answ = Console.ReadLine(); + } Console.WriteLine("Inserire Qty materiale syncronizzare (Demo, WxHxL: 100x100x0):"); var sQty = Console.ReadLine(); @@ -180,10 +196,10 @@ namespace DemoApp List newMaterials = new List(); newMaterials.Add(newMat); // invio - commLib.MaterialsSend(newMaterials); + var sendMat = await commLib.MaterialsSendAsync(newMaterials); answ = Console.ReadLine(); - var listAlias = commLib.AliasGet(); + var listAlias = await commLib.AliasGetAsync(); if (listAlias != null) { Console.WriteLine(sep); @@ -195,18 +211,22 @@ namespace DemoApp } Console.WriteLine(sep); } + else + { + Console.WriteLine("No Alias found!"); + } List alias2send = new List(); - alias2send.Add(new AliasDTO() { ValOrig = "Item01", ValAlias = "Gl24h", IsActive = true }); - alias2send.Add(new AliasDTO() { ValOrig = "Item02", ValAlias = "Gl24h", IsActive = true }); - var resAliasSend = commLib.AliasSend(alias2send); + alias2send.Add(new AliasDTO() { ValOrig = "", ValAlias = "Gl24h", IsActive = true }); + alias2send.Add(new AliasDTO() { ValOrig = "GL24H", ValAlias = "Gl24h", IsActive = true }); + var resAliasSend = await commLib.AliasSendAsync(alias2send); } if (testDbLog) { // carico dal DB primi 2000 rec e li invio 100 alla volta... LogMachineController lmc = new LogMachineController(); - int num2send = 2000; + int num2send = 50000; int batchSize = 100; int numSent = 0; @@ -218,9 +238,29 @@ namespace DemoApp lmc.TryFixProjCloudId(); var recList = lmc.GetUnsentAsc(num2send); + if (recList != null && recList.Count < num2send) + { + num2send = recList.Count; + } + bool res = false; // ciclo! + Stopwatch sw = new Stopwatch(); + DateTime inizio = DateTime.Now; + + + // per prima cosa svuoto dati vecchi... + DateTime dtStart = recList.OrderBy(x => x.DtEvent).First().DtEvent; + DateTime dtEnd = recList.OrderByDescending(x => x.DtEvent).First().DtEvent; + // invio cancellazione! + res = commLib.LogMachineRemoveRange(dtStart, dtEnd); + sw.Stop(); + Console.WriteLine($"Cancellazione dati preesistenti effettuata | elapsed {sw.Elapsed.TotalSeconds:N3} sec"); + while (numSent < num2send) { + //commLib = new DataSyncro(servAddr, commToken, 5000); + sw.Restart(); + res = false; var currList = recList .Skip(numSent) .Take(batchSize) @@ -230,25 +270,43 @@ namespace DemoApp .Select(x => LogMachineController.ConvToItemDto(x)) .ToList(); // invio! - var res = await commLib.LogMachineSendAsync(listDto); + try + { + //res = commLib.LogMachineSend(listDto); + res = await commLib.LogMachineSendAsync(listDto); + } + catch (Exception exc) + { + Console.WriteLine(exc); + } if (res) { // registro dati inviati... lmc.SetDtSent(currList); - Console.WriteLine($"Inviati {batchSize}rec | {numSent} --> {numSent + batchSize}"); - numSent += batchSize; + sw.Stop(); + Console.WriteLine($"Inviati {batchSize}rec | {numSent} --> {numSent + batchSize} | elapsed {sw.Elapsed.TotalSeconds:N3} sec"); } else { - Console.WriteLine($"Errore in invio logMacchina"); + sw.Stop(); + Console.WriteLine($"Errore in invio logMacchina, attesa 150ms | elapsed {sw.Elapsed.TotalSeconds:N3} sec"); + await Task.Delay(150); } + numSent += batchSize; } + var durTot = DateTime.Now.Subtract(inizio); + Console.WriteLine($"Durata totale: {durTot.TotalSeconds:N3} sec"); Console.WriteLine(sep); Console.WriteLine(); + if (durTot.TotalSeconds > 1.5) + { + await Task.Delay(250); + } } - Console.WriteLine("Enter to close"); answ = Console.ReadLine(); } + + #endregion Private Methods } -} +} \ No newline at end of file