Files
2025-09-12 11:39:20 +02:00

919 lines
34 KiB
C#

using MP.Core.Conf;
using MP.Data.DbModels;
using Newtonsoft.Json;
using NLog;
using StackExchange.Redis;
using System.Diagnostics;
using EgwCoreLib.Razor;
using EgwCoreLib.Razor.Data;
using EgwCoreLib.Utils;
namespace MP.INVE.Data
{
public class MiDataService : IDisposable
{
#region Public Constructors
public MiDataService(IConfiguration configuration, ILogger<MiDataService> logger)
{
_logger = logger;
_logger.LogInformation("Starting MiDataService INIT");
_configuration = configuration;
// setup compoenti REDIS
redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis"));
redisConnAdmin = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("RedisAdmin"));
redisDb = redisConn.GetDatabase();
// leggo cache lungo periodo
int.TryParse(_configuration.GetValue<string>("ServerConf:redisLongTimeCache"), out redisLongTimeCache);
_logger.LogInformation("Redis INIT");
// conf DB
string connStrData = _configuration.GetConnectionString("MP.Data");
string connStrInve = _configuration.GetConnectionString("MP.Inve");
if (string.IsNullOrEmpty(connStrData) || string.IsNullOrEmpty(connStrInve))
{
_logger.LogError($"DbController: ConnString empty! connStrData: {connStrData} | connStrInve: {connStrInve}");
}
else
{
dbController = new MP.Data.Controllers.MpInveController(configuration);
_logger.LogInformation("DbController OK");
}
}
#endregion Public Constructors
#region Public Properties
public static MP.Data.Controllers.MpInveController dbController { get; set; } = null!;
/// <summary>
/// Dizionario dei tag configurati per IOB
/// </summary>
public Dictionary<string, List<TagData>> currTagConf { get; set; } = new Dictionary<string, List<TagData>>();
#endregion Public Properties
#region Public Methods
/// <summary>
/// Aggiornamento record selezionato
/// </summary>
/// <param name="currRec"></param>
/// <returns></returns>
public async Task<AnagArticoli_MAG> artBySearch(string artSearch)
{
var dbResult = dbController.artBySearch(artSearch);
// elimino cache redis...
await Task.Delay(1);
return dbResult;
}
public async Task<bool> CloseOpenSessione(int sessID, bool flgClose)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
bool result = false;
string source = "DB";
result = await dbController.CloseOpenSessione(sessID, flgClose);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"CloseOpenSessione Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public async Task<List<ConfigModel>> ConfigGetAll()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<ConfigModel>? result = new List<ConfigModel>();
string source = "DB";
// cerco in redis...
RedisValue rawData = await redisDb.StringGetAsync(redisConfigBaseAddr);
if (!string.IsNullOrEmpty($"{rawData}"))
{
result = JsonConvert.DeserializeObject<List<ConfigModel>>($"{rawData}");
source = "REDIS";
}
else
{
result = await Task.FromResult(dbController.ConfigGetAll());
// serializzo e salvo...
rawData = JsonConvert.SerializeObject(result);
await redisDb.StringSetAsync(redisConfigBaseAddr, rawData, getRandTOut(redisLongTimeCache));
source = "DB";
}
if (result == null)
{
result = new List<ConfigModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ConfigGetAll Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
/// <summary>
/// Reset dati cache config
/// </summary>
/// <returns></returns>
public async Task ConfigResetCache()
{
await redisDb.StringSetAsync(redisConfigBaseAddr, "");
}
public async Task<bool> DeleteMag(AnagMagModel Mag)
{
bool result = false;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
result = await dbController.DeleteMag(Mag);
// elimino cache redis...
RedisValue pattern = new RedisValue($"{redisMagList}:*");
bool answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"DeleteMag | Codice magazzino: {Mag.CodMag} | Descrizione magazzino: {Mag.DescMag} | {ts.TotalMilliseconds}ms");
return result;
}
public async Task<bool> deleteScansione(ScanDataModel scan)
{
bool result = false;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
result = await dbController.deleteScansione(scan);
// elimino cache redis...
RedisValue pattern = new RedisValue($"{redisScanBaseAddr}*");
bool answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"deleteScansione | Id scansione: {scan.ScanID} | Codice scansionato: {scan.ScanValue} | {ts.TotalMilliseconds}ms");
return result;
// elimino record dal DB
}
public async Task<bool> deleteSessione(InventorySessionModel session)
{
bool result = false;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
result = await dbController.deleteSessione(session);
// elimino cache redis...
RedisValue pattern = new RedisValue($"{redisBaseAddr}{redisSessionBaseAddr}*");
bool answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"deleteSessione | Id sessione: {session.InveSessID} | Id sessione: {session.Description} | {ts.TotalMilliseconds}ms");
return result;
// elimino record dal DB
}
public string DeriptData(string encData)
{
return SteamCrypto.DecryptString(encData, passPhrase);
}
public void Dispose()
{
}
public List<AnagLottoModel> ElencoLotti()
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<AnagLottoModel>? result = new List<AnagLottoModel>();
// cerco in redis...
RedisValue rawData = redisDb.StringGet(redisLottiInterni);
if (!string.IsNullOrEmpty($"{rawData}"))
{
result = JsonConvert.DeserializeObject<List<AnagLottoModel>>($"{rawData}");
source = "REDIS";
}
else
{
result = dbController.ElencoLotti();
// serializzo e salvo...
rawData = JsonConvert.SerializeObject(result);
redisDb.StringSetAsync(redisLottiInterni, rawData, getRandTOut(redisLongTimeCache));
source = "DB";
}
if (result == null)
{
result = new List<AnagLottoModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ElencoLotti Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public List<AnagOperatoriModel> ElencoOperatori()
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<AnagOperatoriModel>? result = new List<AnagOperatoriModel>();
// cerco in redis...
RedisValue rawData = redisDb.StringGet(redisElencoOperatori);
if (!string.IsNullOrEmpty($"{rawData}"))
{
result = JsonConvert.DeserializeObject<List<AnagOperatoriModel>>($"{rawData}");
source = "REDIS";
}
else
{
result = dbController.ElencoOperatori();
// serializzo e salvo...
rawData = JsonConvert.SerializeObject(result);
redisDb.StringSetAsync(redisElencoOperatori, rawData, getRandTOut(redisLongTimeCache));
source = "DB";
}
if (result == null)
{
result = new List<AnagOperatoriModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ElencoOperatori Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public List<AnagUdcModel> ElencoUDC()
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<AnagUdcModel>? result = new List<AnagUdcModel>();
// cerco in redis...
RedisValue rawData = redisDb.StringGet(redisUdcBaseAddr);
if (!string.IsNullOrEmpty($"{rawData}"))
{
result = JsonConvert.DeserializeObject<List<AnagUdcModel>>($"{rawData}");
source = "REDIS";
}
else
{
result = dbController.ElencoUdc();
// serializzo e salvo...
rawData = JsonConvert.SerializeObject(result);
redisDb.StringSetAsync(redisUdcBaseAddr, rawData, getRandTOut(redisLongTimeCache));
source = "DB";
}
if (result == null)
{
result = new List<AnagUdcModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ElencoUDC Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public string EncriptData(string rawData)
{
return SteamCrypto.EncryptString(rawData, passPhrase);
}
/// <summary>
/// Export sessione scansioni inventario (in dettaglio)
/// </summary>
/// <param name="sessID"></param>
/// <returns></returns>
public List<VExpInveSession> ExportSessionDetail(int sessID)
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<VExpInveSession>? result = new List<VExpInveSession>();
result = dbController.ExportSessionDetail(sessID);
source = "DB";
if (result == null)
{
result = new List<VExpInveSession>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ExportSessionDetail Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
/// <summary>
/// Svuota tutta la sessione dalla root di gestione
/// </summary>
/// <returns></returns>
public async Task<bool> FlushRedisCache()
{
await Task.Delay(1);
RedisValue pattern = new RedisValue($"{redisBaseAddr}*");
bool answ = await ExecFlushRedisPattern(pattern);
return answ;
}
/// <summary>
/// Svuota solo il pat2Flush richiesto
/// </summary>
/// <param name="basePattern"></param>
/// <returns></returns>
public async Task<bool> FlushRedisCache(string basePattern)
{
await Task.Delay(1);
RedisValue pattern = new RedisValue($"{basePattern}*");
bool answ = await ExecFlushRedisPattern(pattern);
return answ;
}
/// <summary> Svuota cahce sessioni inventario <returns></returns>
public async Task<bool> FlushSessInvCache()
{
bool answ = await FlushRedisCache(redisSessionCurrList) && await FlushRedisCache(redisSessionHistList);
return answ;
}
public async Task<bool> InsertNewMag(AnagMagModel newMag)
{
bool result = false;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
result = await dbController.InsertNewMag(newMag);
// elimino cache redis...
RedisValue pattern = new RedisValue($"{redisMagList}");
bool answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"InsertNewMag | Codice magazzino: {newMag.CodMag} | Descrizione magazzino: {newMag.DescMag} | {ts.TotalMilliseconds}ms");
return result;
// aggiungo record al DB
}
public async Task<bool> InsertNewScansione(ScanDataModel newScan)
{
bool result = false;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
result = await dbController.InsertNewScansione(newScan);
// elimino cache redis...
RedisValue pattern = new RedisValue(redisScanBaseAddr);
bool answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"InsertNewScansione | Id scansione: {newScan.ScanID} | Id sessione: {newScan.InveSessID} | {ts.TotalMilliseconds}ms");
return result;
// aggiungo record al DB
}
public async Task<bool> InsertNewSessione(InventorySessionModel newSess)
{
bool result = false;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
result = await dbController.InsertNewSessione(newSess);
// elimino cache redis...
RedisValue pattern = new RedisValue($"{redisBaseAddr}{redisSessionBaseAddr}*");
bool answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"InsertNewSessione | Id sessione: {newSess.InveSessID} | Descrizione sessione: {newSess.Description} | {ts.TotalMilliseconds}ms");
return result;
// aggiungo record al DB
}
public InventorySessionModel InventSessByID(int sessID)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
InventorySessionModel result = new InventorySessionModel();
string source = "DB";
result = dbController.InventSessByID(sessID);
//if (result == null)
//{
// result = new InventorySessionModel();
//}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"InventSessByID Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public List<InventorySessionModel> InventSessCurrList()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<InventorySessionModel>? result = new List<InventorySessionModel>();
string source = "DB";
// cerco in redis...
RedisValue rawData = redisDb.StringGet(redisSessionCurrList);
if (!string.IsNullOrEmpty($"{rawData}"))
{
result = JsonConvert.DeserializeObject<List<InventorySessionModel>>($"{rawData}");
source = "REDIS";
}
else
{
result = dbController.InventSessCurrList();
// serializzo e salvo...
rawData = JsonConvert.SerializeObject(result);
redisDb.StringSetAsync(redisSessionCurrList, rawData, getRandTOut(redisLongTimeCache));
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"InventSessCurrList Read from {source}: {ts.TotalMilliseconds}ms");
if (result == null)
{
result = new List<InventorySessionModel>();
}
return result;
}
public List<InventorySessionModel> InventSessHistList()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<InventorySessionModel> result = new List<InventorySessionModel>();
string source = "DB";
// cerco in redis...
RedisValue rawData = redisDb.StringGet($"{redisSessionHistList}");
if (!string.IsNullOrEmpty($"{rawData}"))
{
result = JsonConvert.DeserializeObject<List<InventorySessionModel>>($"{rawData}");
source = "REDIS";
}
else
{
result = dbController.InventSessHistList();
// serializzo e salvo...
rawData = JsonConvert.SerializeObject(result);
redisDb.StringSetAsync(redisSessionHistList, rawData, getRandTOut(redisLongTimeCache));
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"InventSessHistList Read from {source}: {ts.TotalMilliseconds}ms");
if (result == null)
{
result = new List<InventorySessionModel>();
}
return result;
}
public List<InveSessTotLotModel> InveSessTotLotList(int sessID)
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<InveSessTotLotModel>? result = new List<InveSessTotLotModel>();
result = dbController.InveSessTotLotList(sessID);
source = "DB";
if (result == null)
{
result = new List<InveSessTotLotModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"InveSessTotLotList Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public AnagUdcModel IsUDC(string udc)
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
AnagUdcModel? result = new AnagUdcModel();
result = dbController.IsUDC(udc);
source = "DB";
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"IsUDC Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public bool loginOperatore(int matrOpr, string authkey)
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
AnagOperatoriModel? result = new AnagOperatoriModel();
bool answ = false;
// cerco in redis...
RedisValue rawData = redisDb.StringGet($"{redisElencoOperatori}:{matrOpr}:{authkey}");
if (!string.IsNullOrEmpty($"{rawData}"))
{
result = JsonConvert.DeserializeObject<AnagOperatoriModel>($"{rawData}");
if (result != null)
{
answ = true;
source = "REDIS";
}
}
else
{
answ = dbController.LoginOperatore(matrOpr, authkey);
if (answ)
{
result = ElencoOperatori().Where(x => (x.MatrOpr == matrOpr) && (x.authKey == authkey)).SingleOrDefault();
}
// serializzo e salvo...
rawData = JsonConvert.SerializeObject(result);
redisDb.StringSetAsync(redisOperatoreLogged, rawData, getRandTOut(redisLongTimeCache));
source = "DB";
}
if (result == null)
{
result = new AnagOperatoriModel();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"loginOperatore Read from {source}: {ts.TotalMilliseconds}ms");
return answ;
}
public List<AnagLottiArca> LottoEsterno(string codArt, string codLotto, string codMagazzino)
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<AnagLottiArca>? result = new List<AnagLottiArca>();
// cerco in redis...
result = dbController.LottoEsterno(codArt, codLotto, codMagazzino);
source = "DB";
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"LottoEsterno Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public AnagLottoModel LottoInterno(string lotto)
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
AnagLottoModel? result = new AnagLottoModel();
result = dbController.LottoInterno(lotto);
source = "DB";
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"LottoInterno Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public List<AnagMagModel> MagazziniList()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<AnagMagModel> result = new List<AnagMagModel>();
string source = "DB";
// cerco in redis...
RedisValue rawData = redisDb.StringGet(redisMagList);
if (!string.IsNullOrEmpty($"{rawData}"))
{
result = JsonConvert.DeserializeObject<List<AnagMagModel>>($"{rawData}");
source = "REDIS";
}
else
{
result = dbController.MagazziniList();
// serializzo e salvo...
rawData = JsonConvert.SerializeObject(result);
redisDb.StringSetAsync(redisMagList, rawData, getRandTOut(redisLongTimeCache));
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ElencoMagazzini Read from {source}: {ts.TotalMilliseconds}ms");
if (result == null)
{
result = new List<AnagMagModel>();
}
return result;
}
/// <summary>
/// Scansioni dato lotto e sessione
/// </summary>
/// <param name="lotto"></param>
/// <param name="inveSessId"></param>
/// <returns></returns>
public async Task<List<ScanDataModel>> ScanByLottoSession(string lotto, int inveSessId)
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<ScanDataModel>? result = new List<ScanDataModel>();
result = dbController.ScanByLottoSession(lotto, inveSessId);
source = "DB";
stopWatch.Stop();
await Task.Delay(1);
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ScanByLottoSession Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public List<ScanDataModel> ScanBySession(int idSessione)
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<ScanDataModel>? result = new List<ScanDataModel>();
// cerco in redis...
{
var ListAll = ScanList();
result = ListAll.Where(x => x.InveSessID == idSessione).ToList();
if (result == null)
{
result = new List<ScanDataModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ScanBySession Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
}
/// <summary>
/// Scansioni dati UDC e sessione
/// </summary>
/// <param name="udc"></param>
/// <param name="inveSessId"></param>
/// <returns></returns>
public ScanDataModel ScanByUdcSession(string udc, int inveSessId)
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
ScanDataModel? result = new ScanDataModel();
result = dbController.ScanByUdcSession(udc, inveSessId);
source = "DB";
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ScanByUdcSession Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public List<ScanDataModel> ScanByValueSessionOpr(string scanData, int inveSessId, string Opr)
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<ScanDataModel>? result = new List<ScanDataModel>();
result = dbController.ScanByValueSessionOpr(scanData, inveSessId, Opr);
source = "DB";
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ScanByValueSessionOpr Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public List<ScanDataModel> ScanList()
{
string source = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<ScanDataModel>? result = new List<ScanDataModel>();
// cerco in redis...
RedisValue rawData = redisDb.StringGet(redisScanBaseAddr);
if (!string.IsNullOrEmpty($"{rawData}"))
{
result = JsonConvert.DeserializeObject<List<ScanDataModel>>($"{rawData}");
source = "REDIS";
}
else
{
result = dbController.ScanList();
// serializzo e salvo...
rawData = JsonConvert.SerializeObject(result);
redisDb.StringSetAsync(redisScanBaseAddr, rawData, getRandTOut(redisLongTimeCache));
source = "DB";
}
if (result == null)
{
result = new List<ScanDataModel>();
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"ScanList Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
public async Task<bool> TransferSessione(int sessID)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
bool result = false;
string source = "DB";
result = await dbController.TransferSessione(sessID);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"TransferSessione Read from {source}: {ts.TotalMilliseconds}ms");
return result;
}
/// <summary>
/// Restituisce valore della stringa (SE disponibile)
/// </summary>
/// <param name="keyName"></param>
/// <returns></returns>
public async Task<string> tryGetConfig(string keyName)
{
string answ = "";
// preselezione valori
var configData = await ConfigGetAll();
var currRec = configData.FirstOrDefault(x => x.Chiave == keyName);
if (currRec != null)
{
answ = currRec.Valore;
}
return answ;
}
public async Task<bool> UpdateMag(AnagMagModel Mag)
{
bool result = false;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
result = await dbController.UpdateMag(Mag);
// elimino cache redis...
RedisValue pattern = new RedisValue($"{redisMagList}");
bool answ = await ExecFlushRedisPattern(pattern);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Debug($"UpdateMag | Codice magazzino: {Mag.CodMag} | Descrizione magazzino: {Mag.DescMag} | {ts.TotalMilliseconds}ms");
return result;
// aggiungo record al DB
}
/// <summary>
/// Aggiornamento record selezionato
/// </summary>
/// <param name="currRec"></param>
/// <returns></returns>
public async Task<bool> UpdateScan(ScanDataModel currRec)
{
var dbResult = await dbController.updateScan(currRec);
// elimino cache redis...
RedisValue pattern = new RedisValue(redisScanBaseAddr);
bool answ = await ExecFlushRedisPattern(pattern);
await Task.Delay(1);
return dbResult;
}
#endregion Public Methods
#region Protected Fields
protected const string passPhrase = "7871D817-C71F-4DFC-BF12-00A95BE507B5";
protected Random rand = new Random();
#endregion Protected Fields
#region Protected Methods
/// <summary>
/// Restituisce un timeout dai minuti richiesti + tempo random 1..60 sec
/// </summary>
/// <param name="stdMinutes"></param>
/// <returns></returns>
protected TimeSpan getRandTOut(int stdMinutes)
{
double rndValue = (double)stdMinutes + (double)rand.Next(1, 60) / 60;
return TimeSpan.FromMinutes(rndValue);
}
#endregion Protected Methods
#region Private Fields
private const string redisBaseAddr = "MP:INVE";
private const string redisConfigBaseAddr = ":Config";
private const string redisElencoOperatori = redisBaseAddr + redisOperatoriBaseAddr + ":ListOperatori";
private const string redisLottiBaseAddr = ":Lotti";
private const string redisLottiEsterni = redisBaseAddr + redisLottiBaseAddr + ":LottiEsterni";
private const string redisLottiInterni = redisBaseAddr + redisLottiBaseAddr + ":LottiInterni";
private const string redisMagList = redisBaseAddr + ":ListMag";
private const string redisOperatoreLogged = redisBaseAddr + redisOperatoriBaseAddr + ":OperatoreLogged";
private const string redisOperatoriBaseAddr = ":Operatore";
private const string redisScanBaseAddr = redisBaseAddr + ":Scan";
private const string redisSessionBaseAddr = ":Session";
private const string redisSessionCurrList = redisBaseAddr + redisSessionBaseAddr + ":ListSessHist";
private const string redisSessionHistList = redisBaseAddr + redisSessionBaseAddr + ":ListSessCurr";
private const string redisTotLottoAddr = ":TotaleLotto";
private const string redisUdcBaseAddr = ":UDC";
private static IConfiguration _configuration = null!;
private static ILogger<MiDataService> _logger = null!;
private static Logger Log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Oggetto vocabolario x uso continuo traduzione
/// </summary>
private List<VocabolarioModel> ObjVocabolario = new List<VocabolarioModel>();
/// <summary>
/// Oggetto per connessione a REDIS
/// </summary>
private ConnectionMultiplexer redisConn = null!;
/// <summary>
/// Oggetto per connessione a REDIS modalità admin (ex flux dati)
/// </summary>
private ConnectionMultiplexer redisConnAdmin = null!;
/// <summary>
/// Oggetto DB redis da impiegare x chiamate R/W
/// </summary>
private IDatabase redisDb = null!;
private int redisLongTimeCache = 5;
#endregion Private Fields
#region Private Methods
/// <summary>
/// Esegue flush memoria redis dato pat2Flush
/// </summary>
/// <param name="pat2Flush"></param>
/// <returns></returns>
private async Task<bool> ExecFlushRedisPattern(RedisValue pat2Flush)
{
bool answ = false;
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);
}
else
{
var server = redisConn.GetServer(masterEndpoint);
var keys = server.Keys(database: redisDb.Database, pattern: pat2Flush, pageSize: 1000);
var deleteTasks = new List<Task>();
foreach (var key in keys)
{
deleteTasks.Add(redisDb.KeyDeleteAsync(key));
if (deleteTasks.Count >= 1000)
{
await Task.WhenAll(deleteTasks);
deleteTasks.Clear();
}
}
if (deleteTasks.Count > 0)
{
await Task.WhenAll(deleteTasks);
}
}
answ = true;
#if false
var listEndpoints = redisConnAdmin.GetEndPoints();
foreach (var endPoint in listEndpoints)
{
//var server = redisConnAdmin.GetServer(listEndpoints[0]);
var server = redisConnAdmin.GetServer(endPoint);
if (server != null)
{
var keyList = server.Keys(redisDb.Database, pattern);
foreach (var item in keyList)
{
await redisDb.KeyDeleteAsync(item);
}
// brutalmente rimuovo intero contenuto DB... DANGER
//await server.FlushDatabaseAsync();
answ = true;
}
}
#endif
return answ;
}
#endregion Private Methods
}
}