diff --git a/MP-STATS.sln b/MP-STATS.sln index 33e62912..14d527c2 100644 --- a/MP-STATS.sln +++ b/MP-STATS.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32126.317 +# Visual Studio Version 18 +VisualStudioVersion = 18.5.11723.231 stable MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MP.Stats", "MP.Stats\MP.Stats.csproj", "{D9901B50-E61C-400C-B62C-FA060CF72C29}" EndProject diff --git a/MP.Data/Controllers/MpInveController.cs b/MP.Data/Controllers/MpInveController.cs index 7e3ecb0b..aadbc604 100644 --- a/MP.Data/Controllers/MpInveController.cs +++ b/MP.Data/Controllers/MpInveController.cs @@ -17,6 +17,10 @@ namespace MP.Data.Controllers public MpInveController(IConfiguration configuration) { _configuration = configuration; + string connStr = _configuration.GetConnectionString("MP.Data"); + options = new DbContextOptionsBuilder() + .UseSqlServer(connStr) + .Options; Log.Info("Avviata classe MpInveController"); } @@ -84,6 +88,7 @@ namespace MP.Data.Controllers #endregion gestione articoli + private DbContextOptions options; #region gestione config /// @@ -93,7 +98,7 @@ namespace MP.Data.Controllers public List ConfigGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetConfig @@ -350,7 +355,7 @@ namespace MP.Data.Controllers public List ElencoOperatori() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbOperatori @@ -372,7 +377,7 @@ namespace MP.Data.Controllers { List dbResult = new List(); bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbOperatori @@ -644,7 +649,7 @@ namespace MP.Data.Controllers InventorySessionModel dbResult = new InventorySessionModel(); using (var dbCtx = new MoonPro_InveContext(_configuration)) { - + dbResult = dbCtx .DbInveSess .Where(x => x.InveSessID == sessID) diff --git a/MP.Data/Controllers/MpIocController.cs b/MP.Data/Controllers/MpIocController.cs index 4a9cf45a..4c3cb3be 100644 --- a/MP.Data/Controllers/MpIocController.cs +++ b/MP.Data/Controllers/MpIocController.cs @@ -9,16 +9,21 @@ using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; +using static MP.Core.Objects.Enums; namespace MP.Data.Controllers { - public class MpIocController /*: IDisposable*/ + public class MpIocController { #region Public Constructors public MpIocController(IConfiguration configuration) { _configuration = configuration; + string connStr = _configuration.GetConnectionString("MP.Data"); + options = new DbContextOptionsBuilder() + .UseSqlServer(connStr) + .Options; Log.Info("Avviata classe MpIocController"); } @@ -38,7 +43,7 @@ namespace MP.Data.Controllers /// public async Task AlarmLogInsertAsync(DateTime dtRif, string machineId, string memAddress, int memIndex, int statusVal, string valDecoded) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var DtRif = new SqlParameter("@DtRif", dtRif); var MachineId = new SqlParameter("@MachineId", machineId); @@ -58,7 +63,7 @@ namespace MP.Data.Controllers /// public async Task> AnagStatiGetAllAsync() { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var dbResult = await dbCtx .DbSetAnagStati @@ -76,7 +81,7 @@ namespace MP.Data.Controllers /// public async Task> ArticoliGetLastByMaccAsync(string idxMacc) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacc); var dbResult = await dbCtx @@ -102,7 +107,7 @@ namespace MP.Data.Controllers /// public async Task AutoStartOdlAsync(int idxOdl, int MatrOpr, string idxMacchina, decimal tCRich, int pzPallet, string note, bool startNewOdl, int qtyRich, string keyRich) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxOdl = new SqlParameter("@idxOdl ", idxOdl); var MatrApp = new SqlParameter("@MatrApp ", MatrOpr); @@ -119,6 +124,94 @@ namespace MP.Data.Controllers return result != 0; } + /// + /// Processing intera catena eventi verifica cambio stato in singola transazione e con unico DbContext + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public async Task CheckCambiaStatoBatchAsync(tipoInputEvento tipoInput, string IdxMacchina, DateTime InizioStato, int IdxTipo, string CodArt, string Value, int MatrOpr, string pallet) + { + await using var dbCtx = new MoonProContext(options); + //await using var tx = await dbCtx.Database.BeginTransactionAsync(); + + try + { + var pIdxMacchina = new SqlParameter("@IdxMacchina", IdxMacchina); + var pIdxTipo = new SqlParameter("@IdxTipo", IdxTipo); + var pInizioStato = new SqlParameter("@InizioStato", InizioStato); + var pCodArticolo = new SqlParameter("@codArticolo", CodArt); + var pValue = new SqlParameter("@Value", Value); + var pMatrOpr = new SqlParameter("@MatrOpr", MatrOpr); + var pPallet = new SqlParameter("@pallet", pallet); + + string opType = tipoInput switch + { + tipoInputEvento.barcode => "BARCODE", + tipoInputEvento.hw => "HW", + _ => "ND" + }; + + TransizioneStatiModel? rigaTrans = null; + + if (opType != "ND") + { + string sql = tipoInput switch + { + tipoInputEvento.barcode => "EXEC dbo.stp_TS_getUserForcedTrans @IdxMacchina, @IdxTipo", + tipoInputEvento.hw => "EXEC dbo.stp_TS_getByIdxMacchIdxTipoEv @IdxMacchina, @IdxTipo", + _ => string.Empty + }; + + // ✅ prima chiamata ASYNC + rigaTrans = (await dbCtx.DbSetSMES + .FromSqlRaw(sql, pIdxMacchina, pIdxTipo) + .AsNoTracking() + .ToListAsync() + ).FirstOrDefault(); + } + + if (rigaTrans != null && rigaTrans.IdxStato != rigaTrans.next_IdxStato) + { + var pIdxStato = new SqlParameter("@IdxStato", rigaTrans.next_IdxStato); + + await dbCtx.Database.ExecuteSqlRawAsync( + "EXEC dbo.stp_DDB_InsStatoBatch @IdxMacchina, @InizioStato, @IdxStato, @codArticolo, @Value, @MatrOpr, @pallet", + pIdxMacchina, pInizioStato, pIdxStato, pCodArticolo, pValue, pMatrOpr, pPallet); + + // eseguo solo se evento manuale/barcode + if (tipoInput == tipoInputEvento.barcode) + { + var pMaxAgeSec = new SqlParameter("@maxAgeSec", 0); + await dbCtx.Database.ExecuteSqlRawAsync( + "EXEC stp_MSE_recalc @maxAgeSec, @idxMacchina", + pMaxAgeSec, pIdxMacchina); + } + } + else + { + Log.Debug($"Nessun cambio stato richiesto | {opType} | {IdxMacchina} | {IdxTipo}"); + } + + // Nessuna eccezione = successo + //await tx.CommitAsync(); + return true; + } + catch (Exception ex) + { + //await tx.RollbackAsync(); + // Log dettagliato errore + Log.Error(ex, $"Errore in CheckCambiaStatoBatchAsync: {IdxMacchina} | {tipoInput}"); + throw; // O return false; se il chiamante gestisce fallimenti + } + } + /// /// Effettua conferma prod macchina dell'intero periodo da confermare (ultima conferma - dtEvent) /// @@ -131,7 +224,7 @@ namespace MP.Data.Controllers /// public async Task ConfermaProdMacchinaAsync(string idxMacchina, int modoConfProd, int numPzConfermati, int numPzScarto, DateTime DataOraApp, int MatrOpr) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var DataOra = new SqlParameter("@DataOra ", DateTime.Now); @@ -174,7 +267,7 @@ namespace MP.Data.Controllers /// public async Task ConfermaProdMacchinaFullAsync(string idxMacchina, int modoConfProd, int numPzConfermati, int numPzLasciati, int numPzScarto, DateTime DataOraApp, int MatrOpr) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var DataOra = new SqlParameter("@DataOra ", DateTime.Now); @@ -233,7 +326,7 @@ namespace MP.Data.Controllers /// public async Task> ConfigGetAllAsync() { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var dbResult = await dbCtx .DbSetConfig @@ -250,7 +343,7 @@ namespace MP.Data.Controllers /// public async Task ConfigUpdateAsync(ConfigModel updRec) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); bool fatto = false; var dbResult = dbCtx @@ -272,7 +365,7 @@ namespace MP.Data.Controllers /// public async Task> DatiMacchineGetAllAsync() { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var dbResult = await dbCtx .DbSetDatiMacchine @@ -295,7 +388,7 @@ namespace MP.Data.Controllers /// public async Task DDB_InsStatoBatchAsync(string idxMacchina, DateTime inizioStato, int idxStato, string codArt, string value, int matrOpr, string pallet) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var InizioStato = new SqlParameter("@InizioStato", inizioStato); @@ -318,7 +411,7 @@ namespace MP.Data.Controllers /// public async Task> DecNumArtGetFiltAsync(string codArt = "") { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var query = dbCtx.DbSetDecNumArt .AsNoTracking() @@ -332,13 +425,6 @@ namespace MP.Data.Controllers return dbResult; } -#if false - public void Dispose() - { - _configuration = null; - } -#endif - /// /// Stored x recuperare ultimi dossier macchina /// @@ -366,12 +452,64 @@ namespace MP.Data.Controllers /// public async Task EvListInsertAsync(EventListModel newRec) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); dbCtx.DbSetEvList.Add(newRec); return await dbCtx.SaveChangesAsync() > 0; } + /// + /// Aggiunta record MicroStato + EventList + /// + /// + /// + /// + public async Task EvListMicroStatoInsertAsync(MicroStatoMacchinaModel newRecMsm, EventListModel newRecEv) + { + // eseguo in transazione... + await using var dbCtx = new MoonProContext(options); + await using var tx = await dbCtx.Database.BeginTransactionAsync(); + + try + { + // inizio con record microstato... + var actRec = await dbCtx + .DbSetMicroStatoMacc + .FindAsync(newRecMsm.IdxMacchina); + //.SingleOrDefaultAsync(); + if (actRec == null) + { + dbCtx.DbSetMicroStatoMacc.Add(newRecMsm); + } + else + { + actRec.IdxMicroStato = newRecMsm.IdxMicroStato; + actRec.InizioStato = newRecMsm.InizioStato; + actRec.Value = newRecMsm.Value; + + // Update() allega l'entità e segna tutti i campi come Modified + dbCtx.DbSetMicroStatoMacc.Update(actRec); +#if false + dbCtx.Entry(actRec).State = EntityState.Modified; +#endif + } + + // ora record EVList + dbCtx.DbSetEvList.Add(newRecEv); + + // EF Core 8 raggruppa automaticamente INSERT/UPDATE in un batch + var rowsAffected = await dbCtx.SaveChangesAsync(); + await tx.CommitAsync(); + + return rowsAffected > 0; + } + catch + { + await tx.RollbackAsync(); + throw; + } + } + /// /// Chiamata x stored recupero FluxLog x macchina (first) /// @@ -467,7 +605,7 @@ namespace MP.Data.Controllers public async Task KeepAliveUpsertAsync(string IdxMacc, DateTime OraServer, DateTime OraMacc) { bool fatto = false; - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var currRec = await dbCtx .DbSetKeepAlive @@ -500,7 +638,7 @@ namespace MP.Data.Controllers public async Task> ListLinkFiltAsync(string tipoLink) { List dbResult = new List(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); dbResult = await dbCtx .DbSetLinkMenu @@ -520,7 +658,7 @@ namespace MP.Data.Controllers public async Task> ListValuesFiltAsync(string tabName, string fieldName) { List dbResult = new List(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var query = dbCtx .DbSetListValues @@ -544,7 +682,7 @@ namespace MP.Data.Controllers public async Task> Macchine2SlaveAsync() { List dbResult = new List(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); dbResult = await dbCtx .DbSetM2S @@ -562,7 +700,7 @@ namespace MP.Data.Controllers public async Task> MacchineGetAllAsync() { List dbResult = new List(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); dbResult = await dbCtx .DbSetMacchine @@ -574,7 +712,7 @@ namespace MP.Data.Controllers public async Task MacchineGetByIdxAsync(string IdxMacchina) { MacchineModel dbResult = null; - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); dbResult = await dbCtx .DbSetMacchine @@ -591,7 +729,7 @@ namespace MP.Data.Controllers public async Task> MacchineGetFiltAsync(string codGruppo) { List dbResult = new List(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); if (codGruppo == "*") { @@ -625,7 +763,7 @@ namespace MP.Data.Controllers /// public async Task MacchineUpsertAsync(MacchineModel entity) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); // Recuperiamo l'entità tracciata dal context var trackedEntity = await dbCtx @@ -653,7 +791,7 @@ namespace MP.Data.Controllers public async Task> MicroStatoMacchinaGetByIdxMaccAsync(string IdxMacc) { List dbResult = new List(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); dbResult = await dbCtx .DbSetMicroStatoMacc @@ -671,7 +809,7 @@ namespace MP.Data.Controllers public async Task MicroStatoMacchinaUpsertAsync(MicroStatoMacchinaModel newRec) { bool fatto = false; - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var actRec = await dbCtx .DbSetMicroStatoMacc @@ -704,7 +842,7 @@ namespace MP.Data.Controllers public async Task> MseGetAllAsync(int maxAge = 2000) { List dbResult = new List(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var maxAgeSec = new SqlParameter("@maxAgeSec", maxAge); @@ -724,7 +862,7 @@ namespace MP.Data.Controllers /// public async Task OdlAutoDayGenAsync(string idxMacchina, DateTime dataInizio, DateTime dataFine, string codArticolo) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var DataInizio = new SqlParameter("@DataInizio", dataInizio); @@ -746,7 +884,7 @@ namespace MP.Data.Controllers /// public async Task OdlAutoDayGenFullAsync(string idxMacchina, DateTime dataInizio, DateTime dataFine, string codArticolo, int? pzPODL, int? pzPallet, string? keyRichiesta, int? tcAssegnato, string? codGruppo, bool flgCreaPODL, bool flgCheckTC) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var DataInizio = new SqlParameter("@DataInizio", dataInizio); @@ -775,7 +913,7 @@ namespace MP.Data.Controllers public async Task OdlCurrByMaccAsync(string idxMacchina) { ODLExpModel answ = new(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var pIdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); // attenzione: se la stored resituisce una tabella, il primo elemento va recuperato in RAM!!! @@ -798,7 +936,7 @@ namespace MP.Data.Controllers /// public async Task OdlFixMachineSlave(string idxMacchina, int numDayPrev, int doInsert) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var idxMaccParam = new SqlParameter("@IdxMacchina", idxMacchina ?? ""); var numDayPrevParam = new SqlParameter("@NumDayPrev", numDayPrev); @@ -820,7 +958,7 @@ namespace MP.Data.Controllers /// public async Task OdlFixMachineSlaveAsync(string idxMacchina, int numDayPrev, int doInsert) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var NumDayPrev = new SqlParameter("@NumDayPrev", numDayPrev); @@ -839,7 +977,7 @@ namespace MP.Data.Controllers public async Task OdlLastByMaccAsync(string idxMacchina) { ODLExpModel answ = new(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var pIdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); // attenzione: se la stored resituisce una tabella, il primo elemento va recuperato in RAM!!! @@ -863,7 +1001,7 @@ namespace MP.Data.Controllers public async Task> OdlListByMaccPeriodoAsync(string idxMacchina, DateTime dtStart, DateTime dtEnd) { List dbResult = new List(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var DataFrom = new SqlParameter("@dataFrom", dtStart); @@ -885,7 +1023,7 @@ namespace MP.Data.Controllers public async Task PezziProdMacchinaAsync(string idxMacchina) { PzProdModel dbResult = new PzProdModel(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var pIdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); dbResult = (await dbCtx @@ -908,7 +1046,7 @@ namespace MP.Data.Controllers public async Task> POdlGetByMaccArtAsync(string idxMacchina, string codArticolo, string codGruppo, bool onlyFree) { List dbResult = new List(); - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var pIdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var pCodArticolo = new SqlParameter("@CodArticolo", codArticolo); @@ -931,7 +1069,7 @@ namespace MP.Data.Controllers /// public async Task RecalcMseAsync(string idxMacchina, int maxAgeSec) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var rigaProd = await StatoProdMacchinaAsync(idxMacchina, DateTime.Now); var MaxAgeSec = new SqlParameter("@maxAgeSec ", maxAgeSec); @@ -955,7 +1093,7 @@ namespace MP.Data.Controllers /// public async Task RegControlliInsertAsync(string idxMacchina, int matrOpr, bool esitoOk, string note, DateTime dataOra) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var MatrOpr = new SqlParameter("@MatrOpr", matrOpr); @@ -976,7 +1114,7 @@ namespace MP.Data.Controllers /// public async Task RegDichiarInsertAsync(RegistroDichiarazioniModel newRec) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var TagCode = new SqlParameter("@TagCode", newRec.TagCode); var IdxMacchina = new SqlParameter("@IdxMacchina", newRec.IdxMacchina); @@ -998,7 +1136,7 @@ namespace MP.Data.Controllers /// public async Task RegDichiarUpdateAsync(RegistroDichiarazioniModel newRec) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var Original_IdxDich = new SqlParameter("@Original_IdxDich", newRec.IdxDich); var DtRec = new SqlParameter("@DtRec", newRec.DtRec); @@ -1019,7 +1157,7 @@ namespace MP.Data.Controllers /// public async Task RegScartiInsertAsync(RegistroScartiModel newRec) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@idxMacchina", newRec.IdxMacchina); var DataOra = new SqlParameter("@DataOra", newRec.DataOra); @@ -1036,21 +1174,6 @@ namespace MP.Data.Controllers return result.Count != 0; } - /// - /// Aggiunta record RemoteRebootLog - /// - /// - /// - public async Task RemRebootLogAddAsync(RemoteRebootLogModel newRec) - { - using var dbCtx = new MoonProContext(_configuration); - - var dbResult = dbCtx - .DbSetRemRebLog - .Add(newRec); - - return await dbCtx.SaveChangesAsync() > 0; - } /// /// Aggiunta record RemoteRebootLog /// @@ -1061,7 +1184,7 @@ namespace MP.Data.Controllers public async Task RemRebootLogAddAndCleanAsync(RemoteRebootLogModel newRec, bool doClean, int num2keep) { bool fatto = false; - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); // 1. Transazione minima: SOLO INSERT + COMMIT await using var tx = await dbCtx.Database.BeginTransactionAsync(); @@ -1086,7 +1209,6 @@ namespace MP.Data.Controllers await dbCtx.Database.ExecuteSqlRawAsync( "EXEC dbo.stp_RRL_KeepLatest @num2keep, @multiplier", param, new SqlParameter("@multiplier", 2.5f)); // Fisso e poiché è coinvolto MAC address è + alto - } catch (Exception ex) { @@ -1098,13 +1220,29 @@ namespace MP.Data.Controllers return fatto; } + /// + /// Aggiunta record RemoteRebootLog + /// + /// + /// + public async Task RemRebootLogAddAsync(RemoteRebootLogModel newRec) + { + using var dbCtx = new MoonProContext(options); + + var dbResult = dbCtx + .DbSetRemRebLog + .Add(newRec); + + return await dbCtx.SaveChangesAsync() > 0; + } + /// /// Recupera tutti i record di RemoteRebootLog /// /// public async Task> RemRebootLogGetAllAsync() { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var dbResult = await dbCtx .DbSetRemRebLog @@ -1120,7 +1258,7 @@ namespace MP.Data.Controllers /// public async Task> RemRebootLogGetLastAsync() { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var dbResult = await dbCtx .DbSetRemRebLog .FromSqlRaw("EXEC stp_RRL_getLast") @@ -1135,7 +1273,7 @@ namespace MP.Data.Controllers /// public async Task RemRebootLogKeepLastAsync(int num2keep) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var pNum2Keep = new SqlParameter("@num2keep", num2keep); // La SP gestisce già la logica di soglia (1.5x), ma la specifico x sicurezza @@ -1153,7 +1291,7 @@ namespace MP.Data.Controllers /// public async Task SignalLogInsertAsync(SignalLogModel newRec) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var currRec = dbCtx .DbSetSignalLog @@ -1169,7 +1307,7 @@ namespace MP.Data.Controllers /// public async Task> SMES_getHwTransitionsAsync(string idxMacchina, int idxTipo) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var IdxTipo = new SqlParameter("@IdxTipo", idxTipo); @@ -1189,7 +1327,7 @@ namespace MP.Data.Controllers /// public async Task> SMES_getUserForcedAsync(string idxMacchina, int idxTipo) { - using var dbCtx = new MoonProContext(_configuration); + await using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var IdxTipo = new SqlParameter("@IdxTipo", idxTipo); @@ -1209,7 +1347,7 @@ namespace MP.Data.Controllers public List StateMachineIngressi(int idxFam) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxFamIn = new SqlParameter("@IdxFamigliaIngresso", idxFam); dbResult = dbCtx @@ -1228,7 +1366,7 @@ namespace MP.Data.Controllers /// public async Task> StateMachineIngressiAsync(int idxFam) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxFamIn = new SqlParameter("@IdxFamigliaIngresso", idxFam); var dbResult = await dbCtx @@ -1248,7 +1386,7 @@ namespace MP.Data.Controllers /// public async Task StatoProdMacchinaAsync(string idxMacchina, DateTime dtReq) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var DataOra = new SqlParameter("@DataOra ", dtReq); @@ -1268,7 +1406,7 @@ namespace MP.Data.Controllers /// public async Task> VMSFDGetAllAsync() { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var dbResult = await dbCtx .DbSetMSFD @@ -1286,7 +1424,7 @@ namespace MP.Data.Controllers /// public async Task VMSFDGetByMaccAsync(string idxMacc) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacc); var dbResult = (await dbCtx @@ -1306,7 +1444,7 @@ namespace MP.Data.Controllers /// public async Task> VMSFDGetMultiByMaccAsync(string idxMacc) { - using var dbCtx = new MoonProContext(_configuration); + using var dbCtx = new MoonProContext(options); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacc); @@ -1324,9 +1462,16 @@ namespace MP.Data.Controllers #region Private Fields private static IConfiguration _configuration; - private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + private DbContextOptions options; #endregion Private Fields + +#if false + public void Dispose() + { + _configuration = null; + } +#endif } } \ No newline at end of file diff --git a/MP.Data/Controllers/MpLandController.cs b/MP.Data/Controllers/MpLandController.cs index e744b638..956c460c 100644 --- a/MP.Data/Controllers/MpLandController.cs +++ b/MP.Data/Controllers/MpLandController.cs @@ -1,16 +1,11 @@ -using Microsoft.Data.SqlClient; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; -using MP.Core.Objects; using MP.Data.DbModels; using NLog; using System; using System.Collections.Generic; using System.Data; using System.Linq; -using System.Threading.Tasks; -using ZXing; -using static MP.Core.Objects.Enums; namespace MP.Data.Controllers { @@ -24,6 +19,10 @@ namespace MP.Data.Controllers public MpLandController(IConfiguration configuration) { _configuration = configuration; + string connStr = _configuration.GetConnectionString("MP.Data"); + options = new DbContextOptionsBuilder() + .UseSqlServer(connStr) + .Options; Log.Info("Avviato MpLandController"); } @@ -67,7 +66,7 @@ namespace MP.Data.Controllers // leggo per DB principale if (!string.IsNullOrEmpty(_configuration.GetConnectionString("MP.All"))) { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var singleRes = dbCtx .DbSetDbSize @@ -113,7 +112,7 @@ namespace MP.Data.Controllers } } } - catch(Exception exc) + catch (Exception exc) { Log.Error($"Eccezione in AllDbInfo:{Environment.NewLine}{exc}"); } @@ -127,7 +126,7 @@ namespace MP.Data.Controllers public List ConfigGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetConfig @@ -150,7 +149,7 @@ namespace MP.Data.Controllers public List ElencoOperatori() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbOperatori @@ -169,7 +168,7 @@ namespace MP.Data.Controllers public List MacchineGetAll() { List dbResult = new List(); - using (MoonProContext localDbCtx = new MoonProContext(_configuration)) + using (MoonProContext localDbCtx = new MoonProContext(options)) { dbResult = localDbCtx .DbSetMacchine @@ -185,7 +184,7 @@ namespace MP.Data.Controllers public List RemRebootLogGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetRemRebLog @@ -203,7 +202,7 @@ namespace MP.Data.Controllers public List RemRebootLogGetLast() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetRemRebLog @@ -221,7 +220,7 @@ namespace MP.Data.Controllers public List RemRebootLogGetLastNoMacc() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetRemRebLog @@ -262,8 +261,8 @@ namespace MP.Data.Controllers #region Private Fields private static IConfiguration _configuration; - private static Logger Log = LogManager.GetCurrentClassLogger(); + private DbContextOptions options; #endregion Private Fields } diff --git a/MP.Data/Controllers/MpMonController.cs b/MP.Data/Controllers/MpMonController.cs index 300bfe46..e45f9913 100644 --- a/MP.Data/Controllers/MpMonController.cs +++ b/MP.Data/Controllers/MpMonController.cs @@ -17,6 +17,11 @@ namespace MP.Data.Controllers public MpMonController(IConfiguration configuration) { _configuration = configuration; + + string connStr = _configuration.GetConnectionString("MP.Data"); + options = new DbContextOptionsBuilder() + .UseSqlServer(connStr) + .Options; Log.Info("Avviata classe MpMonController"); } @@ -33,7 +38,7 @@ namespace MP.Data.Controllers public List ArticoliGetSearch(int numRecord, string searchVal = "") { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetStatArticoli @@ -53,7 +58,7 @@ namespace MP.Data.Controllers public List ConfigGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetConfig @@ -75,7 +80,7 @@ namespace MP.Data.Controllers public List MacchineGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetMacchine @@ -96,7 +101,7 @@ namespace MP.Data.Controllers List dbResult = new List(); try { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { if (codGruppo == "*") { @@ -140,7 +145,7 @@ namespace MP.Data.Controllers public async Task> MseGetAllAsync(int maxAge = 2000) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var maxAgeSec = new SqlParameter("@maxAgeSec", maxAge); @@ -161,7 +166,7 @@ namespace MP.Data.Controllers public bool RollBackEntity(object item) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -183,8 +188,8 @@ namespace MP.Data.Controllers #region Private Fields private static IConfiguration _configuration; - private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + private DbContextOptions options; #endregion Private Fields } diff --git a/MP.Data/Controllers/MpSpecController.cs b/MP.Data/Controllers/MpSpecController.cs index 99470205..efa33086 100644 --- a/MP.Data/Controllers/MpSpecController.cs +++ b/MP.Data/Controllers/MpSpecController.cs @@ -22,6 +22,10 @@ namespace MP.Data.Controllers public MpSpecController(IConfiguration configuration) { _configuration = configuration; + string connStr = _configuration.GetConnectionString("MP.Data"); + options = new DbContextOptionsBuilder() + .UseSqlServer(connStr) + .Options; Log.Info("Avviata classe MpSpecController"); } @@ -36,7 +40,7 @@ namespace MP.Data.Controllers public List AnagCounters() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetAnagCount @@ -56,7 +60,7 @@ namespace MP.Data.Controllers bool outTable = true; if (outTable) { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var pCntType = new SqlParameter("@CntType", cntType); var pLastNum = new SqlParameter @@ -81,7 +85,7 @@ namespace MP.Data.Controllers else { // se si volessero impiegare parametri OUTPUT (qui ne mancherebbe 1 nella stored x CntCode...) - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var pCntType = new SqlParameter("@CntType", cntType); var pLastNum = new SqlParameter @@ -121,7 +125,7 @@ namespace MP.Data.Controllers public List AnagEventiGeneral(string TableName = "EvList", string FieldName = "Common") { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var pTableName = new SqlParameter("@TableName", TableName); var pFieldName = new SqlParameter("@FieldName", FieldName); @@ -142,7 +146,7 @@ namespace MP.Data.Controllers public List AnagEventiGetByMacc(string IdxMac) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacch = new SqlParameter("@idxMacchina", IdxMac); @@ -172,7 +176,7 @@ namespace MP.Data.Controllers public bool AnagGruppiDelete(AnagGruppiModel updRec) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var dbRec = dbCtx .DbSetAnagGruppi @@ -206,7 +210,7 @@ namespace MP.Data.Controllers public List AnagGruppiGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetAnagGruppi @@ -225,7 +229,7 @@ namespace MP.Data.Controllers public List AnagGruppiGetTipo(string tipoGruppo) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetAnagGruppi @@ -253,7 +257,7 @@ namespace MP.Data.Controllers public List AnagGruppiRepartoDTO() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { // in primis recupero i reparti... var listReparti = AnagGruppiGetTipo("REPARTO"); @@ -292,7 +296,7 @@ namespace MP.Data.Controllers public bool AnagGruppiUpsert(AnagGruppiModel updRec) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var dbRec = dbCtx .DbSetAnagGruppi @@ -323,7 +327,7 @@ namespace MP.Data.Controllers public List AnagKeyValGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetAKV @@ -379,7 +383,7 @@ namespace MP.Data.Controllers public async Task ArticoliDeleteRecord(AnagArticoliModel currRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -411,7 +415,7 @@ namespace MP.Data.Controllers public List ArticoliGetByTipo(string tipo, string azienda = "*") { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetArticoli @@ -432,7 +436,7 @@ namespace MP.Data.Controllers public List ArticoliGetSearch(int numRecord, string searchVal = "") { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetArticoli @@ -455,7 +459,7 @@ namespace MP.Data.Controllers public List ArticoliGetSearch(int numRecord, string azienda = "*", string searchVal = "") { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetArticoli @@ -475,7 +479,7 @@ namespace MP.Data.Controllers public List ArticoliGetUsed() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetArticoli @@ -494,7 +498,7 @@ namespace MP.Data.Controllers public async Task ArticoliUpdateRecord(AnagArticoliModel editRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -534,7 +538,7 @@ namespace MP.Data.Controllers public List ConfigGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetConfig @@ -553,7 +557,7 @@ namespace MP.Data.Controllers { bool fatto = false; ConfigModel dbResult = new ConfigModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetConfig @@ -576,7 +580,7 @@ namespace MP.Data.Controllers public List DatiMacchineGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetDatiMacchine @@ -776,7 +780,7 @@ namespace MP.Data.Controllers public List ElencoOperatori() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbOperatori @@ -796,7 +800,7 @@ namespace MP.Data.Controllers public async Task EvListInsert(EventListModel newRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1048,7 +1052,7 @@ namespace MP.Data.Controllers public bool Grp2MaccDelete(Gruppi2MaccModel rec2del) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var dbRec = dbCtx .DbSetGrp2Macc @@ -1072,7 +1076,7 @@ namespace MP.Data.Controllers public bool Grp2MaccInsert(Gruppi2MaccModel upsRec) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var dbRec = dbCtx .DbSetGrp2Macc @@ -1097,7 +1101,7 @@ namespace MP.Data.Controllers public bool Grp2OperDelete(Gruppi2OperModel rec2del) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var dbRec = dbCtx .DbSetGrp2Oper @@ -1121,7 +1125,7 @@ namespace MP.Data.Controllers public bool Grp2OperInsert(Gruppi2OperModel upsRec) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var dbRec = dbCtx .DbSetGrp2Oper @@ -1145,7 +1149,7 @@ namespace MP.Data.Controllers public bool IstKitDelete(IstanzeKitModel rec2del) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = dbCtx .DbSetInstKit @@ -1173,7 +1177,7 @@ namespace MP.Data.Controllers public List IstKitFilt(string keyKit, string keyExtOrd) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetInstKit @@ -1192,7 +1196,7 @@ namespace MP.Data.Controllers public bool IstKitInsertByWKS(string CodArtParent, string KeyFilt) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var pCodArtParent = new SqlParameter("@CodArtParent", CodArtParent); var pKeyFilt = new SqlParameter("@KeyFilt", KeyFilt); @@ -1212,7 +1216,7 @@ namespace MP.Data.Controllers public bool IstKitUpsert(IstanzeKitModel editRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = dbCtx .DbSetInstKit @@ -1274,7 +1278,7 @@ namespace MP.Data.Controllers public List ListLinkAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetLinkMenu @@ -1293,7 +1297,7 @@ namespace MP.Data.Controllers public List ListLinkFilt(string tipoLink) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetLinkMenu @@ -1319,7 +1323,7 @@ namespace MP.Data.Controllers public List ListODLFilt(bool inCorso, string codArt, string keyRichPart, string Reparto, string IdxMacchina, DateTime startDate, DateTime endDate) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var InCorso = new SqlParameter("@InCorso", inCorso); var CodArt = new SqlParameter("@CodArt", codArt); @@ -1347,7 +1351,7 @@ namespace MP.Data.Controllers public List ListPODL_ByCodArt(string CodArticolo, bool OnlyAvail) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var pCodArticolo = new SqlParameter("@CodArticolo", CodArticolo); var pOnlyAvail = new SqlParameter("@onlyAvail", OnlyAvail); @@ -1370,7 +1374,7 @@ namespace MP.Data.Controllers public List ListPODL_ByKitParent(int IdxPodlParent) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var pIdxPodlParent = new SqlParameter("@IdxPodlParent", IdxPodlParent); @@ -1394,7 +1398,7 @@ namespace MP.Data.Controllers public List ListPODL_KitFilt(bool lanciato, string keyRichPart, string idxMacchina, string codGruppo, DateTime startDate, DateTime endDate) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var Lanc = new SqlParameter("@Lanciato", lanciato); var KeyRich = new SqlParameter("@KeyRich", keyRichPart); @@ -1423,7 +1427,7 @@ namespace MP.Data.Controllers public List ListPODLFilt(bool lanciato, string keyRichPart, string idxMacchina, string codGruppo, DateTime startDate, DateTime endDate) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var Lanc = new SqlParameter("@Lanciato", lanciato); var KeyRich = new SqlParameter("@KeyRich", keyRichPart); @@ -1450,7 +1454,7 @@ namespace MP.Data.Controllers public List ListValuesFilt(string tabName, string fieldName) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetListValues @@ -1472,7 +1476,7 @@ namespace MP.Data.Controllers List dbResult = new List(); try { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { if (MatrOpr == 0) { @@ -1522,7 +1526,7 @@ namespace MP.Data.Controllers List dbResult = new List(); try { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { if (codGruppo == "*") { @@ -1577,27 +1581,6 @@ namespace MP.Data.Controllers return dbResult; } - /// - /// Elenco da tabella MappaStatoExplModel - /// - /// - public List MseGetAll(int maxAge = 2000) - { - List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) - { - var maxAgeSec = new SqlParameter("@maxAgeSec", maxAge); - - dbResult = dbCtx - .DbSetMSE - .FromSqlRaw("EXEC stp_MSE_getData @maxAgeSec", maxAgeSec) - .AsNoTracking() - .ToList(); - } - return dbResult; - } - - /// /// Aggiornamento record Microstato macchina /// @@ -1606,7 +1589,7 @@ namespace MP.Data.Controllers public async Task MicroStatoMacchinaUpsert(MicroStatoMacchinaModel newRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = await dbCtx .DbSetMicroStatoMacc @@ -1633,6 +1616,26 @@ namespace MP.Data.Controllers return fatto; } + /// + /// Elenco da tabella MappaStatoExplModel + /// + /// + public List MseGetAll(int maxAge = 2000) + { + List dbResult = new List(); + using (var dbCtx = new MoonProContext(options)) + { + var maxAgeSec = new SqlParameter("@maxAgeSec", maxAge); + + dbResult = dbCtx + .DbSetMSE + .FromSqlRaw("EXEC stp_MSE_getData @maxAgeSec", maxAgeSec) + .AsNoTracking() + .ToList(); + } + return dbResult; + } + /// /// Elenco ODL dato batch selezionato /// @@ -1667,7 +1670,7 @@ namespace MP.Data.Controllers public ODLExpModel OdlByKey(int IdxOdl) { ODLExpModel dbResult = new ODLExpModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1701,7 +1704,7 @@ namespace MP.Data.Controllers await Task.Delay(1); if (idxOdl > 0) { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { DateTime adesso = DateTime.Now; // preparo i parametri @@ -1776,7 +1779,7 @@ namespace MP.Data.Controllers public async Task OdlGetByKey(int idxOdl) { ODLModel dbResult = new ODLModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = await dbCtx .DbSetODL @@ -1792,7 +1795,7 @@ namespace MP.Data.Controllers public List OdlGetCurrent() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetODL @@ -1809,7 +1812,7 @@ namespace MP.Data.Controllers public List OdlListAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1835,7 +1838,7 @@ namespace MP.Data.Controllers List dbResult = new List(); if (IdxOdl > 0) { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxODL = new SqlParameter("@IdxODL", IdxOdl); @@ -1859,7 +1862,7 @@ namespace MP.Data.Controllers List dbResult = new List(); try { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { if (codGruppo == "*") { @@ -1923,7 +1926,7 @@ namespace MP.Data.Controllers public PzProdModel PezziProdMacchina(string idxMacchina) { PzProdModel dbResult = new PzProdModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); dbResult = dbCtx @@ -1943,7 +1946,7 @@ namespace MP.Data.Controllers public async Task PODL_getByKey(int idxPODL) { PODLModel dbResult = new PODLModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1971,7 +1974,7 @@ namespace MP.Data.Controllers public PODLModel PODL_getByOdl(int idxODL) { PODLModel dbResult = new PODLModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -2021,7 +2024,7 @@ namespace MP.Data.Controllers InsertDate = editRec.InsertDate }; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -2066,7 +2069,7 @@ namespace MP.Data.Controllers public async Task PODL_updateRecipe(int idxPODL, string recipeName) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -2118,7 +2121,7 @@ namespace MP.Data.Controllers InsertDate = currRec.InsertDate }; bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -2147,7 +2150,7 @@ namespace MP.Data.Controllers public bool PodlIstKitDelete(int IdxPODL) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var pIdxPODL = new SqlParameter("@IdxPODL", IdxPODL); @@ -2167,7 +2170,7 @@ namespace MP.Data.Controllers public async Task PODLUpdateRecord(PODLModel editRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -2213,7 +2216,7 @@ namespace MP.Data.Controllers public bool RollBackEntity(object item) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -2238,7 +2241,7 @@ namespace MP.Data.Controllers public StatoMacchineModel StatoMacchina(string idxMacchina) { StatoMacchineModel dbResult = new StatoMacchineModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetStatoMacc @@ -2256,7 +2259,7 @@ namespace MP.Data.Controllers public bool TemplateKitDelete(TemplateKitModel rec2del) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = dbCtx .DbSetTempKit @@ -2284,7 +2287,7 @@ namespace MP.Data.Controllers public List TemplateKitFilt(string KitCode, string codChild) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetTempKit @@ -2303,7 +2306,7 @@ namespace MP.Data.Controllers public bool TemplateKitUpsert(TemplateKitModel editRec, string codAzienda) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { // verifico preliminarmente articolo... var recArt = dbCtx @@ -2363,7 +2366,7 @@ namespace MP.Data.Controllers List dbResult = new List(); if (!string.IsNullOrEmpty(KeyFilt)) { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var pKeyFilt = new SqlParameter("@KeyFilt", KeyFilt); var pMaxRes = new SqlParameter("@maxResult", MaxResult); @@ -2385,7 +2388,7 @@ namespace MP.Data.Controllers public List VocabolarioGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetVocabolario @@ -2403,7 +2406,7 @@ namespace MP.Data.Controllers public bool WipKitDelete(WipSetupKitModel rec2del) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = dbCtx .DbSetWipKit @@ -2429,7 +2432,7 @@ namespace MP.Data.Controllers public bool WipKitDeleteGroup(string KeyFilt) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = dbCtx .DbSetWipKit @@ -2456,7 +2459,7 @@ namespace MP.Data.Controllers public bool WipKitDeleteOlder(DateTime dateLimit) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = dbCtx .DbSetWipKit @@ -2486,7 +2489,7 @@ namespace MP.Data.Controllers // solo se filtro valido... if (!string.IsNullOrEmpty(KeyFilt)) { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetWipKit @@ -2505,7 +2508,7 @@ namespace MP.Data.Controllers public bool WipKitUpsert(WipSetupKitModel editRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = dbCtx .DbSetWipKit @@ -2538,8 +2541,8 @@ namespace MP.Data.Controllers #region Private Fields private static IConfiguration _configuration; - private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + private DbContextOptions options; #endregion Private Fields } diff --git a/MP.Data/Controllers/MpStatsController.cs b/MP.Data/Controllers/MpStatsController.cs index de6de2a3..cb6dd8a6 100644 --- a/MP.Data/Controllers/MpStatsController.cs +++ b/MP.Data/Controllers/MpStatsController.cs @@ -1,16 +1,14 @@ -using DnsClient.Protocol; -using Microsoft.Data.SqlClient; +using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using MP.Data.DbModels; +using MP.Data.DbModels.Energy; using NLog; using System; using System.Collections.Generic; using System.Data; -using System.Drawing.Drawing2D; using System.Linq; -using ZXing; -using static MP.Core.Objects.Enums; +using System.Threading.Tasks; namespace MP.Data.Controllers { @@ -199,6 +197,22 @@ namespace MP.Data.Controllers } return dbResult; } + /// + /// Elenco controllo stato Macchine Energy x check + /// + /// + public async Task> MacchineEnergyCheckGetAllAsync() + { + List dbResult = new List(); + using (var dbCtx = new MoonPro_STATSContext(_configuration)) + { + dbResult = await dbCtx + .DbSetMacchineCheck + .OrderBy(x => x.IdxMacchina) + .ToListAsync(); + } + return dbResult; + } /// /// Annulla modifiche su una specifica entity (cancel update) diff --git a/MP.Data/Controllers/MpTabController.cs b/MP.Data/Controllers/MpTabController.cs index fe754d52..55981185 100644 --- a/MP.Data/Controllers/MpTabController.cs +++ b/MP.Data/Controllers/MpTabController.cs @@ -20,6 +20,10 @@ namespace MP.Data.Controllers public MpTabController(IConfiguration configuration) { _configuration = configuration; + string connStr = _configuration.GetConnectionString("MP.Data"); + options = new DbContextOptionsBuilder() + .UseSqlServer(connStr) + .Options; Log.Info("Avviato MpTabController"); } @@ -40,7 +44,7 @@ namespace MP.Data.Controllers public bool AlarmLogInsert(DateTime dtRif, string machineId, string memAddress, int memIndex, int statusVal, string valDecoded) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var DtRif = new SqlParameter("@DtRif", dtRif); var MachineId = new SqlParameter("@MachineId", machineId); @@ -68,7 +72,7 @@ namespace MP.Data.Controllers public List AlarmLogListFilt(string idxMacchina, DateTime dtFrom, DateTime dtTo, bool showMulti) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var DtFrom = new SqlParameter("@dtFrom", dtFrom); @@ -94,7 +98,7 @@ namespace MP.Data.Controllers public bool AlarmLogSetAck(int alarmLogId, DateTime dtAck, string userAck) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var AlarmLogId = new SqlParameter("@MachineId", alarmLogId); var DtAck = new SqlParameter("@DtRif", dtAck); @@ -117,7 +121,7 @@ namespace MP.Data.Controllers public bool AlarmLogSetNotify(int alarmLogId, DateTime dtNotify) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var AlarmLogId = new SqlParameter("@MachineId", alarmLogId); var DtNotify = new SqlParameter("@DtNotify", dtNotify); @@ -137,7 +141,7 @@ namespace MP.Data.Controllers public List AnagEventiGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetAnagEventi @@ -154,7 +158,7 @@ namespace MP.Data.Controllers public List AnagEventiGetByMacc(string IdxMac) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacch = new SqlParameter("@idxMacchina", IdxMac); @@ -175,7 +179,7 @@ namespace MP.Data.Controllers public List AnagStatiGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetAnagStati @@ -192,7 +196,7 @@ namespace MP.Data.Controllers public List AnagTagsOrd() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetAnagTags @@ -214,7 +218,7 @@ namespace MP.Data.Controllers public List ArticoliGetByTipo(string tipo, string azienda = "*") { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetArticoli @@ -319,7 +323,7 @@ namespace MP.Data.Controllers public List CommentiGetLastByMacc(string idxMacchina, int numDays) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var NumDays = new SqlParameter("@NumDays", numDays); @@ -351,7 +355,7 @@ namespace MP.Data.Controllers try { var rigaProd = StatoProdMacchina(idxMacchina, DateTime.Now); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@idxMacchina", idxMacchina); var MatrApp = new SqlParameter("@MatrApp ", MatrOpr); @@ -398,7 +402,7 @@ namespace MP.Data.Controllers try { var rigaProd = StatoProdMacchina(idxMacchina, DateTime.Now); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@idxMacchina", idxMacchina); var MatrApp = new SqlParameter("@MatrApp ", MatrOpr); @@ -433,7 +437,7 @@ namespace MP.Data.Controllers public List ConfigGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetConfig @@ -457,7 +461,7 @@ namespace MP.Data.Controllers public bool DDB_DoRecalc(string idxMacchina, DateTime inizio, int idxStatoStart, int nStepEventi, int nRecCheck, bool checkOnly) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var Inizio = new SqlParameter("@inizio", inizio); @@ -485,7 +489,7 @@ namespace MP.Data.Controllers public DiarioDiBordoModel DDB_getNext(string idxMacchina, DateTime inizioStato) { DiarioDiBordoModel dbResult = new DiarioDiBordoModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var DataRif = new SqlParameter("@dataRif", inizioStato); @@ -514,7 +518,7 @@ namespace MP.Data.Controllers public bool DDB_InsStatoBatch(string idxMacchina, DateTime inizioStato, int idxStato, string codArt, string value, int matrOpr, string pallet) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var InizioStato = new SqlParameter("@InizioStato", inizioStato); @@ -549,7 +553,7 @@ namespace MP.Data.Controllers public List ElencoConfProdFilt(string idxMacchina, DateTime dataFrom, DateTime dataTo) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetElConfProd @@ -595,7 +599,7 @@ namespace MP.Data.Controllers public List ElencoOperatori() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbOperatori @@ -617,7 +621,7 @@ namespace MP.Data.Controllers public bool EvListDelete(string idxMacchina, DateTime dtEvento, int idxTipo) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var InizioStato = new SqlParameter("@InizioStato", dtEvento); @@ -651,7 +655,7 @@ namespace MP.Data.Controllers public async Task> EvListGetLastBySearch(string idxMacchina, DateTime dtLimit, int idxTipo, int maxRec) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = await dbCtx .DbSetEvList @@ -673,7 +677,7 @@ namespace MP.Data.Controllers public async Task EvListInsert(EventListModel newRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -701,7 +705,7 @@ namespace MP.Data.Controllers public List FermiNonQualificatiFilt(string idxMacchina, int gg, double durataMin) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var GG = new SqlParameter("@gg", gg); @@ -724,7 +728,7 @@ namespace MP.Data.Controllers public bool InsManDelete(InsManualiModel currRecord) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = dbCtx .DbSetInsManuali @@ -753,7 +757,7 @@ namespace MP.Data.Controllers public List InsManFilt(string IdxMacc, DateTime dtStart, DateTime dtEnd) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetInsManuali @@ -773,7 +777,7 @@ namespace MP.Data.Controllers public async Task InsManFreezeDay(string idxMacchina, DateTime dtCurr) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var DataElab = new SqlParameter("@pDataOra", dtCurr); @@ -794,7 +798,7 @@ namespace MP.Data.Controllers public bool InsManUpsert(InsManualiModel currRecord) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = dbCtx .DbSetInsManuali @@ -835,7 +839,7 @@ namespace MP.Data.Controllers public bool InsManUpsert(List listRecord) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { foreach (var currRecord in listRecord) { @@ -880,7 +884,7 @@ namespace MP.Data.Controllers public List ListPODL_ByKitParent(int IdxPodlParent) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var pIdxPodlParent = new SqlParameter("@IdxPodlParent", IdxPodlParent); @@ -903,7 +907,7 @@ namespace MP.Data.Controllers public List ListPODLByMacc(string idxMacchina, bool onlyFree, bool onlyDirect) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var OnlyFree = new SqlParameter("@onlyFree", onlyFree); @@ -927,7 +931,7 @@ namespace MP.Data.Controllers public List ListValuesFilt(string tabName, string fieldName) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetListValues @@ -948,7 +952,7 @@ namespace MP.Data.Controllers public bool MacchinaSetInsEnab(string idxMacchina, bool insEnabled) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@idxMacchina", idxMacchina); var InsEnabled = new SqlParameter("@insEnabled", insEnabled); @@ -969,7 +973,7 @@ namespace MP.Data.Controllers public List Macchine2Slave() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetM2S @@ -990,7 +994,7 @@ namespace MP.Data.Controllers List dbResult = new List(); try { - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { if (MatrOpr == 0) { @@ -1038,7 +1042,7 @@ namespace MP.Data.Controllers public MicroStatoMacchinaModel MicroStatoMacchina(string idxMacchina) { MicroStatoMacchinaModel dbResult = new MicroStatoMacchinaModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetMicroStatoMacc @@ -1058,7 +1062,7 @@ namespace MP.Data.Controllers public List MicroStatoMacchinaGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetMicroStatoMacc @@ -1076,7 +1080,7 @@ namespace MP.Data.Controllers public bool MicroStatoMacchinaUpsert(MicroStatoMacchinaModel newRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var actRec = dbCtx .DbSetMicroStatoMacc @@ -1112,7 +1116,7 @@ namespace MP.Data.Controllers public List MseGetSub(string idxMacc, string idxMacchSub) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1141,7 +1145,7 @@ namespace MP.Data.Controllers public List OdlByIdx(int idxOdl, bool onlyUnused) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1170,7 +1174,7 @@ namespace MP.Data.Controllers public bool OdlClearSetup(int idxODL, string idxMacchina) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1197,7 +1201,7 @@ namespace MP.Data.Controllers public List OdlCurrByMacc(string idxMacchina) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1226,7 +1230,7 @@ namespace MP.Data.Controllers public bool OdlDividiDaAltraTavola(int idxODL, int matrOpr, string idxMacchinaTo) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1256,7 +1260,7 @@ namespace MP.Data.Controllers public bool OdlFineProd(int idxODL, string idxMacchina, DateTime dtRif) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1286,7 +1290,7 @@ namespace MP.Data.Controllers public bool OdlFixMachineSlave(string idxMacchina, int numDayPrev, int doInsert) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1319,7 +1323,7 @@ namespace MP.Data.Controllers public bool OdlInizioSetup(int idxODL, int matrOpr, string idxMacchina, decimal tcRich, int pzPallet, string note) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1350,7 +1354,7 @@ namespace MP.Data.Controllers public List OdlLastByMacc(string idxMacchina) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1379,7 +1383,7 @@ namespace MP.Data.Controllers public List OdlListByMaccPeriodo(string idxMacchina, DateTime dtStart, DateTime dtEnd) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1408,7 +1412,7 @@ namespace MP.Data.Controllers public List OdlReopenOdlMacc(string idxMacchina) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1436,7 +1440,7 @@ namespace MP.Data.Controllers public bool OdlSetupPostumo(int idxODL, string idxMacchina) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1465,7 +1469,7 @@ namespace MP.Data.Controllers public bool OdlSetupPromPostuma(int idxPromOdl, int matrOpr, string idxMacchina) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1500,7 +1504,7 @@ namespace MP.Data.Controllers public bool OdlSplit(int idxODL, int matrOpr, string idxMacchina, decimal TCRich, int pzPallet, string note, bool startNewOdl, int qtyRich) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1537,7 +1541,7 @@ namespace MP.Data.Controllers public bool OdlUpdate(int idxODL, int matrOpr, decimal tCRichAttr, int pzPallet, string note) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1571,7 +1575,7 @@ namespace MP.Data.Controllers { AnagOperatoriModel dbResult = null; AnagOperatoriModel answ = new AnagOperatoriModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbOperatori @@ -1594,7 +1598,7 @@ namespace MP.Data.Controllers public List PezziProdMacchina(string idxMacchina) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); try @@ -1644,7 +1648,7 @@ namespace MP.Data.Controllers InsertDate = editRec.InsertDate }; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1688,7 +1692,7 @@ namespace MP.Data.Controllers public PODLExpModel PODLExp_getByKey(int idxPODL) { PODLExpModel dbResult = new PODLExpModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1719,7 +1723,7 @@ namespace MP.Data.Controllers public async Task PODLExp_getByKeyAsync(int idxPODL) { PODLExpModel dbResult = new PODLExpModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { try { @@ -1753,7 +1757,7 @@ namespace MP.Data.Controllers public List RegControlliFilt(string idxMacchina, int idxODL, DateTime dataFrom, DateTime dataTo, bool showMulti) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var IdxODL = new SqlParameter("@IdxODL", idxODL); @@ -1782,7 +1786,7 @@ namespace MP.Data.Controllers public bool RegControlliInsert(string idxMacchina, int matrOpr, bool esitoOk, string note, DateTime dataOra) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var MatrOpr = new SqlParameter("@MatrOpr", matrOpr); @@ -1804,7 +1808,7 @@ namespace MP.Data.Controllers public List RegControlliLast(string idxMacchina) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); @@ -1829,7 +1833,7 @@ namespace MP.Data.Controllers public List RegDichiarGetFilt(string idxMacchina, string tagCode, int matrOpr, int idxODL, DateTime dataFrom, DateTime dataTo) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var TagCode = new SqlParameter("@TagCode", tagCode); var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); @@ -1855,7 +1859,7 @@ namespace MP.Data.Controllers public async Task RegDichiarInsert(RegistroDichiarazioniModel newRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var TagCode = new SqlParameter("@TagCode", newRec.TagCode); var IdxMacchina = new SqlParameter("@IdxMacchina", newRec.IdxMacchina); @@ -1880,7 +1884,7 @@ namespace MP.Data.Controllers public async Task RegDichiarUpdate(RegistroDichiarazioniModel newRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var Original_IdxDich = new SqlParameter("@Original_IdxDich", newRec.IdxDich); var DtRec = new SqlParameter("@DtRec", newRec.DtRec); @@ -1909,7 +1913,7 @@ namespace MP.Data.Controllers public List RegScartiGetFilt(string idxMacchina, int idxODL, DateTime dataFrom, DateTime dataTo, bool showMulti) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var IdxODL = new SqlParameter("@IdxODL", idxODL); @@ -1934,7 +1938,7 @@ namespace MP.Data.Controllers public bool RegScartiInsert(RegistroScartiModel newRec) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@idxMacchina", newRec.IdxMacchina); var DataOra = new SqlParameter("@DataOra", newRec.DataOra); @@ -1963,7 +1967,7 @@ namespace MP.Data.Controllers public bool RegScartiKitDelete(RegistroScartiModel parentRec) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", parentRec.IdxMacchina); var DtRif = new SqlParameter("@DataOra", parentRec.DataOra); @@ -1986,7 +1990,7 @@ namespace MP.Data.Controllers public List RegScartiKitGetFilt(RegistroScartiModel parentRec) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", parentRec.IdxMacchina); var DtRif = new SqlParameter("@DataRif", parentRec.DataOra); @@ -2010,7 +2014,7 @@ namespace MP.Data.Controllers { await Task.Delay(1); bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@idxMacchina", newRec.IdxMacchina); var DataOra = new SqlParameter("@DataOra", newRec.DataOra); @@ -2037,7 +2041,7 @@ namespace MP.Data.Controllers public bool RegScartiKitUpdateQty(RegistroScartiKitModel currRec) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", currRec.IdxMacchina); var DtRif = new SqlParameter("@DataOra", currRec.DataOra); @@ -2066,7 +2070,7 @@ namespace MP.Data.Controllers try { var rigaProd = StatoProdMacchina(idxMacchina, DateTime.Now); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var MaxAgeSec = new SqlParameter("@maxAgeSec ", maxAgeSec); var IdxMacchina = new SqlParameter("@idxMacchina", idxMacchina); @@ -2098,7 +2102,7 @@ namespace MP.Data.Controllers public async Task RipristinaStatoPrec(string idxMacchina, DateTime dtCurr, string valore, int idxStato = 0, int matrOpr = 0) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var pIdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var pDataOra = new SqlParameter("@DataOra", dtCurr); @@ -2139,7 +2143,7 @@ namespace MP.Data.Controllers public List SMES_GetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetSMES @@ -2156,7 +2160,7 @@ namespace MP.Data.Controllers public List SMES_GetByFam(int idxFam) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetSMES @@ -2175,7 +2179,7 @@ namespace MP.Data.Controllers public List SMES_getHwTransitions(string idxMacchina, int idxTipo) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var IdxTipo = new SqlParameter("@IdxTipo", idxTipo); @@ -2197,7 +2201,7 @@ namespace MP.Data.Controllers public List SMES_getUserForced(string idxMacchina, int idxTipo) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var IdxTipo = new SqlParameter("@IdxTipo", idxTipo); @@ -2218,7 +2222,7 @@ namespace MP.Data.Controllers public List ST_AnagGruppiList() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetStAnagGruppi @@ -2232,7 +2236,7 @@ namespace MP.Data.Controllers public bool ST_CheckCleanByOdl(int idxOdl) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxOdl = new SqlParameter("@IdxOdl", idxOdl); @@ -2247,7 +2251,7 @@ namespace MP.Data.Controllers public bool ST_CheckUpsert(int idxOdl, int idxST, int oggetto, int num, string valueRead, string extCode, bool checkOk, string userMod, bool forced) { bool fatto = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxOdl = new SqlParameter("@IdxOdl", idxOdl); var IdxST = new SqlParameter("@IdxST", idxST); @@ -2276,7 +2280,7 @@ namespace MP.Data.Controllers public List STAR_byGrpOdl(string codGruppo, int idxODL) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var CodGruppo = new SqlParameter("@CodGruppo", codGruppo); var IdxODL = new SqlParameter("@IdxODL", idxODL); @@ -2301,7 +2305,7 @@ namespace MP.Data.Controllers public List STAR_byGrpOdlLbl(string codGruppo, string label, int idxODL) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var CodGruppo = new SqlParameter("@CodGruppo", codGruppo); var Label = new SqlParameter("@Label", label); @@ -2325,7 +2329,7 @@ namespace MP.Data.Controllers public List STAR_pendByOdl(int idxODL) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxODL = new SqlParameter("@IdxODL", idxODL); @@ -2347,7 +2351,7 @@ namespace MP.Data.Controllers public List StateMachineIngressi(int idxFam) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxFamIn = new SqlParameter("@IdxFamigliaIngresso", idxFam); dbResult = dbCtx @@ -2368,7 +2372,7 @@ namespace MP.Data.Controllers public StatoMacchineModel StatoMacchina(string idxMacchina) { StatoMacchineModel dbResult = new StatoMacchineModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetStatoMacc @@ -2388,7 +2392,7 @@ namespace MP.Data.Controllers public StatoProdModel StatoProdMacchina(string idxMacchina, DateTime dtReq) { StatoProdModel dbResult = new StatoProdModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var DataOra = new SqlParameter("@DataOra ", dtReq); @@ -2413,7 +2417,7 @@ namespace MP.Data.Controllers public List TemplateKitFilt(string KitCode, string codChild) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetTempKit @@ -2432,7 +2436,7 @@ namespace MP.Data.Controllers public TurniMaccModel TurnoMacchinaGet(string idxMacchina) { TurniMaccModel dbResult = new TurniMaccModel(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); dbResult = dbCtx @@ -2452,7 +2456,7 @@ namespace MP.Data.Controllers public List TurnoMacchinaGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetTurniMacc @@ -2471,7 +2475,7 @@ namespace MP.Data.Controllers public bool TurnoMacchinaToggle(string idxMacchina, int numTurno) { bool answ = false; - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina); var NumTurno = new SqlParameter("@numTurno", numTurno); @@ -2493,7 +2497,7 @@ namespace MP.Data.Controllers public List VocabolarioGetAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetVocabolario @@ -2511,7 +2515,7 @@ namespace MP.Data.Controllers public List VSCS_getAll() { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { dbResult = dbCtx .DbSetVSCS @@ -2530,7 +2534,7 @@ namespace MP.Data.Controllers public List VSOdlGetLastByMacc(string idxMacchina, int numRec) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var NumRec = new SqlParameter("@numRec", numRec); @@ -2554,7 +2558,7 @@ namespace MP.Data.Controllers public List VSOdlGetUnused(string idxMacchina, bool showAll, int numDayAdd) { List dbResult = new List(); - using (var dbCtx = new MoonProContext(_configuration)) + using (var dbCtx = new MoonProContext(options)) { var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina); var ShowAll = new SqlParameter("@showAll", showAll); @@ -2574,8 +2578,8 @@ namespace MP.Data.Controllers #region Private Fields private static IConfiguration _configuration; - private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + private DbContextOptions options; #endregion Private Fields } diff --git a/MP.Data/DataServiceCollectionExtensions.cs b/MP.Data/DataServiceCollectionExtensions.cs index 40e538a9..78eb73e2 100644 --- a/MP.Data/DataServiceCollectionExtensions.cs +++ b/MP.Data/DataServiceCollectionExtensions.cs @@ -1,8 +1,10 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using MP.Data.Controllers; +using MP.Data.Repository.IOC; using MP.Data.Repository.Mtc; using MP.Data.Repository.Utils; +using MP.Data.Services.IOC; using MP.Data.Services.Mtc; using MP.Data.Services.Utils; @@ -25,6 +27,7 @@ namespace MP.Data services.TryAddSingleton(); // Repository Scoped + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); @@ -33,6 +36,7 @@ namespace MP.Data services.TryAddSingleton(); // Servizi Scoped + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); diff --git a/MP.Data/DbModels/Energy/MacchineEnergyCheckModel.cs b/MP.Data/DbModels/Energy/MacchineEnergyCheckModel.cs new file mode 100644 index 00000000..04cedc23 --- /dev/null +++ b/MP.Data/DbModels/Energy/MacchineEnergyCheckModel.cs @@ -0,0 +1,35 @@ +using System; +using System.ComponentModel.DataAnnotations; + +namespace MP.Data.DbModels.Energy +{ + public class MacchineEnergyCheckModel + { + + public string IdxMacchina { get; set; } = ""; + /// + /// Nome macchina + /// + [MaxLength(50)] + public string Nome { get; set; } = ""; + /// + /// Descrizione macchina + /// + public string Descrizione { get; set; } = ""; + + /// + /// DataOra ultimo evento + /// + public DateTime dtEvento { get; set; } + + /// + /// Flusso registrato + /// + public string CodFlux { get; set; } + + /// + /// Valore registrato + /// + public string Valore { get; set; } + } +} diff --git a/MP.Data/MP.Data.csproj b/MP.Data/MP.Data.csproj index 71cf1bc6..c1717ce8 100644 --- a/MP.Data/MP.Data.csproj +++ b/MP.Data/MP.Data.csproj @@ -37,7 +37,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/MP.Data/MoonProContext.cs b/MP.Data/MoonProContext.cs index 7c0d4658..0d65c590 100644 --- a/MP.Data/MoonProContext.cs +++ b/MP.Data/MoonProContext.cs @@ -22,10 +22,16 @@ namespace MP.Data #region Public Constructors - public MoonProContext(IConfiguration configuration) - { - _configuration = configuration; - } + //public MoonProContext(IConfiguration configuration) + //{ + // _configuration = configuration; + //} + + //public MoonProContext(DbContextOptions options, IConfiguration configuration) + //: base(options) + //{ + // _configuration = configuration; + //} public MoonProContext(DbContextOptions options) : base(options) { diff --git a/MP.Data/MoonPro_STATSContext.cs b/MP.Data/MoonPro_STATSContext.cs index 6bad207e..9baca2e2 100644 --- a/MP.Data/MoonPro_STATSContext.cs +++ b/MP.Data/MoonPro_STATSContext.cs @@ -1,8 +1,7 @@ -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using MP.Data.DbModels; +using MP.Data.DbModels.Energy; using NLog; #nullable disable @@ -45,6 +44,8 @@ namespace MP.Data public virtual DbSet DbSetDdbTurni { get; set; } public virtual DbSet DbSetFL { get; set; } public virtual DbSet DbSetMacchine { get; set; } + public virtual DbSet DbSetMacchineCheck { get; set; } + public virtual DbSet DbSetODL { get; set; } public virtual DbSet DbSetOdlEnergy { get; set; } public virtual DbSet DbSetScarti { get; set; } @@ -138,6 +139,13 @@ namespace MP.Data .HasMaxLength(5); }); + modelBuilder.Entity(entity => + { + entity.HasNoKey(); + + entity.ToView("v_UI_MacchineEnergyCheck"); + }); + modelBuilder.Entity(entity => { entity.HasNoKey(); diff --git a/MP.Data/Repository/IOC/BaseRepository.cs b/MP.Data/Repository/IOC/BaseRepository.cs new file mode 100644 index 00000000..7814ee85 --- /dev/null +++ b/MP.Data/Repository/IOC/BaseRepository.cs @@ -0,0 +1,47 @@ +using Microsoft.EntityFrameworkCore; +using System.Threading.Tasks; + +namespace MP.Data.Repository.IOC +{ + public abstract class BaseRepository : IBaseRepository + { + #region Protected Fields + + protected readonly IDbContextFactory _ctxFactory; + + #endregion Protected Fields + + #region Protected Constructors + + protected BaseRepository(IDbContextFactory ctxFactory) + => _ctxFactory = ctxFactory; + + #endregion Protected Constructors + + #region Protected Methods + + /// + /// Creazione dbcontext per singola transazione + /// + /// + protected async Task CreateContextAsync() + => await _ctxFactory.CreateDbContextAsync(); + + #endregion Protected Methods + +#if false + /// + /// Salvataggio dati asincrono + /// + /// + protected async Task SaveChangesAsync(DataLayerContext ctx) + => await ctx.SaveChangesAsync() > 0; +#endif + +#if false + protected readonly DataLayerContext _dbCtx; + protected BaseRepository(DataLayerContext db) => _dbCtx = db; + public async Task SaveChangesAsync() => await _dbCtx.SaveChangesAsync() > 0; +#endif + } +} \ No newline at end of file diff --git a/MP.Data/Repository/IBaseRepository.cs b/MP.Data/Repository/IOC/IBaseRepository.cs similarity index 82% rename from MP.Data/Repository/IBaseRepository.cs rename to MP.Data/Repository/IOC/IBaseRepository.cs index 6e63d664..7a2feeb7 100644 --- a/MP.Data/Repository/IBaseRepository.cs +++ b/MP.Data/Repository/IOC/IBaseRepository.cs @@ -1,4 +1,4 @@ -namespace MP.Data.Repository +namespace MP.Data.Repository.IOC { public interface IBaseRepository { diff --git a/MP.Data/Repository/IOC/IIocRepository.cs b/MP.Data/Repository/IOC/IIocRepository.cs new file mode 100644 index 00000000..cfa5824f --- /dev/null +++ b/MP.Data/Repository/IOC/IIocRepository.cs @@ -0,0 +1,121 @@ +using MP.Data.DbModels; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using static MP.Core.Objects.Enums; + +namespace MP.Data.Repository.IOC +{ + /// + /// Interfaccia per metodi IOC + /// + public interface IIocRepository + { + #region Public Methods + + /// + /// Processing intera catena eventi verifica cambio stato in singola transazione e con unico DbContext + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + Task CheckCambiaStatoBatchAsync(tipoInputEvento tipoInput, string IdxMacchina, DateTime InizioStato, int IdxTipo, string CodArt, string Value, int MatrOpr, string pallet); + + /// + /// Elenco da tabella Config + /// + /// + Task> ConfigGetAllAsync(); + + /// + /// Intera tab dati macchina + /// + /// + Task> DatiMacchineGetAllAsync(); + + /// + /// Aggiunta record MicroStato + EventList + /// + /// + /// + /// + Task EvListMicroStatoInsertAsync(MicroStatoMacchinaModel newRecMsm, EventListModel newRecEv); + + /// + /// Upsert record keepalive + /// + /// + /// + /// + /// + Task KeepAliveUpsertAsync(string IdxMacc, DateTime OraServer, DateTime OraMacc); + + /// + /// Intera tabella relazione master/slave in machine (gestione setup master - slave) + /// + /// + Task> Macchine2SlaveAsync(); + + /// + /// Recupera record macchina da Idx + /// + /// + /// + Task MacchineGetByIdxAsync(string IdxMacchina); + + /// + /// Upsert Record Macchine ASYNC + /// + /// + Task MacchineUpsertAsync(MacchineModel entity); + + /// + /// Elenco da tabella Macchine + /// + /// + /// + Task> MicroStatoMacchinaGetByIdxMaccAsync(string IdxMacc); + + /// + /// Aggiornamento record Microstato macchina + /// + /// + /// + Task MicroStatoMacchinaUpsertAsync(MicroStatoMacchinaModel newRec); + + /// + /// Aggiunta record SignalLog Async + /// + /// + /// + Task SignalLogInsertAsync(SignalLogModel newRec); + + /// + /// Intera tabella state machine ingressi 2 eventi + /// + /// + Task> StateMachineIngressiAsync(int idxFam); + + /// + /// Vista v_MSFD x singola macchina (da stored) - singolo record + /// + /// + /// + Task VMSFDGetByMaccAsync(string idxMacc); + + /// + /// Vista v_MSFD delle machine MULTI filtrato x macchina (da stored) + /// + /// + /// + Task> VMSFDGetMultiByMaccAsync(string idxMacc); + + #endregion Public Methods + } +} \ No newline at end of file diff --git a/MP.Data/Repository/IOC/IocRepository.cs b/MP.Data/Repository/IOC/IocRepository.cs new file mode 100644 index 00000000..de11638e --- /dev/null +++ b/MP.Data/Repository/IOC/IocRepository.cs @@ -0,0 +1,354 @@ +using Microsoft.Data.SqlClient; +using Microsoft.EntityFrameworkCore; +using MongoDB.Driver; +using MP.Data.DbModels; +using NLog; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using static MP.Core.Objects.Enums; + +namespace MP.Data.Repository.IOC +{ + public class IocRepository : BaseRepository, IIocRepository + { + #region Public Constructors + + public IocRepository(IDbContextFactory ctxFactory) : base(ctxFactory) + { + } + + #endregion Public Constructors + + #region Public Methods + + /// + public async Task CheckCambiaStatoBatchAsync(tipoInputEvento tipoInput, string IdxMacchina, DateTime InizioStato, int IdxTipo, string CodArt, string Value, int MatrOpr, string pallet) + { + await using var dbCtx = await CreateContextAsync(); + //await using var tx = await dbCtx.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted); + + try + { + var pIdxMacchina = new SqlParameter("@IdxMacchina", IdxMacchina); + var pIdxTipo = new SqlParameter("@IdxTipo", IdxTipo); + var pInizioStato = new SqlParameter("@InizioStato", InizioStato); + var pCodArticolo = new SqlParameter("@codArticolo", CodArt); + var pValue = new SqlParameter("@Value", Value); + var pMatrOpr = new SqlParameter("@MatrOpr", MatrOpr); + var pPallet = new SqlParameter("@pallet", pallet); + + string opType = tipoInput switch + { + tipoInputEvento.barcode => "BARCODE", + tipoInputEvento.hw => "HW", + _ => "ND" + }; + + TransizioneStatiModel? rigaTrans = null; + + if (opType != "ND") + { + string sql = tipoInput switch + { + tipoInputEvento.barcode => "EXEC dbo.stp_TS_getUserForcedTrans @IdxMacchina, @IdxTipo", + tipoInputEvento.hw => "EXEC dbo.stp_TS_getByIdxMacchIdxTipoEv @IdxMacchina, @IdxTipo", + _ => string.Empty + }; + + // ✅ prima chiamata ASYNC + rigaTrans = (await dbCtx.DbSetSMES + .FromSqlRaw(sql, pIdxMacchina, pIdxTipo) + .AsNoTracking() + .ToListAsync() + ).FirstOrDefault(); + } + + if (rigaTrans != null && rigaTrans.IdxStato != rigaTrans.next_IdxStato) + { + var pIdxStato = new SqlParameter("@IdxStato", rigaTrans.next_IdxStato); + + await dbCtx.Database.ExecuteSqlRawAsync( + "EXEC dbo.stp_DDB_InsStatoBatch @IdxMacchina, @InizioStato, @IdxStato, @codArticolo, @Value, @MatrOpr, @pallet", + pIdxMacchina, pInizioStato, pIdxStato, pCodArticolo, pValue, pMatrOpr, pPallet); + + // eseguo solo se evento manuale/barcode + if (tipoInput == tipoInputEvento.barcode) + { + var pMaxAgeSec = new SqlParameter("@maxAgeSec", 0); + await dbCtx.Database.ExecuteSqlRawAsync( + "EXEC stp_MSE_recalc @maxAgeSec, @idxMacchina", + pMaxAgeSec, pIdxMacchina); + } + } + else + { + Log.Debug($"Nessun cambio stato richiesto | {opType} | {IdxMacchina} | {IdxTipo}"); + } + + //// Nessuna eccezione = successo + //await tx.CommitAsync(); + return true; + } + catch (Exception ex) + { + //await tx.RollbackAsync(); + // Log dettagliato errore + Log.Error(ex, $"Errore in CheckCambiaStatoBatchAsync: {IdxMacchina} | {tipoInput}"); + throw; // O return false; se il chiamante gestisce fallimenti + } + } + + /// + public async Task> ConfigGetAllAsync() + { + await using var dbCtx = await CreateContextAsync(); + var dbResult = await dbCtx + .DbSetConfig + .AsNoTracking() + .OrderBy(x => x.Chiave) + .ToListAsync(); + return dbResult; + } + + /// + public async Task> DatiMacchineGetAllAsync() + { + await using var dbCtx = await CreateContextAsync(); + var dbResult = await dbCtx + .DbSetDatiMacchine + .AsNoTracking() + .OrderBy(x => x.IdxMacchina) + .ToListAsync(); + return dbResult; + } + + /// + public async Task EvListMicroStatoInsertAsync(MicroStatoMacchinaModel newRecMsm, EventListModel newRecEv) + { + await using var dbCtx = await CreateContextAsync(); + //// eseguo in transazione... + //await using var tx = await dbCtx.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted); + + try + { + // inizio con record microstato... + var actRec = await dbCtx + .DbSetMicroStatoMacc + .FindAsync(newRecMsm.IdxMacchina); + //.SingleOrDefaultAsync(); + if (actRec == null) + { + dbCtx.DbSetMicroStatoMacc.Add(newRecMsm); + } + else + { + actRec.IdxMicroStato = newRecMsm.IdxMicroStato; + actRec.InizioStato = newRecMsm.InizioStato; + actRec.Value = newRecMsm.Value; + + // Update() allega l'entità e segna tutti i campi come Modified + dbCtx.DbSetMicroStatoMacc.Update(actRec); + } + + // ora record EVList + dbCtx.DbSetEvList.Add(newRecEv); + + // EF Core 8 raggruppa automaticamente INSERT/UPDATE in un batch + var rowsAffected = await dbCtx.SaveChangesAsync(); + //await tx.CommitAsync(); + + return rowsAffected > 0; + } + catch (Exception ex) + { + //await tx.RollbackAsync(); + // Log dettagliato errore + Log.Error(ex, $"Errore in EvListMicroStatoInsertAsync: {newRecEv.IdxMacchina}"); + throw; + } + } + + /// + public async Task KeepAliveUpsertAsync(string IdxMacc, DateTime OraServer, DateTime OraMacc) + { + await using var dbCtx = await CreateContextAsync(); + bool fatto = false; + + var currRec = await dbCtx + .DbSetKeepAlive + .Where(x => x.IdxMacchina == IdxMacc) + .FirstOrDefaultAsync(); + if (currRec != null) + { + currRec.DataOraServer = OraServer; + currRec.DataOraMacchina = OraMacc; + dbCtx.Entry(currRec).State = EntityState.Modified; + } + else + { + KeepAliveModel newRec = new KeepAliveModel() + { + IdxMacchina = IdxMacc, + DataOraMacchina = OraMacc, + DataOraServer = OraServer, + DataOraStart = DateTime.Now + }; + dbCtx + .DbSetKeepAlive + .Add(newRec); + } + fatto = await dbCtx.SaveChangesAsync() > 0; + + return fatto; + } + + /// + public async Task> Macchine2SlaveAsync() + { + await using var dbCtx = await CreateContextAsync(); + List dbResult = await dbCtx + .DbSetM2S + .AsNoTracking() + .OrderBy(x => x.IdxMacchina) + .ToListAsync(); + + return dbResult; + } + + /// + public async Task MacchineGetByIdxAsync(string IdxMacchina) + { + await using var dbCtx = await CreateContextAsync(); + MacchineModel dbResult = await dbCtx + .DbSetMacchine + .FirstOrDefaultAsync(x => x.IdxMacchina == IdxMacchina); + return dbResult; + } + + /// + public async Task MacchineUpsertAsync(MacchineModel entity) + { + await using var dbCtx = await CreateContextAsync(); + + // Recuperiamo l'entità tracciata dal context + var trackedEntity = await dbCtx + .DbSetMacchine + .FirstOrDefaultAsync(x => x.IdxMacchina == entity.IdxMacchina); + + if (trackedEntity != null) + { + // Aggiorna i valori dell'entità tracciata con quelli della nuova + dbCtx.Entry(trackedEntity).CurrentValues.SetValues(entity); + } + else + { + dbCtx.DbSetMacchine.Update(entity); + } + return await dbCtx.SaveChangesAsync() > 0; + } + + /// + public async Task> MicroStatoMacchinaGetByIdxMaccAsync(string IdxMacc) + { + await using var dbCtx = await CreateContextAsync(); + List dbResult = new List(); + dbResult = await dbCtx + .DbSetMicroStatoMacc + .Where(x => x.IdxMacchina == IdxMacc) + .AsNoTracking() + .ToListAsync(); + return dbResult; + } + + /// + public async Task MicroStatoMacchinaUpsertAsync(MicroStatoMacchinaModel newRec) + { + await using var dbCtx = await CreateContextAsync(); + bool fatto = false; + + var actRec = await dbCtx + .DbSetMicroStatoMacc + .Where(x => x.IdxMacchina == newRec.IdxMacchina) + .AsNoTracking() + .FirstOrDefaultAsync(); + if (actRec == null) + { + dbCtx + .DbSetMicroStatoMacc + .Add(newRec); + } + else + { + actRec.IdxMicroStato = newRec.IdxMicroStato; + actRec.InizioStato = newRec.InizioStato; + actRec.Value = newRec.Value; + + dbCtx.Entry(actRec).State = EntityState.Modified; + } + fatto = await dbCtx.SaveChangesAsync() > 0; + + return fatto; + } + + /// + public async Task SignalLogInsertAsync(SignalLogModel newRec) + { + await using var dbCtx = await CreateContextAsync(); + var currRec = dbCtx + .DbSetSignalLog + .Add(newRec); + return await dbCtx.SaveChangesAsync() > 0; + } + + /// + public async Task> StateMachineIngressiAsync(int idxFam) + { + await using var dbCtx = await CreateContextAsync(); + var IdxFamIn = new SqlParameter("@IdxFamigliaIngresso", idxFam); + var dbResult = await dbCtx + .DbSetSMI + .FromSqlRaw("exec dbo.stp_TRI_getByIdxFamIng @IdxFamigliaIngresso", IdxFamIn) + .AsNoTracking() + .ToListAsync(); + return dbResult; + } + + /// + public async Task VMSFDGetByMaccAsync(string idxMacc) + { + await using var dbCtx = await CreateContextAsync(); + var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacc); + var dbResult = (await dbCtx + .DbSetMSFD + .FromSqlRaw("exec dbo.stp_MSFD_getMacc @IdxMacchina", IdxMacchina) + .AsNoTracking() + .ToListAsync()) + .FirstOrDefault(); + return dbResult; + } + + /// + public async Task> VMSFDGetMultiByMaccAsync(string idxMacc) + { + await using var dbCtx = await CreateContextAsync(); + var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacc); + var dbResult = await dbCtx + .DbSetMSFD + .FromSqlRaw("exec dbo.stp_MSFD_getMulti @IdxMacchina", IdxMacchina) + .AsNoTracking() + .ToListAsync(); + return dbResult; + } + + #endregion Public Methods + + #region Protected Fields + + protected static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Protected Fields + } +} \ No newline at end of file diff --git a/MP.Data/Repository/Mtc/MtcSetupRepository.cs b/MP.Data/Repository/Mtc/MtcSetupRepository.cs index 4912f651..b391d3a4 100644 --- a/MP.Data/Repository/Mtc/MtcSetupRepository.cs +++ b/MP.Data/Repository/Mtc/MtcSetupRepository.cs @@ -1,5 +1,6 @@ using Microsoft.EntityFrameworkCore; using MP.Data.DbModels.Mtc; +using MP.Data.Repository.Utils; using System.Threading.Tasks; namespace MP.Data.Repository.Mtc diff --git a/MP.Data/Repository/BaseRepository.cs b/MP.Data/Repository/Utils/BaseRepository.cs similarity index 97% rename from MP.Data/Repository/BaseRepository.cs rename to MP.Data/Repository/Utils/BaseRepository.cs index 7afc1bd2..4e709040 100644 --- a/MP.Data/Repository/BaseRepository.cs +++ b/MP.Data/Repository/Utils/BaseRepository.cs @@ -1,7 +1,7 @@ using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; -namespace MP.Data.Repository +namespace MP.Data.Repository.Utils { public abstract class BaseRepository : IBaseRepository { diff --git a/MP.Data/Repository/Utils/IBaseRepository.cs b/MP.Data/Repository/Utils/IBaseRepository.cs new file mode 100644 index 00000000..c6a4988a --- /dev/null +++ b/MP.Data/Repository/Utils/IBaseRepository.cs @@ -0,0 +1,8 @@ +namespace MP.Data.Repository.Utils +{ + public interface IBaseRepository + { + //Task CreateContextAsync(); + //Task SaveChangesAsync(DataLayerContext ctx); + } +} diff --git a/MP.Data/Services/IOC/IIocService.cs b/MP.Data/Services/IOC/IIocService.cs new file mode 100644 index 00000000..3f3b48a0 --- /dev/null +++ b/MP.Data/Services/IOC/IIocService.cs @@ -0,0 +1,69 @@ +using MP.Data.DbModels; +using System; +using System.Threading.Tasks; +using static MP.Core.Objects.Enums; + +namespace MP.Data.Services.IOC +{ + public interface IIocService + { + #region Public Methods + + /// + /// Processing intera catena eventi verifica cambio stato in singola transazione e con unico DbContext + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + Task CheckCambiaStatoBatchAsync(tipoInputEvento tipoInput, string IdxMacchina, DateTime InizioStato, int IdxTipo, string CodArt, string Value, int MatrOpr, string pallet); + + /// + /// Aggiunta record MicroStato + EventList + /// + /// + /// + /// + Task EvListMicroStatoInsertAsync(MicroStatoMacchinaModel newRecMsm, EventListModel newRecEv); + + /// + /// Restituisce il valOut booleano se la macchina sia abilitata all'input + /// + /// + /// + Task IobInsEnabAsync(string idxMacchina); + + /// + /// Aggiornamento record Microstato macchina + /// + /// + /// + Task MicroStatoMacchinaUpsertAsync(MicroStatoMacchinaModel newRec); + + /// + /// Processa input da IOB eventualmente registrando i segnali inviati + /// + /// + /// + /// + /// + /// + /// + Task ProcessInputAsync(string idxMacchina, string valore, string dtEve, string dtCurr, string contatore); + + /// + /// scrive un evento di keepalive sulla tabella + /// + /// + /// + /// + Task ScriviKeepAliveAsync(string IdxMacchina, DateTime oraMacchina); + + #endregion Public Methods + } +} \ No newline at end of file diff --git a/MP.Data/Services/IOC/IocService.cs b/MP.Data/Services/IOC/IocService.cs new file mode 100644 index 00000000..8c5b9407 --- /dev/null +++ b/MP.Data/Services/IOC/IocService.cs @@ -0,0 +1,977 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using MP.Core.Objects; +using MP.Data.DbModels; +using MP.Data.Repository.IOC; +using Newtonsoft.Json; +using NLog; +using StackExchange.Redis; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading.Tasks; +using static MP.Core.Objects.Enums; + +namespace MP.Data.Services.IOC +{ + public class IocService : BaseServ, IIocService + { + #region Public Constructors + + public IocService( + IConfiguration config, + IConnectionMultiplexer redis, + IIocRepository repo, + IServiceScopeFactory scopeFactory) : base(config, redis) + { + _className = "IocServ"; + int.TryParse(config.GetValue("ServerConf:redisLongTimeCache"), out redisLongTimeCache); + int.TryParse(config.GetValue("ServerConf:redisShortTimeCache"), out redisShortTimeCache); + _repo = repo; + _scopeFactory = scopeFactory; + } + + #endregion Public Constructors + + #region Public Methods + + /// + public async Task CheckCambiaStatoBatchAsync(tipoInputEvento tipoInput, string IdxMacchina, DateTime InizioStato, int IdxTipo, string CodArt, string Value, int MatrOpr, string pallet) + { + bool success = await _repo.CheckCambiaStatoBatchAsync(tipoInput, IdxMacchina, InizioStato, IdxTipo, CodArt, Value, MatrOpr, pallet); + return success; + } + + /// + public async Task EvListMicroStatoInsertAsync(MicroStatoMacchinaModel newRecMsm, EventListModel newRecEv) + { + bool success = await _repo.EvListMicroStatoInsertAsync(newRecMsm, newRecEv); + return success; + } + + /// + public async Task IobInsEnabAsync(string idxMacchina) + { + var key = MP.Data.Utils.RedKeyDatiMacc(idxMacchina, MpIoNS); + + string? val = await _redisDb.HashGetAsync(key, "insEnabled"); + + if (val == null) + { + var data = await ResetDatiMacchinaAsync(idxMacchina); + data.TryGetValue("insEnabled", out val); + } + + return val != null && (val == "1" || val.ToLower() == "true"); + } + + /// + public async Task MicroStatoMacchinaUpsertAsync(MicroStatoMacchinaModel newRec) + { + bool success = await _repo.MicroStatoMacchinaUpsertAsync(newRec); + return success; + } + + /// + public async Task ProcessInputAsync(string idxMacchina, string valore, string dtEve, string dtCurr, string contatore) + { + string answ = ""; + if (ValidateinputParams(idxMacchina, valore, dtEve, dtCurr)) + { + DateTime dataOraEvento = ParseEventTime(dtEve, dtCurr); + + // se abilitato registro evento sul DB + if (await IobSLogEnabAsync(idxMacchina)) + { + int cntVal = 0; + int.TryParse(contatore, out cntVal); + await saveSigLogAsync(idxMacchina, valore, dataOraEvento, cntVal); + } + // continuo col resto + try + { + // scrivo keep alive!!! (se necessario, altrimenti è in cache...) + await ScriviKeepAliveAsync(idxMacchina, DateTime.Now); + // Cache dati macchina per evitare lookup ridondanti + Dictionary datiMacc = await mDatiMacchineAsync(idxMacchina); + // verifico se sia una macchina MULTI.... + if (isMulti(idxMacchina, datiMacc)) + { + // inizio preprocessing + string newVal = ""; + // processo OGNI macchina a stati dell'impianto... (KEY:IdxMacchina / IdxMacchina#qualcosa, Val = IdxFamIn) + foreach (var item in await mTabMSMIAsync(idxMacchina)) + { + newVal = preProcInput(item.Key, valore, datiMacc); + // ora processo e salvo il valOut del microstato... + // INTERNAMENTE gestisce i casi DB/REDIS secondo necessità + await CheckMicroStatoAsync(item.Key, newVal, dataOraEvento, contatore, datiMacc); + } + } + else + { + // ora processo e salvo il valOut del microstato... INTERNAMENTE + // gestisce i casi DB/REDIS secondo necessità + await CheckMicroStatoAsync(idxMacchina, valore, dataOraEvento, contatore, datiMacc); + } + // forzo RESET dati macchina... + await ResetDatiMacchinaAsync(idxMacchina); + // registro in risposta che è andato tutto bene... + answ = "OK"; + } + catch (Exception exc) + { + string errore = $"Errore: {Environment.NewLine}{exc}"; + Log.Error(errore); + answ = errore; + } + } + return answ; + } + + /// + public async Task ScriviKeepAliveAsync(string IdxMacchina, DateTime oraMacchina) + { + // cerco se ho keep alive in redis, + var currKey = MP.Data.Utils.RedKeyHash($"KeepAlive:{IdxMacchina}"); + bool keyPresent = await _redisDb.KeyExistsAsync(currKey); + // se NON presente salvo in REDIS con TTL 10 sec e sul DB... + if (!keyPresent) + { + DateTime adesso = DateTime.Now; + await _redisDb.StringSetAsync(currKey, adesso.ToString("s"), TimeSpan.FromSeconds(30)); + // effettuo scrittura sul DB + await _repo.KeepAliveUpsertAsync(IdxMacchina, DateTime.Now, oraMacchina); + } + } + + #endregion Public Methods + + #region Protected Fields + + protected Random rand = new Random(); + + #endregion Protected Fields + + #region Protected Methods + + /// + /// Restituisce un timeout dai minuti richiesti + tempo random 1..60 sec + /// + /// + /// + protected TimeSpan getRandTOut(double stdMinutes) + { + double rndValue = stdMinutes + (double)rand.Next(1, 60) / 60; + return TimeSpan.FromMinutes(rndValue); + } + + #endregion Protected Methods + + #region Private Fields + + private static Logger Log = LogManager.GetCurrentClassLogger(); + + private readonly string _className; + + private readonly IIocRepository _repo; + + private readonly IServiceScopeFactory _scopeFactory; + + /// + /// Provider CultureInfo x parse valori (es dataora) + /// + private CultureInfo ciProvider = CultureInfo.InvariantCulture; + + /// + /// Formato dataora standard x parsing + /// + private string dtFormat = "yyyyMMddHHmmssfff"; + + private int redisLongTimeCache = 5; + + private int redisShortTimeCache = 2; + + #endregion Private Fields + + #region Private Methods + + /// + /// controlla se da il segnale di "microstato" deriva un evento da generare - modalità OFFLINE + /// + /// idx macchina + /// valOut ingresso + /// data-ora evento (server) + /// sequenza dati inviati + /// dati macchina in cache (opzionale, se null fa lookup) + /// + private async Task CheckMicroStatoAsync(string idxMacchina, string valore, DateTime dtEve, string contatore, Dictionary? datiMaccCache = null) + { + // recupero SE IMPIEGATO REDIS i valori del Dictionary della macchina... + Dictionary datiMacc = datiMaccCache ?? await mDatiMacchineAsync(idxMacchina); + + // processing + inputComandoMapo answ = new inputComandoMapo(); + + // SE no trovassi verifico se esista la macchina altrimenti la creo... REDIS compliant + if (!datiMacc.ContainsKey(idxMacchina)) + { + await verificaIdxMacchinaAsync(idxMacchina); + } + + // continuo processing... + string CodArticolo = datiMacc["CodArticolo"]; + if (string.IsNullOrEmpty(CodArticolo)) + { + var allDatiMacch = await _repo.DatiMacchineGetAllAsync(); + var recMacc = allDatiMacch.FirstOrDefault(x => x.IdxMacchina == idxMacchina); + if (recMacc != null) + { + CodArticolo = recMacc.CodArticoloA; + } + } + // preparo gestione val ingresso + int? valINT = 0; + int idxTipoEv = 0; + int next_idxMS = 0; + try + { + valINT = int.Parse(valore, NumberStyles.HexNumber); + int idxFamIn = Convert.ToInt32(datiMacc["IdxFamIn"]); + int idxMicroStato = Convert.ToInt32(datiMacc["IdxMicroStato"]); + int valIOB = Convert.ToInt32(valINT); + next_idxMS = idxMicroStato; + // recupero singolo valOut (stringa) x chiave + string todoSMI = await ValoreSmiAsync(idxFamIn, idxMicroStato, valIOB); + // solo se ho trovato un risultato nella tab SMI della famiglia macchina... + if (!string.IsNullOrEmpty(todoSMI) && todoSMI.Contains("_")) + { + // splitto e salvo valori OUT... + string[] valori = todoSMI.Split('_'); + idxTipoEv = Convert.ToInt32(valori[0]); + next_idxMS = Convert.ToInt32(valori[1]); + } + } + catch (Exception exc) + { + Log.Error($"[ChkMiSt_5a] - - Eccezione in recupero riga Trans ingressi | idxMacchina {idxMacchina} | valINT {valINT}:{Environment.NewLine}{exc}", Environment.NewLine, exc, valINT, idxMacchina); + } + + // effettuo update vari SU DB!!! + MicroStatoMacchinaModel newRecMsm = new MicroStatoMacchinaModel() + { + IdxMacchina = idxMacchina, + IdxMicroStato = next_idxMS, + InizioStato = dtEve, + Value = valore + }; + if (idxTipoEv > 0) + { + // preparo record + string valEsteso = string.Format("[{0}] {1}", contatore.PadLeft(3, '0'), valore); + // creo evento + EventListModel newRecEv = new EventListModel() + { + CodArticolo = CodArticolo, + IdxMacchina = idxMacchina, + IdxTipo = idxTipoEv, + InizioStato = dtEve, + MatrOpr = 0, + pallet = "-", + Value = valEsteso + }; + // salva e processa evento + microstato + answ = await scriviRigaEventoAsync(newRecMsm, newRecEv); + } + else + { + await _repo.MicroStatoMacchinaUpsertAsync(newRecMsm); + } + return answ; + } + + /// + /// Elenco completo config da DB + /// + /// + private async Task> ConfigGetAllAsync() + { + List? result = new List(); + // cerco in redis... + RedisValue rawData = await _redisDb.StringGetAsync(MP.Data.Utils.redisConfKey); + string source = "DB"; + if (!string.IsNullOrEmpty($"{rawData}")) + { + result = JsonConvert.DeserializeObject>($"{rawData}"); + source = "REDIS"; + } + else + { + result = await _repo.ConfigGetAllAsync(); + //result = await Task.FromResult(SpecDbController.ConfigGetAllAsync()); + // serializzo e salvo... + rawData = JsonConvert.SerializeObject(result); + await _redisDb.StringSetAsync(MP.Data.Utils.redisConfKey, rawData, getRandTOut(redisLongTimeCache)); + } + Log.Debug($"ConfigGetAllAsync Read from {source}"); + if (result == null) + { + result = new List(); + } + return result; + } + + /// + /// Helper standardizzazione valOut dataora ricevuto da IOB remoti + /// + /// + /// + private string dtFormStd(string? s) + { + return s?.Length > 17 ? s[..17] : s?.PadRight(17, '0') ?? string.Empty; + } + + /// + /// Restituisce il valOut booleano se la macchina sia abilitata all'inserimento COMPLETO nel + /// Signal Log + /// + /// + /// + private async Task IobSLogEnabAsync(string idxMacchina) + { + bool answ = false; + // ORA recupero da memoria redis... + try + { + var currHash = MP.Data.Utils.RedKeyDatiMacc(idxMacchina, MpIoNS); + RedisValue rawData = await _redisDb.HashGetAsync(currHash, (RedisValue)"sLogEnabled"); + // se è vuoto... leggo da DB e popolo! + if (!rawData.HasValue) + { + await ResetDatiMacchinaAsync(idxMacchina); + // riprovo + rawData = await _redisDb.HashGetAsync(currHash, (RedisValue)"sLogEnabled"); + } + + // provo conversione + bool.TryParse($"{rawData}", out answ); + } + catch (Exception exc) + { + Log.Error($"Errore IobSLogEnabAsync | idxMacchina {idxMacchina}:{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// Restituisce il valOut booleano se la macchina sia di tipo MULTI (con più state machine x INGRESSI) + /// usando dati macchina in cache per evitare lookup ridondanti + /// + /// + /// + /// + private bool isMulti(string idxMacchina, Dictionary datiMacc) + { + bool answ = false; + try + { + answ = Convert.ToBoolean(datiMacc.ContainsKey("Multi") && datiMacc["Multi"] == "1"); + } + catch (Exception exc) + { + Log.Error($"Eccezione in isMulti{Environment.NewLine}{exc}"); + } + return answ; + } + + private async Task> ListMasterAsync() + { + HashSet result = new(); + string currKey = $"{MP.Data.Utils.redisBaseAddr}:ListMaster"; + RedisValue rawData = await _redisDb.StringGetAsync(currKey); + if (rawData.HasValue) + { + result = JsonConvert.DeserializeObject>($"{rawData}") ?? new(); + } + else + { + var fullList = await Macchine2SlaveGetAllAsync(); + result = fullList.Select(x => x.IdxMacchina).ToHashSet(); + // serializzo e salvo... + rawData = JsonConvert.SerializeObject(result); + await _redisDb.StringSetAsync(currKey, rawData, getRandTOut(redisLongTimeCache * 10)); + } + return result; + } + + private async Task> ListSlaveAsync() + { + HashSet result = new(); + string currKey = $"{MP.Data.Utils.redisBaseAddr}:ListSlave"; + RedisValue rawData = await _redisDb.StringGetAsync(currKey); + if (rawData.HasValue) + { + result = JsonConvert.DeserializeObject>($"{rawData}") ?? new(); + } + else + { + var fullList = await Macchine2SlaveGetAllAsync(); + result = fullList.Select(x => x.IdxMacchinaSlave).Distinct().ToHashSet(); + // serializzo e salvo... + rawData = JsonConvert.SerializeObject(result); + await _redisDb.StringSetAsync(currKey, rawData, getRandTOut(redisLongTimeCache * 10)); + } + return result; + } + + /// + /// Elenco completo valori Macchine 2 Slave + /// + /// + private async Task> Macchine2SlaveGetAllAsync() + { + List? result = new List(); + string currKey = $"{MP.Data.Utils.redisBaseAddr}:M2STab"; + // cerco in redis dato valOut sel macchina... + RedisValue rawData = await _redisDb.StringGetAsync(currKey); + if (rawData.HasValue) + { + result = JsonConvert.DeserializeObject>($"{rawData}"); + } + else + { + result = await _repo.Macchine2SlaveAsync(); + // serializzo e salvo... + rawData = JsonConvert.SerializeObject(result); + await _redisDb.StringSetAsync(currKey, rawData, getRandTOut(redisLongTimeCache * 10)); + } + if (result == null) + { + result = new List(); + } + return result; + } + + /// + /// Restitusice elenco KVP dei campi DatiMacchine + StatoMacchine per l'impianto indicato + /// + /// + /// + private async Task> mDatiMacchineAsync(string idxMacchina) + { + // hard coded dimensione vettore DatiMacchine + Dictionary answ = new Dictionary(); + // ORA recupero da memoria redis... + try + { + var currHash = MP.Data.Utils.RedKeyDatiMacc(idxMacchina, MpIoNS); + answ = await RedisGetHashDictAsync(currHash); + // se è vuoto... leggo da DB e popolo! + if (answ.Count == 0) + { + answ = await ResetDatiMacchinaAsync(idxMacchina); + } + } + catch (Exception exc) + { + Log.Error($"Errore in compilazione dati Macchine x Redis - idxMacchina {idxMacchina}:{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// Restitusice elenco KVP (async) per evitare blocchi quando chiamato da metodi asincroni + /// + /// + /// + private async Task[]> mTabMSMIAsync(string idxMacchina) + { + KeyValuePair[] answ = new KeyValuePair[1]; + answ[0] = new KeyValuePair("0", "0"); + try + { + var currHash = MP.Data.Utils.RedKeyMsmi(idxMacchina); + answ = await RedisGetHashAsync(currHash); + if (answ == null || answ.Length == 0) + { + answ = await resetMSMIAsync(idxMacchina); + } + } + catch (Exception exc) + { + Log.Error($"Errore in compilazione Tabella Multi State Machine Ingressi x Redis:{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// Calcola dataora evento da info dt ricevute + /// + /// + /// + /// + private DateTime ParseEventTime(string dtEve, string dtCurr) + { + DateTime dataOraEvento = DateTime.Now; + + // fix formato dataora in ingresso + string stdEve = dtFormStd(dtEve); + string stdCurr = dtFormStd(dtCurr); + + // 2. Se le stringhe normalizzate coincidono, skip dei calcoli + if (stdEve != stdCurr) + { + // 3. Parsing sicuro + if (DateTime.TryParseExact(stdEve, dtFormat, ciProvider, DateTimeStyles.None, out DateTime dtEvento) && + DateTime.TryParseExact(stdCurr, dtFormat, ciProvider, DateTimeStyles.None, out DateTime dtCorrente)) + { + TimeSpan diff = dtCorrente - dtEvento; + double ms = Math.Abs(diff.TotalMilliseconds); + + // 4. Classificazione delta con switch expression (più leggibile e performante) + string deltaClass = ms switch + { + <= 10 => "0-10 ms", + <= 100 => "10-100 ms", + <= 1000 => "100-1000 ms", + <= 10000 => "1-10 sec", + _ => "> 10 sec" + }; + + Log.Debug($"Correzione delta {deltaClass}"); + + // 5. Correzione data/ora server: sottrao lo scarto calcolato + dataOraEvento = dataOraEvento.Subtract(diff); + } + else + { + Log.Error($"Errore parsing date: {stdEve} | {stdCurr}"); + } + } + return dataOraEvento; + } + + /// + /// Calcola l'effettivo valOut da passare alla macchina a stati INGRESSI usando dati macchina in cache + /// + /// + /// + /// + /// + private string preProcInput(string idxMacchina, string valore, Dictionary datiMacc) + { + string newVal = ""; + try + { + // variabili + int valINT = 0; + int BitFilt = 0; + int BSR = 0; + bool ExplodeBit = false; + int NumBit = 0; + int newValInt = 0; + // recupero parametri dalla cache... + int.TryParse(datiMacc.ContainsKey("BitFilt") ? datiMacc["BitFilt"] : "0", out BitFilt); + int.TryParse(datiMacc.ContainsKey("BSR") ? datiMacc["BSR"] : "0", out BSR); + Boolean.TryParse(datiMacc.ContainsKey("ExplodeBit") ? datiMacc["ExplodeBit"] : "false", out ExplodeBit); + // non usato (x ora) + int.TryParse(datiMacc.ContainsKey("NumBit") ? datiMacc["NumBit"] : "0", out NumBit); + + // recupero valOut + valINT = int.Parse(valore, NumberStyles.HexNumber); + // filtro + newValInt = MP.Core.Utils.bMaskInt(valINT, BitFilt); + // effettuo eventuale BitShiftRight + if (BSR > 0) + { + newValInt = newValInt >> BSR; + } + // effettuo eventuale esplosione in BIT esclusivi + if (ExplodeBit) + { + newValInt = Convert.ToInt32(1 << newValInt); + } + // riconverto a STRING HEX!!! + newVal = newValInt.ToString("X"); + } + catch + { + newVal = valore; + } + + return newVal; + } + + private async Task[]> RedisGetHashAsync(RedisKey redKey) + { + HashEntry[] rawData = await _redisDb.HashGetAllAsync(redKey); + var result = rawData.Where(x => !x.Name.IsNull).Select(x => new KeyValuePair($"{x.Name}", $"{x.Value}")).ToArray(); + return result; + } + + private async Task> RedisGetHashDictAsync(RedisKey hashKey) + { + HashEntry[] rawData = await _redisDb.HashGetAllAsync(hashKey); + var result = rawData + .Where(x => !x.Name.IsNull) + .ToDictionary(x => x.Name.ToString(), x => x.Value.ToString()); + return result; + } + + private async Task RedisSetHashAsync(RedisKey redKey, KeyValuePair[] valori, double expireSeconds = -1.0) + { + HashEntry[] redHash = valori.Select(x => new HashEntry(x.Key, x.Value)).ToArray(); + await _redisDb.HashSetAsync(redKey, redHash); + if (expireSeconds > 0.0) + { + await _redisDb.KeyExpireAsync(redKey, DateTime.Now.AddSeconds(expireSeconds)); + } + } + + /// + /// Restitusice elenco KVP dei campi DatiMacchine + StatoMacchine per l'impianto indicato + /// + /// + /// + private async Task> ResetDatiMacchinaAsync(string idxMacc) + { + Dictionary result = new Dictionary(); + VMSFDModel? dbResult = null; + dbResult = await _repo.VMSFDGetByMaccAsync(idxMacc); + if (dbResult == null) return new Dictionary(); + + double numSecCache = redisLongTimeCache; + // converto in formato dizionario... + if (dbResult != null) + { + // salvo 1:1 i valori... STATO + result.Add("IdxMicroStato", $"{dbResult.IdxMicroStato}"); + result.Add("IdxStato", $"{dbResult.IdxStato}"); + result.Add("CodArticolo", $"{dbResult.CodArticolo}"); + result.Add("insEnabled", $"{dbResult.InsEnabled}"); + result.Add("sLogEnabled", $"{dbResult.SLogEnabled}"); + result.Add("pallet", $"{dbResult.Pallet}"); + result.Add("CodArticolo_A", $"{dbResult.CodArticoloA}"); + result.Add("CodArticolo_B", $"{dbResult.CodArticoloB}"); + result.Add("TempoCicloBase", $"{dbResult.TempoCicloBase}"); + result.Add("PzPalletProd", $"{dbResult.PzPalletProd}"); + result.Add("MatrOpr", $"{dbResult.MatrOpr}"); + result.Add("lastVal", $"{dbResult.LastVal}"); + result.Add("TCBase", $"{dbResult.TempoCicloBase}"); + + //...e SETUP + result.Add("CodMacc", $"{dbResult.Codmacchina}"); + result.Add("IdxFamIn", $"{dbResult.IdxFamigliaIngresso}"); + result.Add("Multi", $"{dbResult.Multi}"); + result.Add("BitFilt", $"{dbResult.BitFilt}"); + result.Add("MaxVal", $"{dbResult.MaxVal}"); + result.Add("BSR", $"{dbResult.Bsr}"); + result.Add("ExplodeBit", $"{dbResult.ExplodeBit}"); + result.Add("NumBit", $"{dbResult.NumBit}"); + result.Add("IdxFamMacc", $"{dbResult.IdxFamiglia}"); + result.Add("simplePallet", $"{dbResult.SimplePallet}"); + result.Add("palletChange", $"{dbResult.PalletChange}"); + // durata cache in secondi dal valOut insEnabled... + //double numSecCache = ((result["insEnabled"].ToLower() == "true") ? redisShortTimeCache : redisLongTimeCache); + numSecCache = dbResult.InsEnabled ? redisShortTimeCache : redisLongTimeCache; + } + else + { + } + // dati master/slave + string isMaster = (await ListMasterAsync()).Contains(idxMacc) ? "1" : "0"; + string isSlave = (await ListSlaveAsync()).Contains(idxMacc) ? "1" : "0"; + result.Add("Master", isMaster); + result.Add("Slave", isSlave); + + // Processing redis in transazoine... + var redKey = MP.Data.Utils.RedKeyDatiMacc(idxMacc, MpIoNS); + + // variazione con redis transaction... + var transaction = _redisDb.CreateTransaction(); + // 1. Eliminiamo la chiave (rimuove i vecchi campi) + _ = transaction.KeyDeleteAsync(redKey); + // 2. Prepariamo gli HashEntry per il batch (più efficiente di un Dictionary) + HashEntry[] entries = result.Select(kvp => new HashEntry(kvp.Key, kvp.Value)).ToArray(); + // 3. Inseriamo i nuovi valori + _ = transaction.HashSetAsync(redKey, entries); + // 4. Impostiamo l'expiration in un unico colpo + _ = transaction.KeyExpireAsync(redKey, TimeSpan.FromSeconds(numSecCache)); + // Eseguiamo tutto in un unico viaggio verso Redis + bool success = await transaction.ExecuteAsync(); + + return result; + } + + /// + /// Resetta (rileggendo) i dati della State Machine multi ingressi nel formato + /// currKey: IdxMacchina + /// value: IdxFamigliaIngresso + /// + /// + /// + private async Task[]> resetMSMIAsync(string idxMacchina) + { + var currHash = MP.Data.Utils.RedKeyMsmi(idxMacchina); + // recupero records + var tabMSMI = await _repo.VMSFDGetMultiByMaccAsync(idxMacchina); + + KeyValuePair[] answ = new KeyValuePair[tabMSMI.Count]; + // salvo tutti i valori StateMachineIngressi... + int i = 0; + foreach (var item in tabMSMI) + { + answ[i] = new KeyValuePair(item.IdxMacchina, item.IdxFamigliaIngresso.ToString()); + i++; + } + // verifico il timeout (default 60 sec...) + var sTOutSmi = await tryGetConfigAsync("TmOut.MSMI"); + int tOut = 60; + int.TryParse(sTOutSmi, out tOut); + tOut = tOut <= 60 ? 60 : tOut; + // salvo in redis! + await RedisSetHashAsync(currHash, answ, tOut); + return answ; + } + + /// + /// Resetta (rileggendo) i dati della State Machine ingressi nel formato + /// currKey: cState_nVal (current MICRO-STATE + "_" + new Value) + /// value: iTipoEv_nState (IdxTipoEv da trasmettere + New MICRO-STATE) + /// + /// + /// + private async Task[]> resetSMIAsync(int idxFamIn) + { + var currHash = MP.Data.Utils.GetHashSMI(idxFamIn); + // leggo da DB... + var tabSMI = await _repo.StateMachineIngressiAsync(idxFamIn); + + KeyValuePair[] answ = new KeyValuePair[tabSMI.Count]; + // salvo tutti i valori StateMachineIngressi... + int i = 0; + string key = ""; + string val = ""; + foreach (var item in tabSMI) + { + key = string.Format("{0}_{1}", item.IdxMicroStato, item.ValoreIngresso); + val = string.Format("{0}_{1}", item.IdxTipoEvento, item.NextIdxMicroStato); + answ[i] = new KeyValuePair(key, val); + i++; + } + // verifico il timeout (default 60 sec...) + int tOut = 300; + var sTOutSmi = await tryGetConfigAsync("TmOut.SMI"); + if (!string.IsNullOrEmpty(sTOutSmi)) + { + int.TryParse(sTOutSmi, out tOut); + } + // salvo in redis! + await RedisSetHashAsync(currHash, answ, tOut); + return answ; + } + + /// + /// salva il segnale di "microstato" (segnale) ASYNC + /// + /// idx macchina + /// valOut ingresso + /// data-ora evento (server) + /// contatore sequenza dati inviati + /// + private async Task saveSigLogAsync(string idxMacchina, string valore, DateTime dtEve, int contatore) + { + SignalLogModel newRec = new SignalLogModel() + { + IdxMacchina = idxMacchina, + DtCurr = DateTime.Now, + DtEve = dtEve, + Contatore = contatore, + Valore = valore + }; + return await _repo.SignalLogInsertAsync(newRec); + } + + /// + /// Scrive una riga evento + una riga microstato insieme, ed effettua verifica necessità cambio stato + /// + /// Record MicroStatoMacchina + /// record EventList + /// + private async Task scriviRigaEventoAsync(MicroStatoMacchinaModel newRecMsm, EventListModel newRecEv) + { + bool inserito = false; + + // inserisco evento + inserito = await _repo.EvListMicroStatoInsertAsync(newRecMsm, newRecEv); + // faccio controllo per eventuale cambio stato da tab transizioni... + + await _repo.CheckCambiaStatoBatchAsync(tipoInputEvento.hw, newRecEv.IdxMacchina, newRecEv.InizioStato ?? DateTime.Now, newRecEv.IdxTipo, newRecEv.CodArticolo, newRecEv.Value, newRecEv.MatrOpr, newRecEv.pallet); + + // formatto output + inputComandoMapo answ = new inputComandoMapo(); + answ.outValue = inserito.ToString(); + answ.needStatusRefresh = true; + return answ; + } + + /// + /// Restitusice elenco KVP dei campi della State Machine ingressi nel formato + /// currKey: cState_nVal (current MICRO-STATE + "_" + new Value) + /// value: iTipoEv_nState (IdxTipoEv da trasmettere + New MICRO-STATE + /// + /// + /// + private async Task[]> StateMachInByKeyAsync(int idxFamIn) + { + // hard coded dimensione vettore DatiMacchine + KeyValuePair[] answ = new KeyValuePair[1]; + // iniziualizzo con un valOut... 0/0 + answ[0] = new KeyValuePair("0", "0"); + // ORA recupero da memoria redis... + try + { + var currHash = MP.Data.Utils.GetHashSMI(idxFamIn); + answ = await RedisGetHashAsync(currHash); + // se è vuoto... leggo da DB e popolo! + if (answ.Length == 0) + { + answ = await resetSMIAsync(idxFamIn); + } + } + catch (Exception exc) + { + Log.Error($"Errore in compilazione State Machine Ingressi x Redis:{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// Restituisce valOut della stringa (SE disponibile) + /// + /// + /// + private async Task tryGetConfigAsync(string keyName) + { + string answ = ""; + // preselezione valori + var configData = await ConfigGetAllAsync(); + var currRec = configData.FirstOrDefault(x => x.Chiave == keyName); + if (currRec != null) + { + answ = currRec.Valore; + } + return answ; + } + + /// + /// Validazione preliminare valori input + /// + /// + /// + /// + /// + /// + private bool ValidateinputParams(string idxMacchina, string valore, string dtEve, string dtCurr) + { + bool isValid = false; + // preparo stringa valori correnti + string currVals = $"idxMacchina: {idxMacchina} | valOut: {valore} | dtEve: {dtEve} | dtCurr:{dtCurr}"; + if (dtEve == null || dtCurr == null) + { + Log.Warn($"procInput: null found | {currVals}"); + } + else if (dtEve.Length < 17 || dtCurr.Length < 17) + { + Log.Info($"procInput: invalid data | {currVals}"); + } + else if (string.IsNullOrEmpty(idxMacchina)) + { + Log.Info($"procInput: missing IdxMacchina | {currVals}"); + } + else if (string.IsNullOrEmpty(valore)) + { + Log.Info($"procInput: missing valOut | {currVals}"); + } + else + { + isValid = true; + } + return isValid; + } + + /// + /// Restituisce il valore SPECIFICATO per la state machine ingressi + /// value: iTipoEv_nState (IdxTipoEv da trasmettere + New MICRO-STATE) + /// + /// + /// + /// + /// + private async Task ValoreSmiAsync(int idxFamIn, int idxMicroStato, int valoreIn) + { + string valOut = ""; + var currHash = MP.Data.Utils.GetHashSMI(idxFamIn); + string field = $"{idxMicroStato}_{valoreIn}"; + var searchVal = await _redisDb.HashGetAsync(currHash, field); + if (!searchVal.HasValue) + { + // ricarico tabella (salvando in redis x ricerca successiva)! + var valori = await StateMachInByKeyAsync(idxFamIn); + if (valori.Any(x => x.Key == field)) + { + searchVal = valori.FirstOrDefault(x => x.Key == field).Value; + } + } + valOut = $"{searchVal}"; + return valOut; + } + + /// + /// cerca codice in anagrafica macchine ed eventualmente inserisce nuova macchina + /// + /// + private async Task verificaIdxMacchinaAsync(string IdxMacchina) + { + // esecuzione in REDIS...cerco status macchina... + if ((await mDatiMacchineAsync(IdxMacchina)).Count == 0) + { + // verifico se esiste su DB + var dbRec = await _repo.MacchineGetByIdxAsync(IdxMacchina); + if (dbRec == null) + { + MacchineModel newRec = new MacchineModel() + { + IdxMacchina = IdxMacchina, + CodMacchina = "0000", + Nome = IdxMacchina, + Descrizione = "Macchina non codificata", + Note = "-", + locazione = "", + RecipeArchivePath = "", + RecipePath = "" + }; + await _repo.MacchineUpsertAsync(newRec); + + // verifico ci sia un microstato macchina... + var recMSM = await _repo.MicroStatoMacchinaGetByIdxMaccAsync(IdxMacchina); + if (recMSM.Count == 0) + { + // inserisco nuovo stato... + MicroStatoMacchinaModel msRec = new MicroStatoMacchinaModel() + { + IdxMacchina = IdxMacchina, + IdxMicroStato = 0, + InizioStato = DateTime.Now, + Value = "00" + }; + await _repo.MicroStatoMacchinaUpsertAsync(msRec); + } + } + } + } + + #endregion Private Methods + } +} \ No newline at end of file diff --git a/MP.Data/Services/Utils/StatsAggrService.cs b/MP.Data/Services/Utils/StatsAggrService.cs index f0a9f0c7..cadf72cf 100644 --- a/MP.Data/Services/Utils/StatsAggrService.cs +++ b/MP.Data/Services/Utils/StatsAggrService.cs @@ -104,7 +104,8 @@ namespace MP.Data.Services.Utils }) .ToList() }) - .OrderBy(s => s.SeriesName) + //.OrderByDescending(c => c.DataPoints.Sum(x => x.y)) + //.OrderBy(s => s.SeriesName) .ToList(); } else @@ -162,13 +163,14 @@ namespace MP.Data.Services.Utils { Dictionary> result = new(); DateTime oggi = DateTime.Today; - var rawData = await GetFiltAsync(oggi.AddDays(-7), oggi); + int numDays = 7; + var rawData = await GetFiltAsync(oggi.AddDays(-numDays), oggi); // calcolo le varie statistiche... var pDestRequest = rawData.GroupBy(x => x.Destination) .Select(g => new StatDataDTO { Label = g.Key, - Value = g.Sum(x => x.RequestCount) + Value = g.Sum(x => x.RequestCount) / numDays }) .OrderByDescending(x => x.Value) .ToList(); @@ -178,7 +180,7 @@ namespace MP.Data.Services.Utils .Select(g => new StatDataDTO { Label = g.Key, - Value = g.Sum(x => x.RequestCount * x.AvgDuration) + Value = g.Sum(x => x.RequestCount * x.AvgDuration) / numDays }) .OrderByDescending(x => x.Value) .ToList(); @@ -189,16 +191,17 @@ namespace MP.Data.Services.Utils protected async Task>> GetParetoMaccAsync(int numDay) { - numDay = numDay > 1 ? numDay : 1; Dictionary> result = new(); - DateTime oggi = DateTime.Today; - var rawData = await GetFiltAsync(oggi.AddDays(-numDay), oggi); + DateTime adesso = DateTime.Now; + DateTime start = DateTime.Today.AddDays(-numDay); + var rawData = await GetFiltAsync(start, adesso); + var numHour = adesso.Subtract(start).TotalHours; // calcolo le varie statistiche... var pDestRequest = rawData.GroupBy(x => x.MachineId) .Select(g => new StatDataDTO { Label = g.Key, - Value = g.Sum(x => x.RequestCount) / numDay + Value = g.Sum(x => x.RequestCount) / numHour }) .OrderByDescending(x => x.Value) .ToList(); @@ -208,7 +211,7 @@ namespace MP.Data.Services.Utils .Select(g => new StatDataDTO { Label = g.Key, - Value = g.Sum(x => x.RequestCount * x.AvgDuration) / numDay + Value = g.Sum(x => x.RequestCount * x.AvgDuration) / numHour }) .OrderByDescending(x => x.Value) .ToList(); diff --git a/MP.IOC/Components/Pages/CallStats.razor b/MP.IOC/Components/Pages/CallStats.razor index 448c4e32..65d92366 100644 --- a/MP.IOC/Components/Pages/CallStats.razor +++ b/MP.IOC/Components/Pages/CallStats.razor @@ -10,7 +10,7 @@
-
Avail Data (24h)
+
Avail Data (last 24h)
/// idx macchina - /// valore ingresso + /// valOut ingresso /// data-ora evento (server) /// contatore sequenza dati inviati /// @@ -3847,16 +3866,14 @@ namespace MP.IOC.Data /// public async Task ScriviKeepAliveAsync(string IdxMacchina, DateTime oraMacchina) { - string nomeVar = string.Format("KeepAlive:{0}", IdxMacchina); // cerco se ho keep alive in redis, - DateTime adesso = DateTime.Now; - var currKey = Utils.RedKeyHash(nomeVar); + var currKey = Utils.RedKeyHash($"KeepAlive:{IdxMacchina}"); bool keyPresent = await RedisKeyPresentAsync(currKey); // se NON presente salvo in REDIS con TTL 10 sec e sul DB... if (!keyPresent) { - await redisDb.StringSetAsync(currKey, adesso.ToString("s"), TimeSpan.FromSeconds(20)); - Log.Trace($"Scrittura keep alive! IdxMacchina: {IdxMacchina}"); + DateTime adesso = DateTime.Now; + await redisDb.StringSetAsync(currKey, adesso.ToString("s"), TimeSpan.FromSeconds(30)); // effettuo scrittura sul DB await IocDbController.KeepAliveUpsertAsync(IdxMacchina, DateTime.Now, oraMacchina); } @@ -3906,7 +3923,7 @@ namespace MP.IOC.Data { // hard coded dimensione vettore DatiMacchine KeyValuePair[] answ = new KeyValuePair[1]; - // iniziualizzo con un valore... 0/0 + // iniziualizzo con un valOut... 0/0 answ[0] = new KeyValuePair("0", "0"); // ORA recupero da memoria redis... try @@ -3936,9 +3953,9 @@ namespace MP.IOC.Data } /// - /// restituisce il valore da REDIS associato al tag richeisto + /// restituisce il valOut da REDIS associato al tag richeisto /// - /// Chiave in cui cercare il valore + /// Chiave in cui cercare il valOut /// public string TagConfGetKey(string redKey) { @@ -4005,7 +4022,7 @@ namespace MP.IOC.Data fluxLogList.Add(editFL); } - // serializzo nuovamente valore + // serializzo nuovamente valOut DossierFluxLogDTO? result = new DossierFluxLogDTO(); var ODLflux = result.ODL.ToList(); foreach (var item in fluxLogList) @@ -4038,10 +4055,10 @@ namespace MP.IOC.Data Log.Info($"upsertCurrObjItems | idxMacchina: {idxMacchina} | {innovations.Count} innovations"); // leggo i valori attuali... List actValues = MachineParamList(idxMacchina); - // per ogni valore passatomi faccio insert o update rispetto elenco valori correnti in REDIS + // per ogni valOut passatomi faccio insert o update rispetto elenco valori correnti in REDIS foreach (var item in actValues) { - // cerco nelle innovazioni SE CI SIA il valore... + // cerco nelle innovazioni SE CI SIA il valOut... var trovato = innovations.Find(obj => obj.uid == item.uid); // se non trovato nelle innovazioni... if (trovato == null) @@ -4074,11 +4091,23 @@ namespace MP.IOC.Data /// /// /// - public string ValoreSMI(int idxFamIn, int idxMicroStato, int valoreIn) + public async Task ValoreSmiAsync(int idxFamIn, int idxMicroStato, int valoreIn) { + string valOut = ""; var currHash = Utils.GetHashSMI(idxFamIn); string field = $"{idxMicroStato}_{valoreIn}"; - return RedisGetHashField(currHash, field); + var searchVal = await RedisGetHashFieldAsync(currHash, field); + if (!searchVal.HasValue) + { + // ricarico tabella (salvando in redis x ricerca successiva)! + var valori = await StateMachInByKeyAsync(idxFamIn); + if (valori.Any(x => x.Key == field)) + { + searchVal = valori.FirstOrDefault(x => x.Key == field).Value; + } + } + valOut = $"{searchVal}"; + return valOut; } /// @@ -4280,8 +4309,8 @@ namespace MP.IOC.Data /// private async Task CheckCambiaStatoBatchAsync(tipoInputEvento tipoInput, string IdxMacchina, DateTime InizioStato, int IdxTipo, string CodArt, string Value, int MatrOpr, string pallet) { - //DS_applicazione.TransizioneStatiDataTable tabTransStati; - //DS_applicazione.TransizioneStatiRow rigaTransStati; + await IocDbController.CheckCambiaStatoBatchAsync(tipoInput, IdxMacchina, InizioStato, IdxTipo, CodArt, Value, MatrOpr, pallet); +#if false List listTransit = new List(); TransizioneStatiModel? rigaTrans = null; switch (tipoInput) @@ -4328,7 +4357,8 @@ namespace MP.IOC.Data default: break; - } + } +#endif } /// @@ -4378,7 +4408,7 @@ namespace MP.IOC.Data } /// - /// Helper standardizzazione valore dataora ricevuto da IOB remoti + /// Helper standardizzazione valOut dataora ricevuto da IOB remoti /// /// /// @@ -4467,7 +4497,7 @@ namespace MP.IOC.Data } /// - /// Restituisce il valore booleano se la macchina sia di tipo MULTI (con più state machine x INGRESSI) + /// Restituisce il valOut booleano se la macchina sia di tipo MULTI (con più state machine x INGRESSI) /// usando dati macchina in cache per evitare lookup ridondanti /// /// @@ -4543,7 +4573,7 @@ namespace MP.IOC.Data } /// - /// Calcola l'effettivo valore da passare alla macchina a stati INGRESSI usando dati macchina in cache + /// Calcola l'effettivo valOut da passare alla macchina a stati INGRESSI usando dati macchina in cache /// /// /// @@ -4568,7 +4598,7 @@ namespace MP.IOC.Data // non usato (x ora) int.TryParse(datiMacc.ContainsKey("NumBit") ? datiMacc["NumBit"] : "0", out NumBit); - // recupero valore + // recupero valOut valINT = int.Parse(valore, NumberStyles.HexNumber); // filtro newValInt = MP.Core.Utils.bMaskInt(valINT, BitFilt); @@ -4626,7 +4656,8 @@ namespace MP.IOC.Data double numSecCache = redisLongTimeCache; // converto in formato dizionario... if (dbResult != null) - { // salvo 1:1 i valori... STATO + { + // salvo 1:1 i valori... STATO result.Add("IdxMicroStato", $"{dbResult.IdxMicroStato}"); result.Add("IdxStato", $"{dbResult.IdxStato}"); result.Add("CodArticolo", $"{dbResult.CodArticolo}"); @@ -4653,9 +4684,14 @@ namespace MP.IOC.Data result.Add("IdxFamMacc", $"{dbResult.IdxFamiglia}"); result.Add("simplePallet", $"{dbResult.SimplePallet}"); result.Add("palletChange", $"{dbResult.PalletChange}"); - // durata cache in secondi dal valore insEnabled... + // durata cache in secondi dal valOut insEnabled... //double numSecCache = ((result["insEnabled"].ToLower() == "true") ? redisShortTimeCache : redisLongTimeCache); numSecCache = dbResult.InsEnabled ? redisShortTimeCache : redisLongTimeCache; + } + else + { + + } // dati master/slave string isMaster = (await ListMasterAsync()).Contains(idxMacc) ? "1" : "0"; @@ -4708,8 +4744,8 @@ namespace MP.IOC.Data i++; } // verifico il timeout (default 60 sec...) - var sTOutSmi = tryGetConfig("TmOut.SMI").Result; - int tOut = 60; + int tOut = 300; + var sTOutSmi = await tryGetConfigAsync("TmOut.SMI"); if (!string.IsNullOrEmpty(sTOutSmi)) { int.TryParse(sTOutSmi, out tOut); @@ -4773,6 +4809,50 @@ namespace MP.IOC.Data return answ; } + /// + /// Scrive una riga evento + una riga microstato insieme, ed effettua verifica necessità cambio stato + /// + /// Record MicroStatoMacchina + /// record EventList + /// + private async Task scriviRigaEventoAsync(MicroStatoMacchinaModel newRecMsm, EventListModel newRecEv) + { + bool inserito = false; + if (useFactory) + { + await using var scope = _scopeFactory.CreateAsyncScope(); + var iocService = scope.ServiceProvider.GetRequiredService(); + + // inserisco evento + inserito = await iocService.EvListMicroStatoInsertAsync(newRecMsm, newRecEv); + // faccio controllo per eventuale cambio stato da tab transizioni... + + await iocService.CheckCambiaStatoBatchAsync(tipoInputEvento.hw, newRecEv.IdxMacchina, newRecEv.InizioStato ?? DateTime.Now, newRecEv.IdxTipo, newRecEv.CodArticolo, newRecEv.Value, newRecEv.MatrOpr, newRecEv.pallet); + } + else + { + + try + { + // inserisco evento + inserito = await IocDbController.EvListMicroStatoInsertAsync(newRecMsm, newRecEv); + // faccio controllo per eventuale cambio stato da tab transizioni... + await CheckCambiaStatoBatchAsync(tipoInputEvento.hw, newRecEv.IdxMacchina, newRecEv.InizioStato ?? DateTime.Now, newRecEv.IdxTipo, newRecEv.CodArticolo, newRecEv.Value, newRecEv.MatrOpr, newRecEv.pallet); + } + catch (Exception exc) + { + Log.Error($"Errore in scriviRigaEvento | IdxMacchina {newRecEv.IdxMacchina} | IdxTipo {newRecEv.IdxTipo} | codArticolo {newRecEv.CodArticolo} | Value {newRecEv.Value} | MatrOpr {newRecEv.MatrOpr} | Pallet {newRecEv.pallet} | dTime {newRecEv.InizioStato}{Environment.NewLine}{exc}"); + } + } + // formatto output + inputComandoMapo answ = new inputComandoMapo(); + answ.outValue = inserito.ToString(); + answ.needStatusRefresh = true; + return answ; + } + + + /// /// Scrive una riga di evento manuale (barcode) nel db + check cambio stato DiarioDiBordo /// @@ -4833,11 +4913,11 @@ namespace MP.IOC.Data } /// - /// Restituisce valore della stringa (SE disponibile) + /// Restituisce valOut della stringa (SE disponibile) /// /// /// - private async Task tryGetConfig(string keyName) + private async Task tryGetConfigAsync(string keyName) { string answ = ""; // preselezione valori @@ -4850,8 +4930,9 @@ namespace MP.IOC.Data return answ; } +#if false /// - /// Restituisce il valore SPECIFICATO per la state machine ingressi + /// Restituisce il valOut SPECIFICATO per la state machine ingressi /// value: iTipoEv_nState (IdxTipoEv da trasmettere + New MICRO-STATE) /// /// @@ -4862,8 +4943,9 @@ namespace MP.IOC.Data { var currHash = Utils.GetHashSMI(idxFamIn); string field = string.Format("{0}_{1}", idxMicroStato, valoreIn); - return RedisGetHashField(currHash, field); - } + return RedisGetHashFieldAsync(currHash, field); + } +#endif /// /// cerca codice in anagrafica macchine ed eventualmente inserisce nuova macchina diff --git a/MP.IOC/MP.IOC.csproj b/MP.IOC/MP.IOC.csproj index 594ff56b..028a2a46 100644 --- a/MP.IOC/MP.IOC.csproj +++ b/MP.IOC/MP.IOC.csproj @@ -4,7 +4,7 @@ net8.0 enable enable - 8.16.2604.2907 + 8.16.2604.3018 diff --git a/MP.IOC/Program.cs b/MP.IOC/Program.cs index e665ee1f..207578c7 100644 --- a/MP.IOC/Program.cs +++ b/MP.IOC/Program.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Http.Extensions; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.OpenApi.Models; using MP.Core.Conf; using MP.Data; @@ -62,6 +63,20 @@ builder.Services.Configure( builder.Configuration.GetSection("RedisScripts")); logger.Info("RedisScript Provider configured"); +// Metodi principali x accesso dati +var connStr = builder.Configuration.GetConnectionString("MP.Data") + ?? throw new InvalidOperationException("ConnString 'MP.Data' mancante."); + +builder.Services.AddDbContextFactory(options => + options.UseSqlServer(connStr) + .EnableSensitiveDataLogging(false) // true solo in Sviluppo + .ConfigureWarnings(w => w.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning))); + +// MP.Data DbContext for Stats repositories +string utilsConnString = builder.Configuration.GetConnectionString("MP.Utils") ?? "Server=localhost;Database=MoonPro_Utils; integrated security=True; MultipleActiveResultSets=True; App=MP.IOC;"; +builder.Services.AddDbContextFactory(options => + options.UseSqlServer(utilsConnString)); + // MP.Data Services Utils - Statistiche DB builder.Services.AddIocDataLayer(); @@ -79,10 +94,7 @@ builder.Services.AddRazorComponents() //builder.Services.AddHealthChecks() // .AddSqlServer(builder.Configuration.GetConnectionString("CoreDb")); -// MP.Data DbContext for Stats repositories -string utilsConnString = builder.Configuration.GetConnectionString("MP.Utils") ?? "Server=localhost;Database=MoonPro_Utils; integrated security=True; MultipleActiveResultSets=True; App=MP.IOC;"; -builder.Services.AddDbContextFactory(options => - options.UseSqlServer(utilsConnString)); + // generic controller builder.Services.AddControllers(); @@ -104,6 +116,7 @@ var redisMux = ConnectionMultiplexer.Connect(confRedis); builder.Services.AddSingleton(redisMux); // oggetto principale accesso dati +//builder.Services.AddScoped(); builder.Services.AddSingleton(); logger.Info("Standard service configured"); diff --git a/MP.IOC/Resources/ChangeLog.html b/MP.IOC/Resources/ChangeLog.html index 14683919..7d6890c5 100644 --- a/MP.IOC/Resources/ChangeLog.html +++ b/MP.IOC/Resources/ChangeLog.html @@ -1,6 +1,6 @@ Modulo MP-IOC -

Versione: 8.16.2604.2907

+

Versione: 8.16.2604.3018


Note di rilascio:
  • diff --git a/MP.IOC/Resources/VersNum.txt b/MP.IOC/Resources/VersNum.txt index 403fcf6f..ab00c4c9 100644 --- a/MP.IOC/Resources/VersNum.txt +++ b/MP.IOC/Resources/VersNum.txt @@ -1 +1 @@ -8.16.2604.2907 +8.16.2604.3018 diff --git a/MP.IOC/Resources/manifest.xml b/MP.IOC/Resources/manifest.xml index e0f943be..eb4e55e3 100644 --- a/MP.IOC/Resources/manifest.xml +++ b/MP.IOC/Resources/manifest.xml @@ -1,6 +1,6 @@ - 8.16.2604.2907 + 8.16.2604.3018 https://nexus.steamware.net/repository/SWS/MP-IOC/stable/LAST/MP.IOC.zip https://nexus.steamware.net/repository/SWS/MP-IOC/stable/LAST/ChangeLog.html false diff --git a/MP.IOC/appsettings.Development.json b/MP.IOC/appsettings.Development.json index 770d3e93..b9395333 100644 --- a/MP.IOC/appsettings.Development.json +++ b/MP.IOC/appsettings.Development.json @@ -2,7 +2,7 @@ "DetailedErrors": true, "Logging": { "LogLevel": { - "Default": "Information", + "Default": "Debug", "Microsoft.AspNetCore": "Warning" } } diff --git a/MP.IOC/appsettings.json b/MP.IOC/appsettings.json index d7c5727c..93bee530 100644 --- a/MP.IOC/appsettings.json +++ b/MP.IOC/appsettings.json @@ -1,7 +1,7 @@ { "Logging": { "LogLevel": { - "Default": "Information", + "Default": "Debug", "Microsoft.AspNetCore": "Warning", "Microsoft.EntityFrameworkCore.Database.Command": "Warning", "Microsoft.EntityFrameworkCore.Infrastructure": "Warning", diff --git a/MP.Stats/Data/MpStatsService.cs b/MP.Stats/Data/MpStatsService.cs index ea91785f..35c6cfbb 100644 --- a/MP.Stats/Data/MpStatsService.cs +++ b/MP.Stats/Data/MpStatsService.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Configuration; using MP.Data.DbModels; +using MP.Data.DbModels.Energy; using MP.Data.Services; using Newtonsoft.Json; using NLog; @@ -359,7 +360,7 @@ namespace MP.Stats.Data } else { - result = dbController.MacchineGetAll().ToList(); + result = dbController.MacchineGetAll(); // serializzp e salvo... rawData = JsonConvert.SerializeObject(result); _redisDb.StringSet(currKey, rawData, FastCache); @@ -373,6 +374,42 @@ namespace MP.Stats.Data return result; } + /// + /// Elenco check stato Macchine Energy + /// + /// + public async Task> MacchineEnergyCheckGetAll() + { + // setup parametri costanti + string source = "DB"; + Stopwatch sw = new Stopwatch(); + sw.Start(); + List result = new List(); + // cerco in redis... + DateTime adesso = DateTime.Now; + string currKey = $"{redisBaseKey}:Cache:MacchineEnegyCheck"; + RedisValue rawData = await _redisDb.StringGetAsync(currKey); + if (rawData.HasValue) + { + result = JsonConvert.DeserializeObject>($"{rawData}"); + source = "REDIS"; + } + else + { + result = await dbController.MacchineEnergyCheckGetAllAsync(); + // serializzp e salvo... + rawData = JsonConvert.SerializeObject(result); + await _redisDb.StringSetAsync(currKey, rawData, FastCache); + } + if (result == null) + { + result = new List(); + } + sw.Stop(); + Log.Debug($"MacchineEnergyCheckGetAllAsync | {source} | {sw.Elapsed.TotalMilliseconds}ms"); + return result; + } + public Task> MachineList(bool onlyEnergy = false) { List answ = new List(); diff --git a/MP.Stats/MP.Stats.csproj b/MP.Stats/MP.Stats.csproj index 369aafad..f55ebae2 100644 --- a/MP.Stats/MP.Stats.csproj +++ b/MP.Stats/MP.Stats.csproj @@ -4,7 +4,7 @@ net8.0 MP.Stats 826e877c-ba70-4253-84cb-d0b1cafd4440 - 8.16.2604.2718 + 8.16.2605.0409 true en diff --git a/MP.Stats/Pages/StatusChecks.razor b/MP.Stats/Pages/StatusChecks.razor new file mode 100644 index 00000000..1aee7299 --- /dev/null +++ b/MP.Stats/Pages/StatusChecks.razor @@ -0,0 +1,47 @@ +@page "/StatusChecks" + + +
    +
    +
    + Status Checks +
    +
    +
    + Scdenza (minuti) + +
    +
    +
    +
    + + + + + + + + + + + + + + @foreach (var record in ListPaged) + { + + + + + + + + + } + +
    IdxMacchinadescrFluxLast EventValore
    @record.IdxMacchina@record.Nome@record.Descrizione@record.CodFlux@record.dtEvento@record.Valore
    +
    + +
    diff --git a/MP.Stats/Pages/StatusChecks.razor.cs b/MP.Stats/Pages/StatusChecks.razor.cs new file mode 100644 index 00000000..1b44db4b --- /dev/null +++ b/MP.Stats/Pages/StatusChecks.razor.cs @@ -0,0 +1,108 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Configuration; +using MP.Data.DbModels.Energy; +using MP.Stats.Data; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace MP.Stats.Pages +{ + public partial class StatusChecks + { + #region Protected Properties + + [Inject] + protected IConfiguration ConfMan { get; set; } = null!; + + [Inject] + protected MpStatsService StatService { get; set; } = null!; + + #endregion Protected Properties + + #region Protected Methods + + protected override void OnInitialized() + { + timeoutMin = ConfMan.GetValue("SpecialConf:TimeoutEnergyFlux"); + } + + protected override async Task OnParametersSetAsync() + { + await ReloadDataAsync(); + UpdateTable(); + } + + #endregion Protected Methods + + #region Private Fields + + private List AllRecord = new(); + + private List ListPaged = new(); + + private int numRecPage = 10; + + private int pageNum = 1; + + private int timeoutMin = 30; + private int totalCount = 0; + + #endregion Private Fields + + #region Private Methods + + /// + /// Scadute se evento > 5 minuti + /// + /// + /// + private string CheckScadute(MacchineEnergyCheckModel item) + { + DateTime adesso = DateTime.Now; + var dataAge = adesso.Subtract(item.dtEvento).TotalMinutes; + string status = ""; + // se supero limite + if (dataAge >= timeoutMin) + { + // se doppio del limite danger sennò warning... + status = dataAge <= 2 * timeoutMin ? "table-warning" : "table-danger"; + } + return status; + } + + private async Task ReloadDataAsync() + { + AllRecord = await StatService.MacchineEnergyCheckGetAll(); + totalCount = AllRecord.Count; + } + + private void SaveNumRec(int newNum) + { + numRecPage = newNum; + UpdateTable(); + } + + private void SavePage(int newNum) + { + pageNum = newNum; + UpdateTable(); + } + + private void UpdateTable() + { + // esegue paginazione + if (totalCount > numRecPage) + { + ListPaged = AllRecord.Skip((pageNum - 1) * numRecPage).Take(numRecPage).ToList(); + } + else + { + ListPaged = AllRecord; + } + } + + #endregion Private Methods + } +} \ No newline at end of file diff --git a/MP.Stats/Resources/ChangeLog.html b/MP.Stats/Resources/ChangeLog.html index 8b3918eb..5a3ceecc 100644 --- a/MP.Stats/Resources/ChangeLog.html +++ b/MP.Stats/Resources/ChangeLog.html @@ -1,6 +1,6 @@ Modulo statistiche MAPO -

    Versione: 8.16.2604.2718

    +

    Versione: 8.16.2605.0409


    Note di rilascio:
      diff --git a/MP.Stats/Resources/VersNum.txt b/MP.Stats/Resources/VersNum.txt index 87ec763e..8cdf9194 100644 --- a/MP.Stats/Resources/VersNum.txt +++ b/MP.Stats/Resources/VersNum.txt @@ -1 +1 @@ -8.16.2604.2718 +8.16.2605.0409 diff --git a/MP.Stats/Resources/manifest.xml b/MP.Stats/Resources/manifest.xml index 8d4f2844..bbf1a5bd 100644 --- a/MP.Stats/Resources/manifest.xml +++ b/MP.Stats/Resources/manifest.xml @@ -1,6 +1,6 @@ - 8.16.2604.2718 + 8.16.2605.0409 https://nexus.steamware.net/repository/SWS/MP-STATS/stable/LAST/MP.Stats.zip https://nexus.steamware.net/repository/SWS/MP-STATS/stable/LAST/ChangeLog.html false diff --git a/MP.Stats/Shared/NavMenu.razor b/MP.Stats/Shared/NavMenu.razor index 99ede02a..2e357d5b 100644 --- a/MP.Stats/Shared/NavMenu.razor +++ b/MP.Stats/Shared/NavMenu.razor @@ -16,7 +16,7 @@ diff --git a/MP.Stats/appsettings.json b/MP.Stats/appsettings.json index 213a8c54..0dc6bccb 100644 --- a/MP.Stats/appsettings.json +++ b/MP.Stats/appsettings.json @@ -61,6 +61,7 @@ "FormatDur": "HH:mm.ss.ff", "SpecialConf": { "AppUrl": "/MP/STATS", + "TimeoutEnergyFlux": 60, "TaskEnableRedis": false, "TaskManConn": "MP.Stats", "RedisBaseConf": "MP:TASK:STATS"