using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using NLog; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity.UI.Services; using Core; namespace LiMan.UI.Data { public class LiManDataService : IDisposable { #region Private Fields private static IConfiguration _configuration; private static ILogger _logger; private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); private readonly IEmailSender _emailSender; private readonly IDistributedCache distributedCache; private readonly IMemoryCache memoryCache; /// /// Durata assoluta massima della cache IN SECONDI /// private int chAbsExp = 60 * 5; /// /// Durata della cache IN SECONDI in modalità inattiva (non acceduta) prima di venire rimossa /// NON estende oltre il tempo massimo di validità della cache (chAbsExp) /// private int chSliExp = 60 * 1; #endregion Private Fields #region Protected Fields protected static string connStringBBM = ""; #endregion Protected Fields #region Public Fields public static GLS.Controllers.LicManController dbControllerGLS; public static DB.Controllers.DbController dbControllerNext; #endregion Public Fields #region Public Constructors public LiManDataService(IConfiguration configuration, ILogger logger, IMemoryCache memoryCache, IDistributedCache distributedCache, IEmailSender emailSender) { _logger = logger; _configuration = configuration; _emailSender = emailSender; // conf cache this.memoryCache = memoryCache; this.distributedCache = distributedCache; // conf DB string connStrGLS = _configuration.GetConnectionString("LiMan.GLS"); string connStrDB = _configuration.GetConnectionString("LiMan.DB"); if (string.IsNullOrEmpty(connStrDB) || string.IsNullOrEmpty(connStrGLS)) { _logger.LogError("Almost one ConnString empty!"); } else { dbControllerGLS = new LiMan.GLS.Controllers.LicManController(configuration); dbControllerNext = new LiMan.DB.Controllers.DbController(configuration); _logger.LogInformation("DbControllers OK"); } } #endregion Public Constructors #region Private Methods private DistributedCacheEntryOptions cacheOpt(bool fastCache) { var numSecAbsExp = fastCache ? chAbsExp : chAbsExp * 10; var numSecSliExp = fastCache ? chSliExp : chSliExp * 10; return new DistributedCacheEntryOptions().SetAbsoluteExpiration(DateTime.Now.AddSeconds(numSecAbsExp)).SetSlidingExpiration(TimeSpan.FromSeconds(numSecSliExp)); } #endregion Private Methods #region Protected Methods protected string getCacheKey(string TableName, SelectData CurrFilter) { string answ = $"{TableName}:D_{CurrFilter.DateStart:yyyyMMddHHmm}_{CurrFilter.DateEnd:yyyyMMddHHmm}"; return answ; } #endregion Protected Methods #region Internal Methods /// /// Effettua sblocco di una licenza impostando data veto a oggi /// /// /// public async Task AttivazioneUnlock(int idxSubLic) { bool fatto = dbControllerNext.AttivazioniUnlock(idxSubLic); await Task.Delay(1); return fatto; } /// /// Effettua sblocco di una licenza impostando data veto a oggi /// /// /// internal async Task AttivazioneDelete(int idxSubLic) { bool fatto = dbControllerNext.AttivazioniDelete(idxSubLic); await Task.Delay(1); return fatto; } #endregion Internal Methods #region Public Methods /// /// Hash Redis contenente i dati MP di una specifico TYPE (es StatusMacchina, StateMachineIngressi, ...) /// /// /// public static string mHash(string dataType) { return $"DATA:{dataType}"; } public async Task> ApplicazioniGLSGetAll() { List dbResult = new List(); string cacheKey = mHash("GLS:Applicazioni"); string rawData; var redisDataList = await distributedCache.GetAsync(cacheKey); if (redisDataList != null) { rawData = Encoding.UTF8.GetString(redisDataList); dbResult = JsonConvert.DeserializeObject>(rawData); } else { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); dbResult = dbControllerGLS.GetApplicazioni(); rawData = JsonConvert.SerializeObject(dbResult); redisDataList = Encoding.UTF8.GetBytes(rawData); await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true)); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Trace($"Effettuata lettura da DB + caching per ApplicazioniGLSGetAll: {ts.TotalMilliseconds} ms"); } return await Task.FromResult(dbResult); } public async Task ApplicazioniGLSUpdate(GLS.DatabaseModels.AnagApplicazioni currItem) { bool done = false; try { done = dbControllerGLS.UpdateApplicazioni(currItem); await InvalidateAllCache(); } catch (Exception exc) { Log.Error($"Eccezione in ApplicazioniGLSUpdate:{Environment.NewLine}{exc}"); } return await Task.FromResult(done); } public async Task> ApplicazioniNextGetAll() { List dbResult = new List(); string cacheKey = mHash("Next:Applicazioni"); string rawData; var redisDataList = await distributedCache.GetAsync(cacheKey); if (redisDataList != null) { rawData = Encoding.UTF8.GetString(redisDataList); dbResult = JsonConvert.DeserializeObject>(rawData); } else { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); dbResult = dbControllerNext.GetApplicazioni(); rawData = JsonConvert.SerializeObject(dbResult); redisDataList = Encoding.UTF8.GetBytes(rawData); await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true)); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Trace($"Effettuata lettura da DB + caching per ApplicazioniNextGetAll: {ts.TotalMilliseconds} ms"); } return await Task.FromResult(dbResult); } public async Task ApplicazioniNextUpdate(DB.DBModels.ApplicativoModel currItem) { bool done = false; try { done = dbControllerNext.UpsertApplicazione(currItem); await InvalidateAllCache(); } catch (Exception exc) { Log.Error($"Eccezione in ApplicazioniNextUpdate:{Environment.NewLine}{exc}"); } return await Task.FromResult(done); } /// /// Recupera attivazioni data licenza /// /// /// public async Task> AttivazioniGetByLic(int IdxLic) { Stopwatch stopWatch = new Stopwatch(); List dbResult = new List(); stopWatch.Start(); dbResult = dbControllerNext.AttivazioniGetByLic(IdxLic); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Trace($"Effettuata lettura da DB per AttivazioniGetByLic: {ts.TotalMilliseconds} ms"); return await Task.FromResult(dbResult); } public async Task DbForceMigrate() { return await Task.FromResult(dbControllerGLS.DbForceMigrate()); } public void Dispose() { // Clear database controller dbControllerGLS.Dispose(); } public async Task> InstallazioniGLSGetAll() { List dbResult = new List(); string cacheKey = mHash("GLS:Installazioni"); string rawData; var redisDataList = await distributedCache.GetAsync(cacheKey); if (redisDataList != null) { rawData = Encoding.UTF8.GetString(redisDataList); dbResult = JsonConvert.DeserializeObject>(rawData); } else { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); dbResult = dbControllerGLS.GetInstallazioni(); rawData = JsonConvert.SerializeObject(dbResult); redisDataList = Encoding.UTF8.GetBytes(rawData); await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true)); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Trace($"Effettuata lettura da DB + caching per InstallazioniGLSGetAll: {ts.TotalMilliseconds} ms"); } return await Task.FromResult(dbResult); } public async Task InstallazioniGLSUpdate(GLS.DatabaseModels.AnagInstallazioni currItem) { bool done = false; try { done = dbControllerGLS.UpdateInstallazioni(currItem); await InvalidateAllCache(); } catch (Exception exc) { Log.Error($"Eccezione in InstallazioniGLSUpdate:{Environment.NewLine}{exc}"); } return await Task.FromResult(done); } public async Task> InstallazioniNextGetAll() { List dbResult = new List(); string cacheKey = mHash("Next:Installazioni"); string rawData; var redisDataList = await distributedCache.GetAsync(cacheKey); if (redisDataList != null) { rawData = Encoding.UTF8.GetString(redisDataList); dbResult = JsonConvert.DeserializeObject>(rawData); } else { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); dbResult = dbControllerNext.GetInstallazioni(); rawData = JsonConvert.SerializeObject(dbResult); redisDataList = Encoding.UTF8.GetBytes(rawData); await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true)); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Trace($"Effettuata lettura da DB + caching per InstallazioniNextGetAll: {ts.TotalMilliseconds} ms"); } return await Task.FromResult(dbResult); } public async Task InstallazioniNextUpdate(DB.DBModels.InstallazioneModel currItem) { bool done = false; try { done = dbControllerNext.UpsertInstallazione(currItem); await InvalidateAllCache(); } catch (Exception exc) { Log.Error($"Eccezione in InstallazioniNextUpdate:{Environment.NewLine}{exc}"); } return await Task.FromResult(done); } /// /// invalida tutta la cache in caso di update /// /// public async Task InvalidateAllCache() { await distributedCache.RemoveAsync(mHash("GLS:Applicazioni")); await distributedCache.RemoveAsync(mHash("Next:Applicazioni")); await distributedCache.RemoveAsync(mHash("GLS:Installazioni")); await distributedCache.RemoveAsync(mHash("Next:Installazioni")); await distributedCache.RemoveAsync(mHash("GLS:Licenze")); await distributedCache.RemoveAsync(mHash("Next:Licenze")); //await distributedCache.RemoveAsync(mHash("SUPPL:List")); //await distributedCache.RemoveAsync(mHash("TRANSP:List")); //await distributedCache.RemoveAsync(mHash("WEEKPLAN:List")); } /// /// Trasferisce una licenza da GLS a Next come LOG di una licenza scaduta /// /// /// public async Task LicenzaLogGlsNext(GLS.DatabaseModels.LicenzeAttive currItem, int IdxLicNext) { bool done = false; var currLicenza = dbControllerNext.GetLicenza(IdxLicNext); // step 1: converto licenza, faccio upsert var logLicNext = new DB.DBModels.LogLicenzaModel() { CodApp = currItem.ApplicativoNavigation.Applicativo, CodInst = currItem.InstallazioneNavigation.Installazione, Chiave = currItem.Licenza, NumLicenze = currItem.NumLicenze, Scadenza = currItem.Scadenza, Descrizione = currItem.ApplicativoNavigation.Descrizione, Tipo = TipoLicenza.GLS, IdxLic = IdxLicNext, Locked = true }; bool step1 = dbControllerNext.UpsertLogLic(logLicNext); if (currLicenza != null && step1) { // step 2: disattivo vecchia licenza currItem.Locked = true; done = dbControllerGLS.UpdateLicenze(currItem); } return await Task.FromResult(done); } /// /// Trasferisce una licenza da GLS a Next /// /// /// public async Task LicenzaTransferGlsNext(GLS.DatabaseModels.LicenzeAttive currItem) { bool done = false; // step 1: controllo applicazione esistente DB.DBModels.ApplicativoModel appNext = new DB.DBModels.ApplicativoModel() { CodApp = currItem.ApplicativoNavigation.Applicativo, Descrizione = currItem.ApplicativoNavigation.Descrizione }; bool step1 = dbControllerNext.UpsertApplicazione(appNext); // step 2: controllo installazione esistente var instNext = new DB.DBModels.InstallazioneModel() { Cliente = currItem.InstallazioneNavigation.Installazione, CodInst = currItem.InstallazioneNavigation.Installazione, Contatto = currItem.InstallazioneNavigation.Contatto, Email = currItem.InstallazioneNavigation.Email, Descrizione = currItem.ApplicativoNavigation.Descrizione }; bool step2 = dbControllerNext.UpsertInstallazione(instNext); // step 3: converto licenza, faccio upsert var licNext = new DB.DBModels.LicenzaModel() { CodApp = currItem.ApplicativoNavigation.Applicativo, CodInst = currItem.InstallazioneNavigation.Installazione, Chiave = currItem.Licenza, NumLicenze = currItem.NumLicenze, Scadenza = currItem.Scadenza, Descrizione = currItem.ApplicativoNavigation.Descrizione, Tipo = TipoLicenza.GLS, Enigma = "", Payload = "", DataEnigma = DateTime.Now }; bool step3 = dbControllerNext.UpsertLicenza(licNext); if (step1 && step2 && step3) { // step 4: disattivo vecchia licenza currItem.Locked = true; done = dbControllerGLS.UpdateLicenze(currItem); } return await Task.FromResult(done); } public async Task> LicenzeGLSGetAll() { List dbResult = new List(); string cacheKey = mHash("GLS:Licenze"); string rawData; var redisDataList = await distributedCache.GetAsync(cacheKey); if (redisDataList != null) { rawData = Encoding.UTF8.GetString(redisDataList); dbResult = JsonConvert.DeserializeObject>(rawData); } else { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); dbResult = dbControllerGLS.GetLicenze(); rawData = JsonConvert.SerializeObject(dbResult); redisDataList = Encoding.UTF8.GetBytes(rawData); await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true)); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Trace($"Effettuata lettura da DB + caching per LicenzeGLSGetAll: {ts.TotalMilliseconds} ms"); } return await Task.FromResult(dbResult); } /// /// Recupera licenze SENZA cache /// /// /// public async Task> LicenzeGLSGetFilt(SelectGLS CurrFilter) { Stopwatch stopWatch = new Stopwatch(); List dbResult = new List(); stopWatch.Start(); dbResult = dbControllerGLS.GetLicenzeFilt(CurrFilter.OnlyActive, CurrFilter.OnlyUnlock, CurrFilter.ApplicazioneSel, CurrFilter.InstallazioneSel); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Trace($"Effettuata lettura da DB per LicenzeGLSGetFilt: {ts.TotalMilliseconds} ms"); return await Task.FromResult(dbResult); } public async Task LicenzeGLSUpdate(GLS.DatabaseModels.LicenzeAttive currItem) { bool done = false; #if false try { done = dbControllerGLS.UpdateApplicazioni(currItem); await InvalidateAllCache(); } catch (Exception exc) { Log.Error($"Eccezione in ApplicazioniUpdate:{Environment.NewLine}{exc}"); } #endif return await Task.FromResult(done); } public async Task> LicenzeNextGetAll() { List dbResult = new List(); string cacheKey = mHash("Next:Licenze"); string rawData; var redisDataList = await distributedCache.GetAsync(cacheKey); if (redisDataList != null) { rawData = Encoding.UTF8.GetString(redisDataList); dbResult = JsonConvert.DeserializeObject>(rawData); } else { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); dbResult = dbControllerNext.GetLicenze(); rawData = JsonConvert.SerializeObject(dbResult); redisDataList = Encoding.UTF8.GetBytes(rawData); await distributedCache.SetAsync(cacheKey, redisDataList, cacheOpt(true)); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Trace($"Effettuata lettura da DB + caching per LicenzeNextGetAll: {ts.TotalMilliseconds} ms"); } return await Task.FromResult(dbResult); } /// /// Recupera licenze SENZA cache /// /// /// public async Task> LicenzeNextGetFilt(SelectNext CurrFilter) { Stopwatch stopWatch = new Stopwatch(); List dbResult = new List(); stopWatch.Start(); dbResult = dbControllerNext.GetLicenzeFilt(CurrFilter.OnlyActive, CurrFilter.ApplicazioneSel, CurrFilter.InstallazioneSel); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Trace($"Effettuata lettura da DB per LicenzeNextGetFilt: {ts.TotalMilliseconds} ms"); return await Task.FromResult(dbResult); } public async Task LicenzeNextUpdate(DB.DBModels.LicenzaModel currItem) { bool done = false; // chiamo Log licenza + update insieme try { done = dbControllerNext.UpsertLicenza(currItem); await InvalidateAllCache(); } catch (Exception exc) { Log.Error($"Eccezione in ApplicazioniUpdate:{Environment.NewLine}{exc}"); } return await Task.FromResult(done); } public void rollBackEditGLS(object item) { dbControllerGLS.rollBackEntity(item); } public async Task SendEmail(string destEmail, string oggetto, string corpo) { bool answ = false; try { await _emailSender.SendEmailAsync(destEmail, oggetto, corpo); answ = true; } catch { } return answ; } /// /// Aggiornamentos tato ticket /// /// /// /// public async Task TicketUpdateState(int IdxTicket, StatoRichiesta NewStatus) { bool fatto = false; // inserimento! Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); fatto = dbControllerNext.TicketUpdateState(IdxTicket, NewStatus); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Trace($"Effettuata update con TicketUpdateState: {ts.TotalMilliseconds} ms"); // restituisce elenco return await Task.FromResult(fatto); } #endregion Public Methods } }