From 45cb6b9f596aad710fbcfcbbe6a2f55ce49ae8c9 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Tue, 7 Apr 2026 10:30:04 +0200 Subject: [PATCH] Fix integrazione preliminare servizi utils.stats x IOC: - aggiunta migrations - correzioni versione ef6 da ef8 - correzioni init varie --- MP.Data/Controllers/MpSpecController.cs | 11 +- .../DbModels/Utils/StatsAggregatedModel.cs | 18 +- MP.Data/DbModels/Utils/StatsDetailModel.cs | 14 +- .../20260407082127_InitDb.Designer.cs | 107 +++++ .../MoonPro_Utils/20260407082127_InitDb.cs | 73 ++++ .../MoonPro_UtilsContextModelSnapshot.cs | 105 +++++ MP.Data/MoonPro_UtilsContext.cs | 17 +- MP.Data/Repository/BaseRepository.cs | 47 +++ MP.Data/Repository/IBaseRepository.cs | 8 + .../Repository/Utils/IStatsAggrRepository.cs | 4 + .../Utils/IStatsDetailRepository.cs | 4 + .../Repository/Utils/StatsAggrRepository.cs | 19 +- .../Repository/Utils/StatsDetailRepository.cs | 27 +- MP.Data/Services/BaseServ.cs | 235 +++++++++-- MP.Data/Services/LandDataService.cs | 24 +- MP.Data/Services/ListSelectDataSrv.cs | 44 +- MP.Data/Services/MessageService.cs | 4 +- MP.Data/Services/OrderDataSrv.cs | 12 +- MP.Data/Services/SchedulerDataService.cs | 4 +- MP.Data/Services/StatusData.cs | 10 +- MP.Data/Services/TabDataService.cs | 392 +++++++++--------- MP.Data/Services/TranslateSrv.cs | 32 +- MP.Data/Services/Utils/IStatsAggrService.cs | 8 +- MP.Data/Services/Utils/IStatsDetailService.cs | 8 +- MP.Data/Services/Utils/StatsAggrService.cs | 11 +- MP.Data/Services/Utils/StatsDetailService.cs | 10 +- MP.IOC/Program.cs | 13 +- MP.IOC/Resources/ChangeLog.html | 2 +- MP.IOC/Resources/VersNum.txt | 2 +- MP.IOC/Resources/manifest.xml | 2 +- MP.IOC/Services/BaseServ.cs | 372 +++++++++++++++++ MP.IOC/Services/MetricsDbFlushService.cs | 13 +- 32 files changed, 1290 insertions(+), 362 deletions(-) create mode 100644 MP.Data/Migrations/MoonPro_Utils/20260407082127_InitDb.Designer.cs create mode 100644 MP.Data/Migrations/MoonPro_Utils/20260407082127_InitDb.cs create mode 100644 MP.Data/Migrations/MoonPro_Utils/MoonPro_UtilsContextModelSnapshot.cs create mode 100644 MP.Data/Repository/BaseRepository.cs create mode 100644 MP.Data/Repository/IBaseRepository.cs create mode 100644 MP.IOC/Services/BaseServ.cs diff --git a/MP.Data/Controllers/MpSpecController.cs b/MP.Data/Controllers/MpSpecController.cs index 396a1a2a..c8fa8412 100644 --- a/MP.Data/Controllers/MpSpecController.cs +++ b/MP.Data/Controllers/MpSpecController.cs @@ -4,19 +4,14 @@ using Microsoft.Extensions.Configuration; using MP.Core.DTO; using MP.Core.Objects; using MP.Data.DbModels; -using MP.Data.DTO; -using MP.Data.Translate; using NLog; -using Org.BouncyCastle.Crypto; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; -using ZXing; using static EgwCoreLib.Utils.DtUtils; -using static MP.Core.Objects.Enums; namespace MP.Data.Controllers { @@ -531,7 +526,7 @@ namespace MP.Data.Controllers } return fatto; } - + /// /// Elenco da tabella Config /// @@ -682,7 +677,7 @@ namespace MP.Data.Controllers } /// - /// Effettua salvataggio snapshot parametri (con stored) + svuota eventuale cache redisConn + /// Effettua salvataggio snapshot parametri (con stored) + svuota eventuale cache _redisConn /// /// macchina /// Num massimo secondi per recuperare dati correnti @@ -705,7 +700,7 @@ namespace MP.Data.Controllers } /// - /// Effettua salvataggio snapshot parametri (con stored) + svuota eventuale cache redisConn + /// Effettua salvataggio snapshot parametri (con stored) + svuota eventuale cache _redisConn /// /// macchina /// Data min x selezione diff --git a/MP.Data/DbModels/Utils/StatsAggregatedModel.cs b/MP.Data/DbModels/Utils/StatsAggregatedModel.cs index 4221288b..aa64a2ff 100644 --- a/MP.Data/DbModels/Utils/StatsAggregatedModel.cs +++ b/MP.Data/DbModels/Utils/StatsAggregatedModel.cs @@ -1,4 +1,8 @@ -// +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +// // This is here so CodeMaid doesn't reorganize this document // namespace MP.Data.DbModels.Utils @@ -24,17 +28,9 @@ namespace MP.Data.DbModels.Utils /// public double AvgDuration { get; set; } = 0; /// - /// Durata massima esecuzione + /// Durata minima esecuzione /// - public double MaxDuration { get; set; } = 0; - /// - /// Durata 5 perc esecuzione - /// - public double Perc05Duration { get; set; } = 0; - /// - /// Durata 95 perc esecuzione - /// - public double Perc95Duration { get; set; } = 0; + public double MinDuration { get; set; } = 0; /// /// Durata massima esecuzione /// diff --git a/MP.Data/DbModels/Utils/StatsDetailModel.cs b/MP.Data/DbModels/Utils/StatsDetailModel.cs index 0aa9b4a1..34ba8010 100644 --- a/MP.Data/DbModels/Utils/StatsDetailModel.cs +++ b/MP.Data/DbModels/Utils/StatsDetailModel.cs @@ -1,4 +1,8 @@ -// +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +// // This is here so CodeMaid doesn't reorganize this document // namespace MP.Data.DbModels.Utils @@ -32,13 +36,9 @@ namespace MP.Data.DbModels.Utils /// public double AvgDuration { get; set; } = 0; /// - /// Durata 5 perc esecuzione + /// Durata minima esecuzione /// - public double Perc05Duration { get; set; } = 0; - /// - /// Durata 95 perc esecuzione - /// - public double Perc95Duration { get; set; } = 0; + public double MinDuration { get; set; } = 0; /// /// Durata massima esecuzione /// diff --git a/MP.Data/Migrations/MoonPro_Utils/20260407082127_InitDb.Designer.cs b/MP.Data/Migrations/MoonPro_Utils/20260407082127_InitDb.Designer.cs new file mode 100644 index 00000000..4e8df143 --- /dev/null +++ b/MP.Data/Migrations/MoonPro_Utils/20260407082127_InitDb.Designer.cs @@ -0,0 +1,107 @@ +// +using System; +using MP.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace MP.Data.Migrations.MoonPro_Utils +{ + [DbContext(typeof(MoonPro_UtilsContext))] + [Migration("20260407082127_InitDb")] + partial class InitDb + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .UseCollation("SQL_Latin1_General_CP1_CI_AS") + .HasAnnotation("ProductVersion", "6.0.36") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); + + modelBuilder.Entity("MP.Data.DbModels.Utils.StatsAggregatedModel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("AvgDuration") + .HasColumnType("float"); + + b.Property("Hour") + .HasColumnType("datetime2"); + + b.Property("MaxDuration") + .HasColumnType("float"); + + b.Property("MinDuration") + .HasColumnType("float"); + + b.Property("NoReply") + .HasColumnType("bigint"); + + b.Property("RequestCount") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("Hour") + .IsUnique() + .HasDatabaseName("idx_statsaggr_hour"); + + b.ToTable("stats_aggr"); + }); + + modelBuilder.Entity("MP.Data.DbModels.Utils.StatsDetailModel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("AvgDuration") + .HasColumnType("float"); + + b.Property("Environment") + .HasColumnType("nvarchar(450)"); + + b.Property("Hour") + .HasColumnType("datetime2"); + + b.Property("MaxDuration") + .HasColumnType("float"); + + b.Property("MinDuration") + .HasColumnType("float"); + + b.Property("NoReply") + .HasColumnType("bigint"); + + b.Property("RequestCount") + .HasColumnType("bigint"); + + b.Property("Type") + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Hour", "Environment", "Type") + .IsUnique() + .HasDatabaseName("idx_statsdet_hour_env_type") + .HasFilter("[Environment] IS NOT NULL AND [Type] IS NOT NULL"); + + b.ToTable("stats_detail"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/MP.Data/Migrations/MoonPro_Utils/20260407082127_InitDb.cs b/MP.Data/Migrations/MoonPro_Utils/20260407082127_InitDb.cs new file mode 100644 index 00000000..1908fd13 --- /dev/null +++ b/MP.Data/Migrations/MoonPro_Utils/20260407082127_InitDb.cs @@ -0,0 +1,73 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace MP.Data.Migrations.MoonPro_Utils +{ + public partial class InitDb : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "stats_aggr", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Hour = table.Column(type: "datetime2", nullable: false), + RequestCount = table.Column(type: "bigint", nullable: false), + AvgDuration = table.Column(type: "float", nullable: false), + MinDuration = table.Column(type: "float", nullable: false), + MaxDuration = table.Column(type: "float", nullable: false), + NoReply = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_stats_aggr", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "stats_detail", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Environment = table.Column(type: "nvarchar(450)", nullable: true), + Type = table.Column(type: "nvarchar(450)", nullable: true), + Hour = table.Column(type: "datetime2", nullable: false), + RequestCount = table.Column(type: "bigint", nullable: false), + AvgDuration = table.Column(type: "float", nullable: false), + MinDuration = table.Column(type: "float", nullable: false), + MaxDuration = table.Column(type: "float", nullable: false), + NoReply = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_stats_detail", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "idx_statsaggr_hour", + table: "stats_aggr", + column: "Hour", + unique: true); + + migrationBuilder.CreateIndex( + name: "idx_statsdet_hour_env_type", + table: "stats_detail", + columns: new[] { "Hour", "Environment", "Type" }, + unique: true, + filter: "[Environment] IS NOT NULL AND [Type] IS NOT NULL"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "stats_aggr"); + + migrationBuilder.DropTable( + name: "stats_detail"); + } + } +} diff --git a/MP.Data/Migrations/MoonPro_Utils/MoonPro_UtilsContextModelSnapshot.cs b/MP.Data/Migrations/MoonPro_Utils/MoonPro_UtilsContextModelSnapshot.cs new file mode 100644 index 00000000..cba5e513 --- /dev/null +++ b/MP.Data/Migrations/MoonPro_Utils/MoonPro_UtilsContextModelSnapshot.cs @@ -0,0 +1,105 @@ +// +using System; +using MP.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace MP.Data.Migrations.MoonPro_Utils +{ + [DbContext(typeof(MoonPro_UtilsContext))] + partial class MoonPro_UtilsContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .UseCollation("SQL_Latin1_General_CP1_CI_AS") + .HasAnnotation("ProductVersion", "6.0.36") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); + + modelBuilder.Entity("MP.Data.DbModels.Utils.StatsAggregatedModel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("AvgDuration") + .HasColumnType("float"); + + b.Property("Hour") + .HasColumnType("datetime2"); + + b.Property("MaxDuration") + .HasColumnType("float"); + + b.Property("MinDuration") + .HasColumnType("float"); + + b.Property("NoReply") + .HasColumnType("bigint"); + + b.Property("RequestCount") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("Hour") + .IsUnique() + .HasDatabaseName("idx_statsaggr_hour"); + + b.ToTable("stats_aggr"); + }); + + modelBuilder.Entity("MP.Data.DbModels.Utils.StatsDetailModel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("AvgDuration") + .HasColumnType("float"); + + b.Property("Environment") + .HasColumnType("nvarchar(450)"); + + b.Property("Hour") + .HasColumnType("datetime2"); + + b.Property("MaxDuration") + .HasColumnType("float"); + + b.Property("MinDuration") + .HasColumnType("float"); + + b.Property("NoReply") + .HasColumnType("bigint"); + + b.Property("RequestCount") + .HasColumnType("bigint"); + + b.Property("Type") + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Hour", "Environment", "Type") + .IsUnique() + .HasDatabaseName("idx_statsdet_hour_env_type") + .HasFilter("[Environment] IS NOT NULL AND [Type] IS NOT NULL"); + + b.ToTable("stats_detail"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/MP.Data/MoonPro_UtilsContext.cs b/MP.Data/MoonPro_UtilsContext.cs index b87aad6c..5220a4e3 100644 --- a/MP.Data/MoonPro_UtilsContext.cs +++ b/MP.Data/MoonPro_UtilsContext.cs @@ -1,11 +1,8 @@ -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; -using MP.Core.DTO; -using MP.Data.DbModels; -using MP.Data.DTO; +using MP.Data.DbModels.Utils; using NLog; +using System; #nullable disable // @@ -34,10 +31,10 @@ namespace MP.Data { } - public MoonPro_UtilsContext(IConfiguration configuration) - { - _configuration = configuration; - } + //public MoonPro_UtilsContext(IConfiguration configuration) + //{ + // _configuration = configuration; + //} public MoonPro_UtilsContext(DbContextOptions options) : base(options) { diff --git a/MP.Data/Repository/BaseRepository.cs b/MP.Data/Repository/BaseRepository.cs new file mode 100644 index 00000000..4c20bcf4 --- /dev/null +++ b/MP.Data/Repository/BaseRepository.cs @@ -0,0 +1,47 @@ +using Microsoft.EntityFrameworkCore; +using System.Threading.Tasks; + +namespace MP.Data.Repository +{ + 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(); + +#if false + /// + /// Salvataggio dati asincrono + /// + /// + protected async Task SaveChangesAsync(DataLayerContext ctx) + => await ctx.SaveChangesAsync() > 0; +#endif + + #endregion Protected Methods + +#if false + protected readonly DataLayerContext _dbCtx; + protected BaseRepository(DataLayerContext db) => _dbCtx = db; + public async Task SaveChangesAsync() => await _dbCtx.SaveChangesAsync() > 0; +#endif + } +} diff --git a/MP.Data/Repository/IBaseRepository.cs b/MP.Data/Repository/IBaseRepository.cs new file mode 100644 index 00000000..6e63d664 --- /dev/null +++ b/MP.Data/Repository/IBaseRepository.cs @@ -0,0 +1,8 @@ +namespace MP.Data.Repository +{ + public interface IBaseRepository + { + //Task CreateContextAsync(); + //Task SaveChangesAsync(DataLayerContext ctx); + } +} diff --git a/MP.Data/Repository/Utils/IStatsAggrRepository.cs b/MP.Data/Repository/Utils/IStatsAggrRepository.cs index 5f2bf909..e45014f0 100644 --- a/MP.Data/Repository/Utils/IStatsAggrRepository.cs +++ b/MP.Data/Repository/Utils/IStatsAggrRepository.cs @@ -1,4 +1,8 @@ using EgwCoreLib.Utils; +using MP.Data.DbModels.Utils; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace MP.Data.Repository.Utils { diff --git a/MP.Data/Repository/Utils/IStatsDetailRepository.cs b/MP.Data/Repository/Utils/IStatsDetailRepository.cs index 3db2182c..77bd329a 100644 --- a/MP.Data/Repository/Utils/IStatsDetailRepository.cs +++ b/MP.Data/Repository/Utils/IStatsDetailRepository.cs @@ -1,4 +1,8 @@ using EgwCoreLib.Utils; +using MP.Data.DbModels.Utils; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace MP.Data.Repository.Utils { diff --git a/MP.Data/Repository/Utils/StatsAggrRepository.cs b/MP.Data/Repository/Utils/StatsAggrRepository.cs index 2f9e6657..8867c657 100644 --- a/MP.Data/Repository/Utils/StatsAggrRepository.cs +++ b/MP.Data/Repository/Utils/StatsAggrRepository.cs @@ -1,4 +1,10 @@ using EgwCoreLib.Utils; +using Microsoft.EntityFrameworkCore; +using MP.Data.DbModels.Utils; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; namespace MP.Data.Repository.Utils { @@ -6,7 +12,7 @@ namespace MP.Data.Repository.Utils { #region Public Constructors - public StatsAggrRepository(IDbContextFactory ctxFactory) : base(ctxFactory) + public StatsAggrRepository(IDbContextFactory ctxFactory) : base(ctxFactory) { } @@ -58,11 +64,20 @@ namespace MP.Data.Repository.Utils { DateTime startDate = firstRec.Hour; DateTime endDate = lastRec.Hour; - // uso direttamente ExecuteDelete + + // uso direttamente ExecuteDelete quando in EFCore8... +#if false await dbCtx .DbSetStatsAggr .Where(x => x.Hour >= startDate && x.Hour <= endDate) .ExecuteDeleteAsync(); +#endif + var items = await dbCtx.DbSetStatsAggr + .Where(x => x.Hour >= startDate && x.Hour <= endDate) + .ToListAsync(); + + dbCtx.DbSetStatsAggr.RemoveRange(items); + await dbCtx.SaveChangesAsync(); } } diff --git a/MP.Data/Repository/Utils/StatsDetailRepository.cs b/MP.Data/Repository/Utils/StatsDetailRepository.cs index 4b09d801..63f9f0aa 100644 --- a/MP.Data/Repository/Utils/StatsDetailRepository.cs +++ b/MP.Data/Repository/Utils/StatsDetailRepository.cs @@ -1,4 +1,10 @@ using EgwCoreLib.Utils; +using Microsoft.EntityFrameworkCore; +using MP.Data.DbModels.Utils; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; namespace MP.Data.Repository.Utils { @@ -6,7 +12,7 @@ namespace MP.Data.Repository.Utils { #region Public Constructors - public StatsDetailRepository(IDbContextFactory ctxFactory) : base(ctxFactory) + public StatsDetailRepository(IDbContextFactory ctxFactory) : base(ctxFactory) { } @@ -79,11 +85,20 @@ namespace MP.Data.Repository.Utils { DateTime startDate = firstRec.Hour; DateTime endDate = lastRec.Hour; - // uso direttamente ExecuteDelete - await dbCtx - .DbSetStatsDet - .Where(x => x.Hour >= startDate && x.Hour <= endDate) - .ExecuteDeleteAsync(); + + // uso direttamente ExecuteDelete quando in EFCore8... +#if false + await dbCtx + .DbSetStatsDet + .Where(x => x.Hour >= startDate && x.Hour <= endDate) + .ExecuteDeleteAsync(); +#endif + var items = await dbCtx.DbSetStatsDet + .Where(x => x.Hour >= startDate && x.Hour <= endDate) + .ToListAsync(); + + dbCtx.DbSetStatsDet.RemoveRange(items); + await dbCtx.SaveChangesAsync(); } } diff --git a/MP.Data/Services/BaseServ.cs b/MP.Data/Services/BaseServ.cs index db80844c..51355686 100644 --- a/MP.Data/Services/BaseServ.cs +++ b/MP.Data/Services/BaseServ.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Options; using MP.Core.Objects; using Newtonsoft.Json; using NLog; @@ -8,7 +7,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Text; +using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace MP.Data.Services @@ -16,39 +15,20 @@ namespace MP.Data.Services /// /// Classe di partenza x costruzione servizi di accesso dati + cache /// - public class BaseServ:IDisposable + public class BaseServ : IDisposable { - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - private bool _disposed = false; - protected virtual void Dispose(bool disposing) - { - if (!_disposed) - { - if (disposing) - { - // Free managed resources here - redisDb = null; - } - - // Free unmanaged resources here - _disposed = true; - } - } - - #region Public Constructors public BaseServ(IConfiguration configuration, IConnectionMultiplexer redConn) { _configuration = configuration; + // Verifica conf trace... + _traceEnabled = _configuration.GetValue("Otel:EnableTracing", false); + // setup componenti REDIS - this.redisConn = redConn; - redisDb = redisConn.GetDatabase(); + _redisConn = redConn; + _redisDb = _redisConn.GetDatabase(); // json serializer... FIX errore loop circolare https://www.ryadel.com/en/jsonserializationexception-self-referencing-loop-detected-error-fix-entity-framework-asp-net-core/ JSSettings = new JsonSerializerSettings() @@ -64,6 +44,12 @@ namespace MP.Data.Services #region Public Methods + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + /// /// Recupero info IOB x TAB (da info registrate IOB-WIN--> MP-IO) /// @@ -75,9 +61,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); IOB_data? result = new IOB_data(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = RedHashMpIO($"hM2IOB:{IdxMacchina}"); - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -87,7 +73,7 @@ namespace MP.Data.Services else { Log.Error($"Errore: non trovato valore valido in REDIS | key: {currKey}"); - Log.Info($"REDIS | conf: {redisConn.Configuration}"); + Log.Info($"REDIS | conf: {_redisConn.Configuration}"); Log.Info($" --> Valore trovato:{Environment.NewLine}{rawData}"); } if (result == null) @@ -111,11 +97,11 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); Dictionary result = new Dictionary(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = RedHashMpIO($"IOB:{IdxMacchina}:MachIobConf"); try { - result = redisDb + result = _redisDb .HashGetAll(currKey) .ToDictionary(x => $"{x.Name}", x => $"{x.Value}"); source = "REDIS"; @@ -145,11 +131,11 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); string result = ""; - // cerco in redisConn... + // cerco in _redisConn... string currKey = RedHashMpIO($"IOB:{IdxMacchina}:ConfYaml"); try { - result = redisDb.StringGet(currKey); + result = _redisDb.StringGet(currKey); source = "REDIS"; } catch (Exception exc) @@ -170,20 +156,31 @@ namespace MP.Data.Services #region Protected Fields + /// + /// Oggetto per collezione dati Activity (span in Uptrace) + /// + protected static readonly ActivitySource ActivitySource = new ActivitySource("MP.IOC"); + protected static IConfiguration _configuration = null!; - protected JsonSerializerSettings? JSSettings; - protected string MpIoNS = ""; + + /// + /// Abilitazione operazioni tracing generiche + /// + protected readonly bool _traceEnabled = false; /// /// Oggetto per connessione a REDIS /// - protected IConnectionMultiplexer redisConn = null!; + protected IConnectionMultiplexer _redisConn = null!; - //ISubscriber sub = redisConn.GetSubscriber(); + //ISubscriber sub = _redisConn.GetSubscriber(); /// /// Oggetto DB redis da impiegare x chiamate R/W /// - protected IDatabase redisDb = null!; + protected IDatabase _redisDb = null!; + + protected JsonSerializerSettings? JSSettings; + protected string MpIoNS = ""; #endregion Protected Fields @@ -225,6 +222,128 @@ namespace MP.Data.Services #region Protected Methods + /// + /// Helper avvio attività per la funzione tracciata + /// + /// + /// + protected static Activity? StartActivity([CallerMemberName] string? methodName = null) + { + var activity = ActivitySource.StartActivity(methodName ?? "UNDEF"); + activity?.SetTag("host.name", Environment.MachineName); + return activity; + } + + /// + /// Invalida una o più chiavi/pattern in Redis + /// + protected async Task ClearCacheAsync(params string[] patterns) + { + foreach (var pattern in patterns) + { + // Chiamata al tuo metodo esistente + await ExecFlushRedisPatternAsync((RedisValue)pattern); + } + } + + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + // Free managed resources here + _redisDb = null; + } + + // Free unmanaged resources here + _disposed = true; + } + } + + /// + /// Metodo di flush dati cache Redis + /// + /// + /// + protected async Task ExecFlushRedisPatternAsync(RedisValue pattern) + { + // Qui inserisci la tua logica attuale (es. via Lua script o Keys/Scan) + // Esempio rapido via server scan: + var endpoints = _redisConn.GetEndPoints(); + foreach (var endpoint in endpoints) + { + var server = _redisConn.GetServer(endpoint); + await foreach (var key in server.KeysAsync(_redisDb.Database, pattern)) + { + await _redisDb.KeyDeleteAsync(key); + } + } + } + + /// + /// Helper generale di lettura da cache o da funzione (DB) con caching successivo + /// + /// + /// + /// + /// + /// + protected async Task GetOrSetCacheAsync(string key, Func> factory, TimeSpan? expiration = null, [CallerMemberName] string? caller = null) + { + using var activity = StartActivity(); + string source = "DB"; + + // 1. Provo Redis + var cached = await _redisDb.StringGetAsync(key); + if (cached.HasValue) + { + source = "REDIS"; + var cachedResult = JsonConvert.DeserializeObject(cached!)!; + + activity?.SetTag("data.source", source); + LogTrace($"{source} | trace: {activity?.TraceId} | {activity?.Duration.TotalMilliseconds}ms", NLog.LogLevel.Trace, caller); + + return cachedResult; + } + + // 2. Chiamo il factory (DB) + T result = await factory(); + + if (result != null) + { + // 3. Salva in Redis per la prossima volta + var serialized = JsonConvert.SerializeObject(result, JSSettings); + await _redisDb.StringSetAsync(key, serialized, expiration ?? LongCache); + } + + // sistemo activity tracking data + activity?.SetTag("data.source", source); + activity?.Stop(); + + // log in console + LogTrace($"GetOrSetCacheAsync | {source} | trace: {activity?.TraceId} | {activity?.Duration.TotalMilliseconds:N3}ms", NLog.LogLevel.Trace, caller); + + return result!; + } + + /// + /// Helper trace messaggio log (SE abilitato) + /// + /// + /// + /// + protected void LogTrace(string traceMsg, NLog.LogLevel? reqLevel = null, [CallerMemberName] string? methodName = null) + { + if (!_traceEnabled) + return; + + reqLevel ??= NLog.LogLevel.Debug; + + // Loggo! + Log.Log(reqLevel, $"{methodName} | {traceMsg}"); + } + protected string RedHashMpIO(string keyName) { string result = keyName; @@ -240,11 +359,44 @@ namespace MP.Data.Services return result; } + /// + /// Helper generale per la telemetria e gestione eccezioni + /// + /// + /// + /// + /// + /// + protected async Task TraceAsync(string name, Func> body, object? parameters = null) + { + using var activity = ActivitySource.StartActivity(name); + try + { + if (parameters != null) + { + activity?.SetTag("params", JsonConvert.SerializeObject(parameters)); + } + var result = await body(activity); + activity?.SetStatus(ActivityStatusCode.Ok); + activity?.Stop(); + LogTrace($"TraceAsync | trace: {activity?.TraceId} | {activity?.Duration.TotalMilliseconds}ms", methodName: name); + return result; + } + catch (Exception ex) + { + activity?.SetStatus(ActivityStatusCode.Error, ex.Message); + //Log.Error(ex, "Errore in {MethodName}", name); + LogTrace($"Errore in {name}", NLog.LogLevel.Error, name); + throw; // Riesponi l'eccezione per il tracking globale + } + } + #endregion Protected Methods #region Private Fields private static Logger Log = LogManager.GetCurrentClassLogger(); + private bool _disposed = false; /// /// Durata cache lunga IN SECONDI @@ -258,6 +410,11 @@ namespace MP.Data.Services private Random rnd = new Random(); + /// + /// Path base chiavi REDIS + /// + protected readonly string _redisBaseKey = "MP:IOC"; + #endregion Private Fields } } \ No newline at end of file diff --git a/MP.Data/Services/LandDataService.cs b/MP.Data/Services/LandDataService.cs index 00588e84..8607bf6a 100644 --- a/MP.Data/Services/LandDataService.cs +++ b/MP.Data/Services/LandDataService.cs @@ -59,9 +59,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:DbInfo:ALL"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -72,7 +72,7 @@ namespace MP.Data.Services result = dbController.AllDbInfo(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraFastCache); + _redisDb.StringSet(currKey, rawData, UltraFastCache); } if (result == null) { @@ -95,7 +95,7 @@ namespace MP.Data.Services string currKey = $"{redisBaseKey}:IobList"; Stopwatch sw = new Stopwatch(); sw.Start(); - string? rawData = redisDb.StringGet(currKey); + string? rawData = _redisDb.StringGet(currKey); if (!string.IsNullOrEmpty(rawData) && rawData.Length > 2) { source = "REDIS"; @@ -123,9 +123,9 @@ namespace MP.Data.Services //ordino x idxmacchina... dbResult = dbResult.OrderBy(x => x.IdxMacchina).ToList(); - // serializzo in cache redisConn + // serializzo in cache _redisConn rawData = JsonConvert.SerializeObject(dbResult, JSSettings); - redisDb.StringSet(currKey, rawData, UltraLongCache); + _redisDb.StringSet(currKey, rawData, UltraLongCache); } if (dbResult == null) { @@ -147,9 +147,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:RemRebLog:ALL"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -161,7 +161,7 @@ namespace MP.Data.Services result = dbController.RemRebootLogGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraFastCache); + _redisDb.StringSet(currKey, rawData, UltraFastCache); } if (result == null) { @@ -183,9 +183,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:RemRebLog:LAST"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -197,7 +197,7 @@ namespace MP.Data.Services result = dbController.RemRebootLogGetLast(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraFastCache); + _redisDb.StringSet(currKey, rawData, UltraFastCache); } if (result == null) { diff --git a/MP.Data/Services/ListSelectDataSrv.cs b/MP.Data/Services/ListSelectDataSrv.cs index 68fb649d..2a9560a4 100644 --- a/MP.Data/Services/ListSelectDataSrv.cs +++ b/MP.Data/Services/ListSelectDataSrv.cs @@ -63,9 +63,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Art:{azienda}:{searchVal}:{numRecord}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -79,7 +79,7 @@ namespace MP.Data.Services #endif // serializzp e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -100,9 +100,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Conf"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -113,7 +113,7 @@ namespace MP.Data.Services result = dbController.ConfigGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, LongCache); + _redisDb.StringSet(currKey, rawData, LongCache); } if (result == null) { @@ -156,9 +156,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Menu:ALL"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -169,7 +169,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbController.ListLinkAll()); // serializzp e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraLongCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraLongCache); } if (result == null) { @@ -191,9 +191,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Menu:{tipoLink}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -205,7 +205,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbController.ListLinkFilt(tipoLink)); // serializzp e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraLongCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraLongCache); } if (result == null) { @@ -227,9 +227,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Macc:{MatrOpr}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -241,7 +241,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbController.MacchineByMatrOper(MatrOpr)); // serializzp e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraLongCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraLongCache); } if (result == null) { @@ -287,31 +287,31 @@ namespace MP.Data.Services #region Private Methods /// - /// Esegue flush memoria redisConn dato pat2Flush + /// Esegue flush memoria _redisConn dato pat2Flush /// /// /// private async Task ExecFlushRedisPattern(RedisValue pat2Flush) { bool answ = false; - var masterEndpoint = redisConn.GetEndPoints() - .Where(ep => redisConn.GetServer(ep).IsConnected && !redisConn.GetServer(ep).IsReplica) + var masterEndpoint = _redisConn.GetEndPoints() + .Where(ep => _redisConn.GetServer(ep).IsConnected && !_redisConn.GetServer(ep).IsReplica) .FirstOrDefault(); // sepattern è "*" elimino intero DB... if (masterEndpoint != null && (pat2Flush.Equals(new RedisValue("*")) || pat2Flush == RedisValue.Null)) { - redisConn.GetServer(masterEndpoint).FlushDatabase(database: redisDb.Database); + _redisConn.GetServer(masterEndpoint).FlushDatabase(database: _redisDb.Database); } else { - var server = redisConn.GetServer(masterEndpoint); - var keys = server.Keys(database: redisDb.Database, pattern: pat2Flush, pageSize: 1000); + var server = _redisConn.GetServer(masterEndpoint); + var keys = server.Keys(database: _redisDb.Database, pattern: pat2Flush, pageSize: 1000); var deleteTasks = new List(); foreach (var key in keys) { - deleteTasks.Add(redisDb.KeyDeleteAsync(key)); + deleteTasks.Add(_redisDb.KeyDeleteAsync(key)); if (deleteTasks.Count >= 1000) { await Task.WhenAll(deleteTasks); diff --git a/MP.Data/Services/MessageService.cs b/MP.Data/Services/MessageService.cs index d318a2ad..54d5b5e1 100644 --- a/MP.Data/Services/MessageService.cs +++ b/MP.Data/Services/MessageService.cs @@ -688,7 +688,7 @@ namespace MP.Data.Services protected IConnectionMultiplexer redisConn = null!; /// - /// Oggetto DB redisConn da impiegare x chiamate R/W + /// Oggetto DB _redisConn da impiegare x chiamate R/W /// protected IDatabase redisDb = null!; @@ -745,7 +745,7 @@ namespace MP.Data.Services } /// - /// Recupero HashSet redisConn come Dictionary + /// Recupero HashSet _redisConn come Dictionary /// /// /// diff --git a/MP.Data/Services/OrderDataSrv.cs b/MP.Data/Services/OrderDataSrv.cs index 3461a60e..19a08304 100644 --- a/MP.Data/Services/OrderDataSrv.cs +++ b/MP.Data/Services/OrderDataSrv.cs @@ -60,9 +60,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Conf"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -74,7 +74,7 @@ namespace MP.Data.Services result = dbController.ConfigGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, LongCache); + _redisDb.StringSet(currKey, rawData, LongCache); } if (result == null) { @@ -103,9 +103,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:ODL:{IdxMacchina}:{CodArt}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -117,7 +117,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbController.ListODLFilt(inCorso, CodArt, keyRichPart, Reparto, IdxMacchina, startDate, endDate)); // serializzp e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { diff --git a/MP.Data/Services/SchedulerDataService.cs b/MP.Data/Services/SchedulerDataService.cs index b13adf9f..46bb8638 100644 --- a/MP.Data/Services/SchedulerDataService.cs +++ b/MP.Data/Services/SchedulerDataService.cs @@ -68,7 +68,7 @@ namespace MP.Data.Services //Dictionary>? result = null; //// cerco in redis... //string currKey = $"{redisBaseKey}:PlannerData:{dtStart:yyyyMMdd}:{dtEnd:yyyyMMdd}"; - //RedisValue rawData = await redisDb.StringGetAsync(currKey); + //RedisValue rawData = await _redisDb.StringGetAsync(currKey); ////if (!string.IsNullOrEmpty($"{rawData}")) //if (rawData.HasValue && rawData.Length() > 2) //{ @@ -80,7 +80,7 @@ namespace MP.Data.Services // result = dataSimController.PlannerGetEvents(dtStart, dtEnd); // // serializzo e salvo... // rawData = JsonConvert.SerializeObject(result); - // await redisDb.StringSetAsync(currKey, rawData, LongCache); + // await _redisDb.StringSetAsync(currKey, rawData, LongCache); //} //activity?.SetTag("data.source", source); //LogTrace($"{source} | trace: {activity?.TraceId} | {activity?.Duration.TotalMilliseconds}ms"); diff --git a/MP.Data/Services/StatusData.cs b/MP.Data/Services/StatusData.cs index 02d66bcc..7c86ac9c 100644 --- a/MP.Data/Services/StatusData.cs +++ b/MP.Data/Services/StatusData.cs @@ -91,7 +91,7 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Conf"; RedisValue rawData = await redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) @@ -176,7 +176,7 @@ namespace MP.Data.Services string source = "DB"; sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{Constants.redisMacchine}:ALL"; RedisValue rawData = redisDb.StringGet(currKey); if (rawData.HasValue) @@ -207,7 +207,7 @@ namespace MP.Data.Services string source = "DB"; sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{Constants.redisMacchine}:{CodGruppo}"; RedisValue rawData = redisDb.StringGet(currKey); if (rawData.HasValue) @@ -326,7 +326,7 @@ namespace MP.Data.Services string source = "DB"; sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... RedisValue rawData = redisDb.StringGet(Constants.redisMseKey); if (rawData.HasValue && !forceDb) { @@ -426,7 +426,7 @@ namespace MP.Data.Services #region Private Methods /// - /// Esegue flush memoria redisConn dato pat2Flush + /// Esegue flush memoria _redisConn dato pat2Flush /// /// /// diff --git a/MP.Data/Services/TabDataService.cs b/MP.Data/Services/TabDataService.cs index 82dbab87..0aa47c54 100644 --- a/MP.Data/Services/TabDataService.cs +++ b/MP.Data/Services/TabDataService.cs @@ -167,9 +167,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:AlarmLog:{idxMacchina}:{dtFrom:yyyyMMdd-HHmmss}:{dtTo::yyyyMMdd-HHmmss}:{showMulti}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -180,7 +180,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbTabController.AlarmLogListFilt(idxMacchina, dtFrom, dtTo, showMulti)); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraFastCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraFastCache); } if (result == null) { @@ -227,9 +227,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:AnagEventi:ALL"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -240,7 +240,7 @@ namespace MP.Data.Services result = dbTabController.AnagEventiGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -261,9 +261,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:VSEB:{IdxMacch}"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -274,7 +274,7 @@ namespace MP.Data.Services result = dbTabController.AnagEventiGetByMacc(IdxMacch); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, LongCache); + _redisDb.StringSet(currKey, rawData, LongCache); } if (result == null) { @@ -296,9 +296,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:AnagTags"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -309,7 +309,7 @@ namespace MP.Data.Services result = dbTabController.AnagTagsOrd(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraLongCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraLongCache); } if (result == null) { @@ -333,9 +333,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:AnagStati"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -347,7 +347,7 @@ namespace MP.Data.Services result = dbTabController.AnagStatiGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -371,9 +371,9 @@ namespace MP.Data.Services stopWatch.Start(); string readType = "DB"; string sKey = string.IsNullOrEmpty(tipo) ? "ALL" : tipo; - string currKey = $"{Utils.redisArtList}:{azienda}:Tipo:{sKey}"; - // cerco in redisConn dato valore sel idxMaccSel... - RedisValue rawData = redisDb.StringGet(currKey); + string currKey = $"{MP.Core.Utils.redisArtList}:{azienda}:Tipo:{sKey}"; + // cerco in _redisConn dato valore sel idxMaccSel... + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -384,7 +384,7 @@ namespace MP.Data.Services result = dbTabController.ArticoliGetByTipo(tipo, azienda); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraLongCache); + _redisDb.StringSet(currKey, rawData, UltraLongCache); } if (result == null) { @@ -410,9 +410,9 @@ namespace MP.Data.Services sw.Start(); List result = new List(); DateTime adesso = DateTime.Now; - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Commenti:{idxMacchina}:{adesso:yyMMdd-HHmm}:{numDays}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -424,7 +424,7 @@ namespace MP.Data.Services result = dbTabController.CommentiGetLastByMacc(idxMacchina, numDays); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraFastCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraFastCache); } if (result == null) { @@ -484,9 +484,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Conf"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -498,7 +498,7 @@ namespace MP.Data.Services result = dbTabController.ConfigGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, LongCache); + _redisDb.StringSet(currKey, rawData, LongCache); } if (result == null) { @@ -666,9 +666,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:ElConfProd:{idxMacchina}:{dataFrom:yyyyyMMdd-HHmm}:{dataFrom:yyyyyMMdd-HHmm}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}") ?? new List(); @@ -679,7 +679,7 @@ namespace MP.Data.Services result = dbTabController.ElencoConfProdFilt(idxMacchina, dataFrom, dataTo); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraLongCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraLongCache); } sw.Stop(); string callName = $"ElencoConfProdFiltAsync.{source}"; @@ -724,9 +724,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:ElencoOpr"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -737,7 +737,7 @@ namespace MP.Data.Services result = dbTabController.ElencoOperatori(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -794,9 +794,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:EvList:Last:{idxMacchina}:{idxTipo}:{dtLimit:yyyyMMdd-HHmm}:{maxRec}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -808,7 +808,7 @@ namespace MP.Data.Services result = await dbTabController.EvListGetLastBySearch(idxMacchina, dtLimit, idxTipo, maxRec); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -875,9 +875,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:FNQ:{idxMacchina}:{gg}:{durataMin:N0}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -888,7 +888,7 @@ namespace MP.Data.Services result = dbTabController.FermiNonQualificatiFilt(idxMacchina, gg, durataMin); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, FastCache); + await _redisDb.StringSetAsync(currKey, rawData, FastCache); } if (result == null) { @@ -939,7 +939,7 @@ namespace MP.Data.Services TimeSpan answ = TimeSpan.FromMinutes(-1); try { - answ = redisDb.KeyTimeToLive(redKey) ?? new TimeSpan(); + answ = _redisDb.KeyTimeToLive(redKey) ?? new TimeSpan(); } catch (Exception exc) { @@ -1078,9 +1078,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:InsMan:{idxMacchina}:{dtFrom:yyyyMMdd-HHmmss}:{dtTo::yyyyMMdd-HHmmss}"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -1091,7 +1091,7 @@ namespace MP.Data.Services result = dbTabController.InsManFilt(idxMacchina, dtFrom, dtTo); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, FastCache); + _redisDb.StringSet(currKey, rawData, FastCache); } if (result == null) { @@ -1271,9 +1271,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); IOB_data? result = new IOB_data(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = RedHashMpIO($"hM2IOB:{IdxMacchina}"); - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -1283,7 +1283,7 @@ namespace MP.Data.Services else { Log.Error($"Errore: non trovato valore valido in REDIS | key: {currKey}"); - Log.Info($"REDIS | conf: {redisConn.Configuration}"); + Log.Info($"REDIS | conf: {_redisConn.Configuration}"); Log.Info($" --> Valore trovato:{Environment.NewLine}{rawData}"); } if (result == null) @@ -1305,9 +1305,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:PODL:{idxMacchina}:{onlyFree}:{onlyDirect}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -1318,7 +1318,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbTabController.ListPODLByMacc(idxMacchina, onlyFree, onlyDirect)); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraFastCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraFastCache); } if (result == null) { @@ -1339,9 +1339,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:ListVal:{tabName}:{fieldName}"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -1352,7 +1352,7 @@ namespace MP.Data.Services result = dbTabController.ListValuesFilt(tabName, fieldName); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraLongCache); + _redisDb.StringSet(currKey, rawData, UltraLongCache); } if (result == null) { @@ -1377,9 +1377,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:LottoExt:{codMagazzino}:{codArt}:{codLotto}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -1390,7 +1390,7 @@ namespace MP.Data.Services result = dbInveController.LottoEsterno(codArt, codLotto, codMagazzino); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraLongCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraLongCache); } if (result == null) { @@ -1424,9 +1424,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Mach2Slave"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -1438,7 +1438,7 @@ namespace MP.Data.Services result = dbTabController.Macchine2Slave(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraFastCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraFastCache); } if (result == null) { @@ -1463,9 +1463,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:MachByMatOp:{MatrOpr}"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -1477,7 +1477,7 @@ namespace MP.Data.Services result = dbTabController.MacchineByMatrOper(MatrOpr); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraLongCache); + _redisDb.StringSet(currKey, rawData, UltraLongCache); } if (result == null) { @@ -1506,9 +1506,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = RedHashMpIO($"CurrentParameters:{idxMacchina}"); - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue && rawData.Length() > 2) { var rawVal = JsonConvert.DeserializeObject>($"{rawData}"); @@ -1610,7 +1610,7 @@ namespace MP.Data.Services // serializzo e salvo string serVal = JsonConvert.SerializeObject(innovations); string currKey = RedHashMpIO($"CurrentParameters:{idxMacchina}"); - RedisValue rawData = redisDb.StringSet(currKey, serVal); + RedisValue rawData = _redisDb.StringSet(currKey, serVal); } return answ; } @@ -1625,7 +1625,7 @@ namespace MP.Data.Services { // hard coded dimensione vettore DatiMacchine Dictionary answ = new Dictionary(); - // ORA recupero da memoria redisConn... + // ORA recupero da memoria _redisConn... try { var currKey = (RedisKey)savedTaskHash(idxMacchina); @@ -1650,9 +1650,9 @@ namespace MP.Data.Services Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); MappaStatoExplModel result = new MappaStatoExplModel(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{Constants.redisMseKeySingle}:{idxMacchSub}"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue && !forceDb) { result = JsonConvert.DeserializeObject($"{rawData}"); @@ -1669,7 +1669,7 @@ namespace MP.Data.Services } // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraFastCache); + _redisDb.StringSet(currKey, rawData, UltraFastCache); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Debug($"Read from DB: {ts.TotalMilliseconds}ms"); @@ -1723,9 +1723,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); ODLExpModel result = new ODLExpModel(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:ODL:{idxOdl}:{onlyUnused}"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); #if false RedisValue rawData = await redisDb.StringGetAsync(currKey); #endif @@ -1743,7 +1743,7 @@ namespace MP.Data.Services result = listRes.FirstOrDefault(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, FastCache); + _redisDb.StringSet(currKey, rawData, FastCache); #if false await redisDb.StringSetAsync(currKey, rawData, FastCache); #endif @@ -1805,9 +1805,9 @@ namespace MP.Data.Services // se vuoto esco subito... if (!string.IsNullOrEmpty(idxMacchina)) { - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:ODL:{idxMacchina}:CURR"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); #if false RedisValue rawData = await redisDb.StringGetAsync(currKey); #endif @@ -1825,7 +1825,7 @@ namespace MP.Data.Services result = listRes.FirstOrDefault(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, FastCache); + _redisDb.StringSet(currKey, rawData, FastCache); #if false await redisDb.StringSetAsync(currKey, rawData, FastCache); #endif @@ -1963,9 +1963,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); ODLModel result = new ODLModel(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:ODL:{idxMacchina}:LAST"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue && !forceDb) { result = JsonConvert.DeserializeObject($"{rawData}"); @@ -1978,7 +1978,7 @@ namespace MP.Data.Services result = results.FirstOrDefault(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraLongCache); + _redisDb.StringSet(currKey, rawData, UltraLongCache); } if (result == null) { @@ -2002,9 +2002,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:ODL:{idxMacchina}:{dtStart:yyyyMMdd-HHmmss}:{dtEnd:yyyyMMdd-HHmmss}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -2017,7 +2017,7 @@ namespace MP.Data.Services result = result.OrderByDescending(x => x.DataInizio).ToList(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, FastCache); + await _redisDb.StringSetAsync(currKey, rawData, FastCache); } if (result == null) { @@ -2039,7 +2039,7 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); ODLModel result = new ODLModel(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:ODL:{idxMacchina}:LAST"; var results = await Task.FromResult(dbTabController.OdlReopenOdlMacc(idxMacchina)); // riordino @@ -2168,9 +2168,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); bool answ = false; - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisUserDataKey}:CurrOpr:{matrOpr}:CurrDevGuid:{DevGuid}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { var done = await ExecFlushRedisPatternAsync(currKey); @@ -2194,7 +2194,7 @@ namespace MP.Data.Services public TimeSpan OperatoreGetGuidTTL(int matrOpr, Guid currDevGuid) { TimeSpan answ = new TimeSpan(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisUserDataKey}:CurrOpr:{matrOpr}:CurrDevGuid:{currDevGuid}"; answ = GetKeyTTL(currKey); return answ; @@ -2211,9 +2211,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); string answ = ""; - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisUserDataKey}:CurrOpr:{matrOpr}:CurrDevGuid:{currDevGuid}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { answ = rawData; @@ -2263,14 +2263,14 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); string answ = ""; - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisUserDataKey}:CurrOpr:{matrOpr}:CurrDevGuid:{currDevGuid}"; - //RedisValue rawData = await redisDb.StringGetAsync(currKey); + //RedisValue rawData = await _redisDb.StringGetAsync(currKey); // serializzo e salvo... //rawData = JsonConvert.SerializeObject(currOpr); answ = currOpr; //var encrData = SteamCrypto.EncryptString(rawData, passPhrase); - await redisDb.StringSetAsync(currKey, currOpr, ConfigCache); + await _redisDb.StringSetAsync(currKey, currOpr, ConfigCache); if (answ == null) { answ = ""; @@ -2293,9 +2293,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:PzProd:{idxMacchina}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -2306,7 +2306,7 @@ namespace MP.Data.Services result = dbTabController.PezziProdMacchina(idxMacchina); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraFastCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraFastCache); } if (result == null) { @@ -2357,10 +2357,10 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); PODLExpModel result = new PODLExpModel(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:PODL:{idxPODL}"; RedisValue rawData; - rawData = redisDb.StringGet(currKey); + rawData = _redisDb.StringGet(currKey); #if false if (doSync) { @@ -2381,7 +2381,7 @@ namespace MP.Data.Services result = dbTabController.PODLExp_getByKey(idxPODL); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, FastCache); + _redisDb.StringSet(currKey, rawData, FastCache); #if false if (doSync) { @@ -2432,9 +2432,9 @@ namespace MP.Data.Services Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); string readType = "DB"; - string currKey = $"{Utils.redisPOdlList}_kit:ByParent:{IdxPodlParent}"; - // cerco in redisConn dato valore sel idxMaccSel... - RedisValue rawData = redisDb.StringGet(currKey); + string currKey = $"{MP.Core.Utils.redisPOdlList}_kit:ByParent:{IdxPodlParent}"; + // cerco in _redisConn dato valore sel idxMaccSel... + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -2445,7 +2445,7 @@ namespace MP.Data.Services result = dbTabController.ListPODL_ByKitParent(IdxPodlParent); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, LongCache); + _redisDb.StringSet(currKey, rawData, LongCache); } if (result == null) { @@ -2469,7 +2469,7 @@ namespace MP.Data.Services saveCallRec("getCounter"); try { - rCall = redisDb.StringGet(redHash($"PzCount:{idxMacchina}")); + rCall = _redisDb.StringGet(redHash($"PzCount:{idxMacchina}")); if (rCall != "" && rCall != null) { int.TryParse(rCall, out answ); @@ -2477,7 +2477,7 @@ namespace MP.Data.Services else { answ = await pzCounterTC(idxMacchina); - // salvo in redisConn... + // salvo in _redisConn... await saveCounter(idxMacchina, answ.ToString()); } } @@ -2523,12 +2523,12 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:RecContr:{idxMacchina}:{idxODL}:{dataFrom:yyyyyMMdd-HHmm}:{dataFrom:yyyyyMMdd-HHmm}:{showMulti}"; #if false RedisValue rawData = redisDb.StringGet(currKey); #endif - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -2542,7 +2542,7 @@ namespace MP.Data.Services #if false redisDb.StringSet(currKey, rawData, UltraLongCache); #endif - await redisDb.StringSetAsync(currKey, rawData, UltraLongCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraLongCache); } if (result == null) { @@ -2601,9 +2601,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:RecContr:{idxMacchina}:LAST"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); #if false RedisValue rawData = await redisDb.StringGetAsync(currKey); #endif @@ -2620,7 +2620,7 @@ namespace MP.Data.Services #if false await redisDb.StringSetAsync(currKey, rawData, UltraLongCache); #endif - redisDb.StringSet(currKey, rawData, UltraLongCache); + _redisDb.StringSet(currKey, rawData, UltraLongCache); } if (result == null) { @@ -2655,9 +2655,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:RegDichiar:{idxMacchina}:{tagCode}:{matrOpr}:{idxODL}:{dataFrom:yyyyyMMdd-HHmm}:{dataTo:yyyyyMMdd-HHmm}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -2668,7 +2668,7 @@ namespace MP.Data.Services result = dbTabController.RegDichiarGetFilt(idxMacchina, tagCode, matrOpr, idxODL, dataFrom, dataTo); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraLongCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraLongCache); } if (result == null) { @@ -2741,9 +2741,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:RegScarti:{idxMacchina}:{idxODL}:{dataFrom:yyyyyMMdd-HHmm}:{dataTo:yyyyyMMdd-HHmm}:{showMulti}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -2754,7 +2754,7 @@ namespace MP.Data.Services result = dbTabController.RegScartiGetFilt(idxMacchina, idxODL, dataFrom, dataTo, showMulti); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -2825,9 +2825,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:RegScartiKit:{ParentRec.IdxMacchina}:{ParentRec.DataOra:yyyyyMMdd-HHmm}:{ParentRec.Causale}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -2838,7 +2838,7 @@ namespace MP.Data.Services result = dbTabController.RegScartiKitGetFilt(ParentRec); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, FastCache); + await _redisDb.StringSetAsync(currKey, rawData, FastCache); } if (result == null) { @@ -2975,7 +2975,7 @@ namespace MP.Data.Services { Log.Info($"Eccezione in calcolo timeout dati macchina: idxMacchina{idxMacchina} | TShort: {tOutShort} | TLong {tOutLong}{Environment.NewLine}{exc}"); } - // salvo in redisConn! + // salvo in _redisConn! redisHashDictSet(currKey, answ, TimeSpan.FromSeconds(redDtMacTOut)); } return answ; @@ -3013,7 +3013,7 @@ namespace MP.Data.Services Value = "FER" }; var result = dbTabController.MicroStatoMacchinaUpsert(newRecMS); - // reset in redisConn + // reset in _redisConn await resetDatiMacchina(idxMacchina); } @@ -3084,12 +3084,12 @@ namespace MP.Data.Services if (newCounter >= 0) { string redKey = redHash($"PzCount:{idxMacchina}"); - // verifico SE ci sia chiave in redisConn (ALTRIMENTI rileggo da DB) - string redVal = redisDb.StringGet(redKey); + // verifico SE ci sia chiave in _redisConn (ALTRIMENTI rileggo da DB) + string redVal = _redisDb.StringGet(redKey); if (!string.IsNullOrEmpty(redVal)) { // salvo in Redis nell'area corretta il valore richiesto - redisDb.StringSet(redKey, counter); + _redisDb.StringSet(redKey, counter); // imposto risposta... answ = counter; } @@ -3097,7 +3097,7 @@ namespace MP.Data.Services { // rileggo da DB e salvo e poi restituisco questo... int currCount = await pzCounterTC(idxMacchina); - redisDb.StringSet(redKey, $"{currCount}"); + _redisDb.StringSet(redKey, $"{currCount}"); // imposto risposta... answ = currCount.ToString(); } @@ -3142,7 +3142,7 @@ namespace MP.Data.Services { currOdlCacheDur = currOdlCacheDur / 4; } - redisDb.StringSet(redHash($"CurrODL:{idxMacchina}"), currIdxOdl, TimeSpan.FromSeconds(currOdlCacheDur)); + _redisDb.StringSet(redHash($"CurrODL:{idxMacchina}"), currIdxOdl, TimeSpan.FromSeconds(currOdlCacheDur)); // registro in risposta che è andato tutto bene... answ = "OK"; } @@ -3182,9 +3182,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:ST:AnagGruppiModel"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -3195,7 +3195,7 @@ namespace MP.Data.Services result = dbTabController.ST_AnagGruppiList(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraLongCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraLongCache); } if (result == null) { @@ -3247,7 +3247,7 @@ namespace MP.Data.Services { StCheckOverride answ = new StCheckOverride() { IdxST = 0 }; string keyDerogaST = redHash($"DerogaSt:{Utente}:{IdxST:000}"); - string rawData = redisDb.StringGet(keyDerogaST); + string rawData = _redisDb.StringGet(keyDerogaST); if (!string.IsNullOrEmpty(rawData)) { try @@ -3269,7 +3269,7 @@ namespace MP.Data.Services { string keyDerogaST = redHash($"DerogaSt:{deroga.Utente}:{deroga.IdxST:000}"); string rawData = JsonConvert.SerializeObject(deroga); - redisDb.StringSet(keyDerogaST, rawData, TimeSpan.FromMinutes(2)); + _redisDb.StringSet(keyDerogaST, rawData, TimeSpan.FromMinutes(2)); fatto = true; } catch (Exception exc) @@ -3292,9 +3292,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:STAR:{codGruppo}:{idxODL}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -3306,7 +3306,7 @@ namespace MP.Data.Services result = dbTabController.STAR_byGrpOdl(codGruppo, idxODL); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -3331,9 +3331,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:STAR:{codGruppo}:{label}:{idxODL}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -3345,7 +3345,7 @@ namespace MP.Data.Services result = dbTabController.STAR_byGrpOdlLbl(codGruppo, label, idxODL); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -3368,9 +3368,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:STAR:Pend:{idxODL}"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -3381,7 +3381,7 @@ namespace MP.Data.Services result = dbTabController.STAR_pendByOdl(idxODL); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(5)); + _redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(5)); } if (result == null) { @@ -3404,9 +3404,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); StatoMacchineModel? result = new StatoMacchineModel(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:StatoMacc:{idxMacchina}"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject($"{rawData}"); @@ -3417,7 +3417,7 @@ namespace MP.Data.Services result = dbTabController.StatoMacchina(idxMacchina); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(2)); + _redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(2)); } if (result == null) { @@ -3443,12 +3443,12 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); StatoProdModel? result = new StatoProdModel(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:StatoProd:{idxMacchina}:{dtReq:HHmm}"; #if false RedisValue rawData = redisDb.StringGet(currKey); #endif - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -3463,7 +3463,7 @@ namespace MP.Data.Services #if false redisDb.StringSet(currKey, rawData, UltraFastCache); #endif - await redisDb.StringSetAsync(currKey, rawData, UltraFastCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraFastCache); } if (result == null) { @@ -3494,9 +3494,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... - string currKey = $"{Utils.redisKitTempl}:{codParent}:{codChild}"; - RedisValue rawData = redisDb.StringGet(currKey); + // cerco in _redisConn... + string currKey = $"{MP.Core.Utils.redisKitTempl}:{codParent}:{codChild}"; + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -3507,7 +3507,7 @@ namespace MP.Data.Services result = dbTabController.TemplateKitFilt(codParent, codChild); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, LongCache); + _redisDb.StringSet(currKey, rawData, LongCache); } if (result == null) { @@ -3528,9 +3528,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); TurniMaccModel? result = new TurniMaccModel(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:TurniMacc:{idxMacchina}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -3542,7 +3542,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbTabController.TurnoMacchinaGet(idxMacchina)); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -3563,9 +3563,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:TurniMacc:All"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -3576,7 +3576,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbTabController.TurnoMacchinaGetAll()); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -3615,7 +3615,7 @@ namespace MP.Data.Services /// /// Intera vista v_MSFD /// - /// forza rilettura + save su redisConn + /// forza rilettura + save su _redisConn /// public async Task> VMSFDGetAll(bool doForce = false) { @@ -3624,9 +3624,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:MSFD:ALL"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue && !doForce) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -3637,7 +3637,7 @@ namespace MP.Data.Services result = dbIocController.VMSFDGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraFastCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraFastCache); } if (result == null) { @@ -3660,9 +3660,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:MSFD:MACCH:{idxMacc}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -3674,7 +3674,7 @@ namespace MP.Data.Services result = dbIocController.VMSFDGetByMacc(idxMacc); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, UltraFastCache); + await _redisDb.StringSetAsync(currKey, rawData, UltraFastCache); } if (result == null) { @@ -3697,9 +3697,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:MSFD:MULTI:{idxMacc}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -3711,7 +3711,7 @@ namespace MP.Data.Services result = dbIocController.VMSFDGetByMacc(idxMacc); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -3729,9 +3729,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Vocab"; - RedisValue rawData = redisDb.StringGet(currKey); + RedisValue rawData = _redisDb.StringGet(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -3742,7 +3742,7 @@ namespace MP.Data.Services result = dbTabController.VocabolarioGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraLongCache); + _redisDb.StringSet(currKey, rawData, UltraLongCache); } if (result == null) { @@ -3763,9 +3763,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:VSCS"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -3776,7 +3776,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbTabController.VSCS_getAll()); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -3799,9 +3799,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:VSODL:{idxMacchina}:{numRec}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -3812,7 +3812,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbTabController.VSOdlGetLastByMacc(idxMacchina, numRec)); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, LongCache); + await _redisDb.StringSetAsync(currKey, rawData, LongCache); } if (result == null) { @@ -3836,9 +3836,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:VSODL:{idxMacchina}:ALL_{showAll}:{numDayAdd}"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); if (rawData.HasValue && rawData.Length() > 2) { result = JsonConvert.DeserializeObject>($"{rawData}"); @@ -3849,7 +3849,7 @@ namespace MP.Data.Services result = await Task.FromResult(dbTabController.VSOdlGetUnused(idxMacchina, showAll, numDayAdd)); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - await redisDb.StringSetAsync(currKey, rawData, FastCache); + await _redisDb.StringSetAsync(currKey, rawData, FastCache); } if (result == null) { @@ -3962,26 +3962,26 @@ namespace MP.Data.Services #region Private Methods /// - /// Esegue flush memoria redisConn dato pat2Flush, metodo sincrono + /// Esegue flush memoria _redisConn dato pat2Flush, metodo sincrono /// /// /// private bool ExecFlushRedisPattern(RedisValue pat2Flush) { bool answ = false; - var masterEndpoint = redisConn.GetEndPoints() - .Where(ep => redisConn.GetServer(ep).IsConnected && !redisConn.GetServer(ep).IsReplica) + var masterEndpoint = _redisConn.GetEndPoints() + .Where(ep => _redisConn.GetServer(ep).IsConnected && !_redisConn.GetServer(ep).IsReplica) .FirstOrDefault(); // sepattern è "*" elimino intero DB... if (masterEndpoint != null && (pat2Flush.Equals(new RedisValue("*")) || pat2Flush == RedisValue.Null)) { - redisConn.GetServer(masterEndpoint).FlushDatabase(database: redisDb.Database); + _redisConn.GetServer(masterEndpoint).FlushDatabase(database: _redisDb.Database); } else { - var server = redisConn.GetServer(masterEndpoint); - var keys = server.Keys(database: redisDb.Database, pattern: pat2Flush, pageSize: 1000); + var server = _redisConn.GetServer(masterEndpoint); + var keys = server.Keys(database: _redisDb.Database, pattern: pat2Flush, pageSize: 1000); var batch = new List(); foreach (var key in keys) { @@ -3991,7 +3991,7 @@ namespace MP.Data.Services if (batch.Count >= 1000) { foreach (var item in batch) - redisDb.KeyDelete(item); + _redisDb.KeyDelete(item); batch.Clear(); } @@ -3999,7 +3999,7 @@ namespace MP.Data.Services // Flush remaining keys foreach (var item in batch) - redisDb.KeyDelete(item); + _redisDb.KeyDelete(item); } answ = true; #if false @@ -4025,31 +4025,31 @@ namespace MP.Data.Services } /// - /// Esegue flush memoria redisConn dato pat2Flush in async + /// Esegue flush memoria _redisConn dato pat2Flush in async /// /// /// private async Task ExecFlushRedisPatternAsync(RedisValue pat2Flush) { bool answ = false; - var masterEndpoint = redisConn.GetEndPoints() - .Where(ep => redisConn.GetServer(ep).IsConnected && !redisConn.GetServer(ep).IsReplica) + var masterEndpoint = _redisConn.GetEndPoints() + .Where(ep => _redisConn.GetServer(ep).IsConnected && !_redisConn.GetServer(ep).IsReplica) .FirstOrDefault(); // se pattern è "*" elimino intero DB... if (masterEndpoint != null && (pat2Flush.Equals(new RedisValue("*")) || pat2Flush == RedisValue.Null)) { - redisConn.GetServer(masterEndpoint).FlushDatabase(database: redisDb.Database); + _redisConn.GetServer(masterEndpoint).FlushDatabase(database: _redisDb.Database); } else { - var server = redisConn.GetServer(masterEndpoint); - var keys = server.Keys(database: redisDb.Database, pattern: pat2Flush, pageSize: 1000); + var server = _redisConn.GetServer(masterEndpoint); + var keys = server.Keys(database: _redisDb.Database, pattern: pat2Flush, pageSize: 1000); var deleteTasks = new List(); foreach (var key in keys) { - deleteTasks.Add(redisDb.KeyDeleteAsync(key)); + deleteTasks.Add(_redisDb.KeyDeleteAsync(key)); if (deleteTasks.Count >= 1000) { await Task.WhenAll(deleteTasks); @@ -4104,7 +4104,7 @@ namespace MP.Data.Services { // hard coded dimensione vettore DatiMacchine Dictionary answ = new Dictionary(); - // ORA recupero da memoria redisConn... + // ORA recupero da memoria _redisConn... try { var currKey = (RedisKey)exeTaskHash(idxMacchina); @@ -4165,7 +4165,7 @@ namespace MP.Data.Services } /// - /// Recupero HashSet redisConn come Dictionary + /// Recupero HashSet _redisConn come Dictionary /// /// /// @@ -4174,7 +4174,7 @@ namespace MP.Data.Services Dictionary answ = new Dictionary(); try { - answ = redisDb + answ = _redisDb .HashGetAll(currKey) .ToDictionary(x => $"{x.Name}", x => $"{x.Value}"); } @@ -4203,7 +4203,7 @@ namespace MP.Data.Services i++; } // salvo! - redisDb.HashSet(currKey, data2ins); + _redisDb.HashSet(currKey, data2ins); fatto = true; } catch (Exception exc) @@ -4232,8 +4232,8 @@ namespace MP.Data.Services i++; } // salvo! - redisDb.HashSet(currKey, data2ins); - redisDb.KeyExpire(currKey, ttl); + _redisDb.HashSet(currKey, data2ins); + _redisDb.KeyExpire(currKey, ttl); fatto = true; } catch (Exception exc) @@ -4250,7 +4250,7 @@ namespace MP.Data.Services private void saveCallRec(string callCountKey) { // conto la richiesta nel contatore REDIS - long nCall = redisDb.StringIncrement(redHash($"COUNT:pCall:{callCountKey}")); + long nCall = _redisDb.StringIncrement(redHash($"COUNT:pCall:{callCountKey}")); //... se == nCall2Log scrivo su log e resetto int nCall2Log = 10; ConfigGetVal("nCall2Log", ref nCall2Log); @@ -4260,7 +4260,7 @@ namespace MP.Data.Services // loggo Log.Info($"{callCountKey}: {nCall} call received"); // resetto! - redisDb.StringSet(redHash($"COUNT:pCall:{callCountKey}"), "0"); + _redisDb.StringSet(redHash($"COUNT:pCall:{callCountKey}"), "0"); } } diff --git a/MP.Data/Services/TranslateSrv.cs b/MP.Data/Services/TranslateSrv.cs index 40ddaa8a..10af4614 100644 --- a/MP.Data/Services/TranslateSrv.cs +++ b/MP.Data/Services/TranslateSrv.cs @@ -62,9 +62,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Conf"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -76,7 +76,7 @@ namespace MP.Data.Services result = dbController.ConfigGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, LongCache); + _redisDb.StringSet(currKey, rawData, LongCache); } if (result == null) { @@ -122,9 +122,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Lang"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -136,7 +136,7 @@ namespace MP.Data.Services result = dbController.LingueGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraLongCache); + _redisDb.StringSet(currKey, rawData, UltraLongCache); } if (result == null) { @@ -174,9 +174,9 @@ namespace MP.Data.Services Stopwatch sw = new Stopwatch(); sw.Start(); List? result = new List(); - // cerco in redisConn... + // cerco in _redisConn... string currKey = $"{redisBaseKey}:Voc"; - RedisValue rawData = await redisDb.StringGetAsync(currKey); + RedisValue rawData = await _redisDb.StringGetAsync(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { @@ -188,7 +188,7 @@ namespace MP.Data.Services result = dbController.VocabolarioGetAll(); // serializzo e salvo... rawData = JsonConvert.SerializeObject(result); - redisDb.StringSet(currKey, rawData, UltraLongCache); + _redisDb.StringSet(currKey, rawData, UltraLongCache); } if (result == null) { @@ -254,31 +254,31 @@ namespace MP.Data.Services } /// - /// Esegue flush memoria redisConn dato pat2Flush + /// Esegue flush memoria _redisConn dato pat2Flush /// /// /// private async Task ExecFlushRedisPattern(RedisValue pat2Flush) { bool answ = false; - var masterEndpoint = redisConn.GetEndPoints() - .Where(ep => redisConn.GetServer(ep).IsConnected && !redisConn.GetServer(ep).IsReplica) + var masterEndpoint = _redisConn.GetEndPoints() + .Where(ep => _redisConn.GetServer(ep).IsConnected && !_redisConn.GetServer(ep).IsReplica) .FirstOrDefault(); // sepattern è "*" elimino intero DB... if (masterEndpoint != null && (pat2Flush.Equals(new RedisValue("*")) || pat2Flush == RedisValue.Null)) { - redisConn.GetServer(masterEndpoint).FlushDatabase(database: redisDb.Database); + _redisConn.GetServer(masterEndpoint).FlushDatabase(database: _redisDb.Database); } else { - var server = redisConn.GetServer(masterEndpoint); - var keys = server.Keys(database: redisDb.Database, pattern: pat2Flush, pageSize: 1000); + var server = _redisConn.GetServer(masterEndpoint); + var keys = server.Keys(database: _redisDb.Database, pattern: pat2Flush, pageSize: 1000); var deleteTasks = new List(); foreach (var key in keys) { - deleteTasks.Add(redisDb.KeyDeleteAsync(key)); + deleteTasks.Add(_redisDb.KeyDeleteAsync(key)); if (deleteTasks.Count >= 1000) { await Task.WhenAll(deleteTasks); diff --git a/MP.Data/Services/Utils/IStatsAggrService.cs b/MP.Data/Services/Utils/IStatsAggrService.cs index d38a0403..1cdf04e3 100644 --- a/MP.Data/Services/Utils/IStatsAggrService.cs +++ b/MP.Data/Services/Utils/IStatsAggrService.cs @@ -1,4 +1,10 @@ -namespace MP.Data.Services.Utils +using EgwCoreLib.Utils; +using MP.Data.DbModels.Utils; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace MP.Data.Services.Utils { public interface IStatsAggrService { diff --git a/MP.Data/Services/Utils/IStatsDetailService.cs b/MP.Data/Services/Utils/IStatsDetailService.cs index 1eb399da..8b674e89 100644 --- a/MP.Data/Services/Utils/IStatsDetailService.cs +++ b/MP.Data/Services/Utils/IStatsDetailService.cs @@ -1,4 +1,10 @@ -namespace MP.Data.Services.Utils +using EgwCoreLib.Utils; +using MP.Data.DbModels.Utils; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace MP.Data.Services.Utils { public interface IStatsDetailService { diff --git a/MP.Data/Services/Utils/StatsAggrService.cs b/MP.Data/Services/Utils/StatsAggrService.cs index 2d6ec1ff..110ba373 100644 --- a/MP.Data/Services/Utils/StatsAggrService.cs +++ b/MP.Data/Services/Utils/StatsAggrService.cs @@ -1,4 +1,13 @@ -namespace MP.Data.Services.Utils +using EgwCoreLib.Utils; +using Microsoft.Extensions.Configuration; +using MP.Data.DbModels.Utils; +using MP.Data.Repository.Utils; +using StackExchange.Redis; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace MP.Data.Services.Utils { public class StatsAggrService : BaseServ, IStatsAggrService { diff --git a/MP.Data/Services/Utils/StatsDetailService.cs b/MP.Data/Services/Utils/StatsDetailService.cs index 43a9d2fe..30a19f8c 100644 --- a/MP.Data/Services/Utils/StatsDetailService.cs +++ b/MP.Data/Services/Utils/StatsDetailService.cs @@ -1,4 +1,12 @@ -namespace MP.Data.Services.Utils +using EgwCoreLib.Utils; +using Microsoft.Extensions.Configuration; +using MP.Data.DbModels.Utils; +using MP.Data.Repository.Utils; +using StackExchange.Redis; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +namespace MP.Data.Services.Utils { public class StatsDetailService : BaseServ, IStatsDetailService { diff --git a/MP.IOC/Program.cs b/MP.IOC/Program.cs index f859ea94..83288459 100644 --- a/MP.IOC/Program.cs +++ b/MP.IOC/Program.cs @@ -1,5 +1,7 @@ using Microsoft.AspNetCore.Http.Extensions; +using Microsoft.EntityFrameworkCore; using Microsoft.OpenApi.Models; +using MP.Data; using MP.Data.Repository.Utils; using MP.Data.Services.Utils; using MP.IOC.Data; @@ -60,11 +62,16 @@ logger.Info("YARP reverse proxy configured"); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); -builder.Services.AddHostedService(); + +// da rivedere +#if false +builder.Services.AddHostedService(); +#endif // MP.Data DbContext for Stats repositories -builder.Services.AddDbContextFactory(options => - options.UseSqlServer(builder.Configuration.GetConnectionString("MP.Utils"))); +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.AddScoped(); diff --git a/MP.IOC/Resources/ChangeLog.html b/MP.IOC/Resources/ChangeLog.html index 2bdeaabd..8ca05566 100644 --- a/MP.IOC/Resources/ChangeLog.html +++ b/MP.IOC/Resources/ChangeLog.html @@ -1,6 +1,6 @@ Modulo MP-IOC -

Versione: 6.16.2604.410

+

Versione: 6.16.2604.710


Note di rilascio:
  • diff --git a/MP.IOC/Resources/VersNum.txt b/MP.IOC/Resources/VersNum.txt index 1d821d29..16b6304f 100644 --- a/MP.IOC/Resources/VersNum.txt +++ b/MP.IOC/Resources/VersNum.txt @@ -1 +1 @@ -6.16.2604.410 +6.16.2604.710 diff --git a/MP.IOC/Resources/manifest.xml b/MP.IOC/Resources/manifest.xml index dd967cbf..ce899376 100644 --- a/MP.IOC/Resources/manifest.xml +++ b/MP.IOC/Resources/manifest.xml @@ -1,6 +1,6 @@ - 6.16.2604.410 + 6.16.2604.710 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/Services/BaseServ.cs b/MP.IOC/Services/BaseServ.cs new file mode 100644 index 00000000..a5420f14 --- /dev/null +++ b/MP.IOC/Services/BaseServ.cs @@ -0,0 +1,372 @@ +using MP.Data; +using Newtonsoft.Json; +using NLog; +using StackExchange.Redis; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace MP.IOC.Services +{ + + /// + /// Classe base per i servizi che fornisce funzionalità comuni come + /// - connessione a Redis + /// - configurazione + /// - gestione dei messaggi + /// - strategie di caching. + /// + /// Questa classe agisce come modello per altri servizi derivati. + /// + public class BaseServ + { + #region Public Constructors + + /// + /// Inizializza una nuova istanza della classe BaseServ. + /// Configura la connessione Redis, carica le impostazioni di configurazione e inizializza il serializzatore JSON. + /// + /// Oggetto di configurazione per recuperare le impostazioni dell'applicazione. + /// Multiplexer di connessione Redis per operazioni sul database. + public BaseServ(IConfiguration Configuration, IConnectionMultiplexer RedisConn) + { + _config = Configuration; + _redisConn = RedisConn; + _redisDb = _redisConn.GetDatabase(); + // configuro la base key x la cache Redis, con verifica contenga Cache finale + _redisBaseKey = _config.GetValue("ServerConf:RedisBaseKey") ?? "Lux:Cache"; + // aggiungo cache se non finisse per ":cache" + if (!_redisBaseKey.EndsWith(":Cache")) + { + _redisBaseKey += ":Cache"; + } + + // Configurazione serializzatore JSON per risolvere errore di loop circolare + JSSettings = new JsonSerializerSettings() + { + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + }; + } + + #endregion Public Constructors + + #region Public Properties + + /// + /// Pipe dei messaggi per la comunicazione riguardo update calcolo BOM + /// + public MessagePipe PipeBom { get; set; } = null!; + + /// + /// Pipe dei messaggi per ritorno HwList da Engine di calcolo verso interfaccia utente. + /// I messaggi vengono inviati sul canale Redis definito da ChannelHwList. + /// + public MessagePipe PipeHwList { get; set; } = null!; + + /// + /// Pipe dei messaggi per ritorno HwOptions calcolate da Engine di calcolo verso interfaccia utente. + /// I messaggi vengono inviati sul canale Redis definito da ChannelHwOpt. + /// + public MessagePipe PipeHwOpt { get; set; } = null!; + + /// + /// Pipe dei messaggi per ritorno PNG calcolati da Engine di calcolo verso interfaccia utente. + /// I messaggi vengono inviati sul canale Redis definito da ChannelPng. + /// + public MessagePipe PipePng { get; set; } = null!; + + /// + /// Canale informazioni relativo ad attività relative alla gesitone PROD: + /// - carico macchine + /// - scheduling + /// + public MessagePipe PipeProd { get; set; } = null!; + + /// + /// Pipe dei messaggi per ritorno info elementi del profile + /// + public MessagePipe PipeProfElement { get; set; } = null!; + + /// + /// Pipe dei messaggi per ritorno ProfileListAsync calcolate da Engine di calcolo verso interfaccia utente. + /// I messaggi vengono inviati sul canale Redis definito da ChannelProfList. + /// + public MessagePipe PipeProfList { get; set; } = null!; + + /// + /// Pipe dei messaggi per ritorno Shape calcolate da Engine di calcolo verso interfaccia utente. + /// I messaggi vengono inviati sul canale Redis definito da ChannelShape. + /// + public MessagePipe PipeShape { get; set; } = null!; + + /// + /// Pipe dei messaggi per ritorno SVG calcolati da Engine di calcolo verso interfaccia utente. + /// I messaggi vengono inviati sul canale Redis definito da ChannelSvg. + /// + public MessagePipe PipeSvg { get; set; } = null!; + + /// + /// Pipe dei messaggi per la comunicazione riguardo update generico UI + /// + public MessagePipe PipeUpdate { get; set; } = null!; + + #endregion Public Properties + + #region Protected Fields + + /// + /// Oggetto per collezione dati Activity (span in Uptrace) + /// + protected static readonly ActivitySource ActivitySource = new ActivitySource("Lux.DATA"); + + /// + /// Oggetto logger utilizzato per registrare eventi e errori a livello di classe. + /// Utile per il monitoraggio del comportamento dell'applicazione e la risoluzione di problemi. + /// + protected static Logger Log = LogManager.GetCurrentClassLogger(); + + /// + /// Oggetto di configurazione statico per accedere alle impostazioni dell'applicazione (es. stringhe di connessione). + /// Condiviso tra tutte le istanze di BaseServ. + /// + protected readonly IConfiguration _config = null!; + + /// + /// Path base chiavi REDIS + /// + protected readonly string _redisBaseKey = "Lux:Cache"; + + /// + /// Oggetto per la connessione a Redis utilizzato per operazioni di lettura/scrittura. + /// + protected readonly IConnectionMultiplexer _redisConn = null!; + + /// + /// Database Redis utilizzato per le operazioni di lettura/scrittura + /// nb: ottenuto tramite _redisConn.GetDatabase() + /// + protected readonly IDatabase _redisDb = null!; + + /// + /// Abilitazione operazioni tracing generiche + /// + protected readonly bool _traceEnabled = false; + + /// + /// Impostazioni del serializzatore JSON utilizzato per gestire oggetti con riferimenti circolari + /// (es. oggetti che si fanno riferimento reciprocamente). + /// + protected JsonSerializerSettings? JSSettings; + + #endregion Protected Fields + + #region Protected Properties + + /// + /// Durata della cache breve (circa 1 minuto + variazione del +/-10%) + /// + protected TimeSpan FastCache + { + get => TimeSpan.FromSeconds(cacheTtlShort * rnd.Next(900, 1100) / 1000); + } + + /// + /// Durata della cache lunga (+ variazione del +/-10%) + /// + protected TimeSpan LongCache + { + get => TimeSpan.FromSeconds(cacheTtlLong * rnd.Next(900, 1100) / 1000); + } + + /// + /// Durata della cache molto breve (circa 10 secondi + variazione del +/-10%) + /// + protected TimeSpan UltraFastCache + { + get => TimeSpan.FromSeconds(cacheTtlShort / 6 * rnd.Next(900, 1100) / 1000); + } + + /// + /// Durata della cache molto lunga (+ variazione del +/-10%) + /// + protected TimeSpan UltraLongCache + { + get => TimeSpan.FromSeconds(cacheTtlLong * 10 * rnd.Next(900, 1100) / 1000); + } + + #endregion Protected Properties + + #region Protected Methods + + /// + /// Helper avvio attività per la funzione tracciata + /// + /// + /// + protected static Activity? StartActivity([CallerMemberName] string? methodName = null) + { + var activity = ActivitySource.StartActivity(methodName ?? "UNDEF"); + activity?.SetTag("host.name", Environment.MachineName); + return activity; + } + + /// + /// Invalida una o più chiavi/pattern in Redis + /// + protected async Task ClearCacheAsync(params string[] patterns) + { + foreach (var pattern in patterns) + { + // Chiamata al tuo metodo esistente + await ExecFlushRedisPatternAsync((RedisValue)pattern); + } + } + + /// + /// Metodo di flush dati cache Redis + /// + /// + /// + protected async Task ExecFlushRedisPatternAsync(RedisValue pattern) + { + // Qui inserisci la tua logica attuale (es. via Lua script o Keys/Scan) + // Esempio rapido via server scan: + var endpoints = _redisConn.GetEndPoints(); + foreach (var endpoint in endpoints) + { + var server = _redisConn.GetServer(endpoint); + await foreach (var key in server.KeysAsync(_redisDb.Database, pattern)) + { + await _redisDb.KeyDeleteAsync(key); + } + } + } + + /// + /// Helper generale di lettura da cache o da funzione (DB) con caching successivo + /// + /// + /// + /// + /// + /// + protected async Task GetOrSetCacheAsync(string key, Func> factory, TimeSpan? expiration = null, [CallerMemberName] string? caller = null) + { + using var activity = StartActivity(); + string source = "DB"; + + // 1. Provo Redis + var cached = await _redisDb.StringGetAsync(key); + if (cached.HasValue) + { + source = "REDIS"; + var cachedResult = JsonConvert.DeserializeObject(cached!)!; + + activity?.SetTag("data.source", source); + LogTrace($"{source} | trace: {activity?.TraceId} | {activity?.Duration.TotalMilliseconds}ms", NLog.LogLevel.Trace, caller); + + return cachedResult; + } + + // 2. Chiamo il factory (DB) + T result = await factory(); + + if (result != null) + { + // 3. Salva in Redis per la prossima volta + var serialized = JsonConvert.SerializeObject(result, JSSettings); + await _redisDb.StringSetAsync(key, serialized, expiration ?? LongCache); + } + + // sistemo activity tracking data + activity?.SetTag("data.source", source); + activity?.Stop(); + + // log in console + LogTrace($"GetOrSetCacheAsync | {source} | trace: {activity?.TraceId} | {activity?.Duration.TotalMilliseconds:N3}ms", NLog.LogLevel.Trace, caller); + + return result!; + } + + /// + /// Helper trace messaggio log (SE abilitato) + /// + /// + /// + /// + protected void LogTrace(string traceMsg, NLog.LogLevel? reqLevel = null, [CallerMemberName] string? methodName = null) + { + if (!_traceEnabled) + return; + + reqLevel ??= NLog.LogLevel.Debug; + + // Loggo! + Log.Log(reqLevel, $"{methodName} | {traceMsg}"); + } + + /// + /// Helper generale per la telemetria e gestione eccezioni + /// + /// + /// + /// + /// + /// + protected async Task TraceAsync(string name, Func> body, object? parameters = null) + { + using var activity = ActivitySource.StartActivity(name); + try + { + if (parameters != null) + { + activity?.SetTag("params", JsonConvert.SerializeObject(parameters)); + } + var result = await body(activity); + activity?.SetStatus(ActivityStatusCode.Ok); + activity?.Stop(); + LogTrace($"TraceAsync | trace: {activity?.TraceId} | {activity?.Duration.TotalMilliseconds}ms", methodName: name); + return result; + } + catch (Exception ex) + { + activity?.SetStatus(ActivityStatusCode.Error, ex.Message); + //Log.Error(ex, "Errore in {MethodName}", name); + LogTrace($"Errore in {name}", NLog.LogLevel.Error, name); + throw; // Riesponi l'eccezione per il tracking globale + } + } + + #endregion Protected Methods + + #region Private Fields + + private static readonly ConcurrentDictionary _locks = new(); + + /// + /// Durata della cache lunga in secondi (predefinito: 5 minuti) + /// Utilizzato nella proprietà LongCache per definire quanto a lungo i dati devono essere memorizzati in cache. + /// + private int cacheTtlLong = 60 * 5; + + /// + /// Durata della cache breve in secondi (predefinito: 1 minuto) + /// Utilizzato nelle proprietà FastCache e UltraFastCache per definire la durata della cache breve. + /// + private int cacheTtlShort = 60 * 1; + + + /// + /// Generatore di numeri casuali utilizzato per introdurre variabilità dinamica nelle durate della cache + /// (simula variazioni reali nella freschezza dei dati e nei tempi di scadenza). + /// + private Random rnd = new Random(); + + #endregion Private Fields + + #region Private Methods + + + #endregion Private Methods + } +} diff --git a/MP.IOC/Services/MetricsDbFlushService.cs b/MP.IOC/Services/MetricsDbFlushService.cs index 1d6dd0ee..4c7b74df 100644 --- a/MP.IOC/Services/MetricsDbFlushService.cs +++ b/MP.IOC/Services/MetricsDbFlushService.cs @@ -1,7 +1,6 @@ using MP.Data.DbModels.Utils; using MP.Data.Services.Utils; using NLog; -using System.Globalization; namespace MP.IOC.Services { @@ -29,7 +28,7 @@ namespace MP.IOC.Services protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var interval = _config.GetValue("RouteMan:FlushIntervalSeconds", FlushIntervalSeconds); - + while (!stoppingToken.IsCancellationRequested) { try @@ -51,7 +50,7 @@ namespace MP.IOC.Services public async Task FlushMetricsAsync() { var snapshot = _stats.Snapshot(); - + if (snapshot.Count == 0) { return; @@ -61,7 +60,7 @@ namespace MP.IOC.Services { var utcNow = DateTime.Now; var hourStart = new DateTime(utcNow.Year, utcNow.Month, utcNow.Day, utcNow.Hour, 0, 0); - + var aggrRecords = new List(); var detailRecords = new List(); @@ -82,8 +81,7 @@ namespace MP.IOC.Services RequestCount = count, AvgDuration = avgDuration, MaxDuration = totalMs, - Perc05Duration = 0, - Perc95Duration = 0, + MinDuration = 0, NoReply = 0 }; @@ -99,8 +97,7 @@ namespace MP.IOC.Services RequestCount = dest.Value, AvgDuration = totalMs / dest.Value, MaxDuration = totalMs, - Perc05Duration = 0, - Perc95Duration = 0, + MinDuration = 0, NoReply = 0 };