using Core; using Core.DTO; using LiMan.DB.DBModels; using LiMan.DB.DTO; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using NLog; using Org.BouncyCastle.Asn1.Crmf; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using static Core.Enum; namespace LiMan.DB.Controllers { public class DbController : IDisposable { #region Public Constructors public DbController(IConfiguration configuration) { _configuration = configuration; } #endregion Public Constructors #region Public Methods /// /// Upsert record applicativo /// /// /// public bool ApplicativoUpsert(ApplicativoModel upRec) { bool fatto = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { // verifico record esistente var currRec = localDbCtx .DbSetApp .Where(x => x.CodApp == upRec.CodApp) .FirstOrDefault(); if (currRec != null) { currRec.CodApp = upRec.CodApp; currRec.Descrizione = upRec.Descrizione; currRec.TplConnString = upRec.TplConnString; } else { localDbCtx .DbSetApp .Add(upRec); } localDbCtx.SaveChanges(); fatto = true; } catch (Exception exc) { Log.Error($"Errore in ApplicativoUpsert{Environment.NewLine}{exc}"); } } return fatto; } /// /// Verifica se una applcazione abbia record correlati... /// /// /// public bool ApplicazioniHasChild(string CodApp) { bool answ = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { // in primis deve esserci un record che possa essere collegato ApplicativoModel currRec = localDbCtx .DbSetApp .Where(x => x.CodApp == CodApp) .FirstOrDefault(); if (currRec != null) { // controllo: NON ci devono essere record correlati in licenze, revisioni... int numLic = localDbCtx .DbSetLicenze .Where(x => x.CodApp == CodApp) .Count(); int numLogLic = localDbCtx .DbSetLogLicenze .Where(x => x.CodApp == CodApp) .Count(); int numRel = localDbCtx .DbSetReleases .Where(x => x.CodApp == CodApp) .Count(); // procedo solo se non ho record collegati answ = numLic + numLogLic + numRel > 0; } } catch (Exception exc) { Log.Error($"Eccezione in ApplicazioniHasChild:{Environment.NewLine}{exc}"); } } return answ; } /// /// Elimina il record indicato (se non ci sono record correlati...) /// /// /// public bool ApplicazioniNextDelete(ApplicativoModel rec2del) { bool done = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { ApplicativoModel currRec = localDbCtx .DbSetApp .Where(x => x.CodApp == rec2del.CodApp) .FirstOrDefault(); if (currRec != null) { localDbCtx .DbSetApp .Remove(currRec); localDbCtx.SaveChanges(); done = true; } } catch (Exception exc) { Log.Error($"Eccezione in ApplicazioniNextDelete:{Environment.NewLine}{exc}"); } } return done; } public bool ApplicazioniNextUpdate(ApplicativoModel updItem) { bool done = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { ApplicativoModel currData = localDbCtx .DbSetApp .Where(x => x.CodApp == updItem.CodApp) .FirstOrDefault(); if (currData != null) { // aggiorno valori currData.Descrizione = updItem.Descrizione; currData.Tipo = updItem.Tipo; currData.TplConnString = updItem.TplConnString; localDbCtx.Entry(currData).State = EntityState.Modified; } else { localDbCtx .DbSetApp .Add(updItem); } localDbCtx.SaveChanges(); done = true; } catch (Exception exc) { Log.Error($"Eccezione in ApplicazioniNextUpdate:{Environment.NewLine}{exc}"); } } return done; } /// /// Elimino una licenza da quelle attivate (SE scaduto veto) /// /// Dizionario delle Licenze da eliminare /// Chiave Master public bool AttivazioniDelete(Dictionary ParamDict, string MasterKey) { bool fatto = false; LicenzaModel mainLic = new LicenzaModel(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; List items2del = new List(); // ciclo x ogni licenze a vedere SE sia eliminabile... foreach (var item in ParamDict) { // calcolo DTO Attivazione var itemsTgt = localDbCtx .DbSetSubLicenze .Where(x => x.CodImpiego == item.Key && x.Chiave == item.Value && x.LicenzaNav.Chiave == MasterKey && x.VetoUnlock <= oggi) .ToList(); // se trovate aggiungo ad elenco... if (itemsTgt != null && itemsTgt.Count > 0) { items2del.AddRange(itemsTgt); } } // se ho qualcosa procedo... if (items2del != null && items2del.Count > 0) { localDbCtx .DbSetSubLicenze .RemoveRange(items2del); // salvo localDbCtx.SaveChanges(); fatto = true; } } return fatto; } public bool AttivazioniDelete(int idxSubLic) { bool fatto = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // recupero record var currData = localDbCtx .DbSetSubLicenze .Where(x => x.IdxSubLic == idxSubLic) .FirstOrDefault(); // se ho qualcosa procedo... if (currData != null) { localDbCtx.DbSetSubLicenze.Remove(currData); // salvo localDbCtx.SaveChanges(); fatto = true; } } return fatto; } /// /// Lista attivfazioni x licenza /// /// /// public List AttivazioniGetByLic(int idxLic) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; dbResult = localDbCtx .DbSetSubLicenze .Where(x => x.IdxLic == idxLic) .OrderBy(o => o.VetoUnlock) .ToList(); } return dbResult; } /// /// Elimino le licenze con veto scaduto /// /// Chiave Master public bool AttivazioniResetAvail(string MasterKey) { bool fatto = false; LicenzaModel mainLic = new LicenzaModel(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; // calcolo DTO Attivazione var item2Del = localDbCtx .DbSetSubLicenze .Where(x => x.LicenzaNav.Chiave == MasterKey && x.VetoUnlock < oggi) .ToList(); // se ho qualcosa procedo... if (item2Del != null && item2Del.Count > 0) { localDbCtx .DbSetSubLicenze .RemoveRange(item2Del); // salvo localDbCtx.SaveChanges(); } // comunque true se ci ha provato fatto = true; } return fatto; } /// /// Cerca di aggiungere sul DB le attivazioni richieste /// /// Master Lic /// Elenco codici impiego (key) + valori in formato dizionari /// num gg di veto da impostare /// public bool AttivazioniTryAdd(string MasterKey, Dictionary ParamDict, int numDayVeto, TipoLicenza tipoLic) { bool answ = false; // verifica se si può procedere... var licenza = GetLicenza(MasterKey); if (licenza != null) { var attivList = GetAttivazioniByLic(licenza.IdxLic, false); // elimino dall'elenco parametri le licenze già presenti... Dictionary Par2Rem = new Dictionary(); foreach (var item in ParamDict) { var currRec = attivList.FirstOrDefault(x => x.CodImpiego == item.Key && x.Chiave == item.Value); // se c'è segno che è da eliminare... if (currRec != null && currRec.CodImpiego == item.Key) { Par2Rem.Add(item.Key, item.Value); } } // elimino da elenco parametri quelli che sono da eliminare... if (Par2Rem.Count > 0) { foreach (var item in Par2Rem) { ParamDict.Remove(item.Key); } } // controllo se ho ancora qualcosa da aggiungere... if (ParamDict.Count > 0) { if (licenza.IsValid && (licenza.NumLicenze >= (attivList.Count + ParamDict.Count))) { DateTime oggi = DateTime.Today; DateTime vetoDate = oggi.AddDays(numDayVeto); using (LMDbContext dbCtx = new LMDbContext(_configuration)) { try { // cerco eventuali licenze preesistenti (per CodImp) e le elimino SE // sono libere... List list2rem = new List(); foreach (var item in ParamDict) { var rec2del = dbCtx .DbSetSubLicenze .Where(x => x.CodImpiego == item.Key && x.VetoUnlock <= oggi) .FirstOrDefault(); if (rec2del != null) { list2rem.Add(rec2del); } } // se ce ne sono rimuovo e salvo... if (list2rem != null && list2rem.Count > 0) { dbCtx .DbSetSubLicenze .RemoveRange(list2rem); dbCtx.SaveChanges(); } // genero subLicenze... var newRec = ParamDict .Select(x => new SubLicenzaModel() { IdxLic = licenza.IdxLic, CodImpiego = x.Key, VetoUnlock = vetoDate, Tipo = tipoLic, Chiave = x.Value }) .ToList(); dbCtx .DbSetSubLicenze .AddRange(newRec); dbCtx.SaveChanges(); } catch (Exception exc) { Log.Error($"Errore in AttivazioniTryAdd per MasterKey {MasterKey} | tipo: {tipoLic} | #rec: {ParamDict.Count}{Environment.NewLine}{exc}"); } } } } } return answ; } /// /// Cerca di aggiornare le authKey sul DB x le chiavi /// /// Master Lic /// Elenco codici impiego (key) + valori in formato dizionari /// public bool AttivazioniTryRefresh(string MasterKey, Dictionary ParamDict) { bool answ = false; // verifica se si può procedere... var licenza = GetLicenza(MasterKey); if (licenza != null) { var attivList = GetAttivazioniByLic(licenza.IdxLic, false); if (licenza.IsValid) { using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { // ciclo ed aggiorno foreach (var item in ParamDict) { var currRec = localDbCtx .DbSetSubLicenze .Where(x => x.CodImpiego == item.Key) .FirstOrDefault(); if (currRec != null) { currRec.Chiave = item.Value; } } // salvo! localDbCtx.SaveChanges(); } catch (Exception exc) { Log.Error($"Errore in AttivazioniTryRefresh per ComKey {MasterKey} | #rec: {ParamDict.Count}{Environment.NewLine}{exc}"); } } } } return answ; } public bool AttivazioniUnlock(int idxSubLic) { bool fatto = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; // recupero record var currData = localDbCtx .DbSetSubLicenze .Where(x => x.IdxSubLic == idxSubLic && x.VetoUnlock > oggi) .FirstOrDefault(); // se ho qualcosa procedo... if (currData != null) { currData.VetoUnlock = oggi; localDbCtx.Entry(currData).State = EntityState.Modified; // salvo localDbCtx.SaveChanges(); // true fatto = true; } } return fatto; } public List AuthClaimByUserID(int userID) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; dbResult = localDbCtx .DbSetClaims .Where(x => x.UserID == userID) .ToList(); } return dbResult; } public List AuthClaimByUserName(string userName) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; dbResult = localDbCtx .DbSetClaims .Where(x => x.UserNav.Username == userName) .Include(r => r.RoleNav) .ToList(); } return dbResult; } public bool AuthClaimRemove(AuthClaimModel rec2del) { bool answ = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { var currData = localDbCtx .DbSetClaims .Where(x => x.ClaimID == rec2del.ClaimID) .FirstOrDefault(); if (currData != null) { localDbCtx .DbSetClaims .Remove(currData); } localDbCtx.SaveChanges(); answ = true; } catch (Exception exc) { Log.Error($"Errore in AuthClaimRemove | RoleID: {rec2del.RoleID} | UserId: {rec2del.UserID}{Environment.NewLine}{exc}"); } } return answ; } public bool AuthClaimUpsert(AuthClaimModel newRec) { bool answ = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { var currData = localDbCtx .DbSetClaims .Where(x => x.ClaimID == newRec.ClaimID) .FirstOrDefault(); if (currData != null) { currData.UserID = newRec.UserID; currData.RoleID = newRec.RoleID; currData.DtMod = DateTime.Now; // segno aggiornato localDbCtx.Entry(currData).State = EntityState.Modified; } else { localDbCtx .DbSetClaims .Add(newRec); } localDbCtx.SaveChanges(); answ = true; } catch (Exception exc) { Log.Error($"Errore in AuthClaimUpsert | ClaimID: {newRec.ClaimID} | UserID: {newRec.UserID} | RoleID: {newRec.RoleID}{Environment.NewLine}{exc}"); } } return answ; } /// /// Rimozione di ogni Role Claim x utente (che diventa inattivo) /// /// /// public bool AuthRoleResetUser(int UserId) { bool answ = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { var currData = localDbCtx .DbSetClaims .Where(x => x.UserID == UserId) .ToList(); if (currData != null) { // rimuovo intero range... localDbCtx .DbSetClaims .RemoveRange(currData); } localDbCtx.SaveChanges(); answ = true; } catch (Exception exc) { Log.Error($"Errore in AuthUserRemoveRoles | UserId: {UserId}{Environment.NewLine}{exc}"); } } return answ; } public List AuthRolesGetAll() { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetRoles .ToList(); } return dbResult; } public bool AuthRoleUpsert(AuthRoleModel newRec) { bool answ = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { var currData = localDbCtx .DbSetRoles .Where(x => x.RoleID == newRec.RoleID) .FirstOrDefault(); if (currData != null) { currData.Descrizione = newRec.Descrizione; currData.Ruolo = newRec.Ruolo; // segno aggiornato localDbCtx.Entry(currData).State = EntityState.Modified; } else { localDbCtx .DbSetRoles .Add(newRec); } localDbCtx.SaveChanges(); answ = true; } catch (Exception exc) { Log.Error($"Errore in AuthRoleUpsert | RoleID: {newRec.RoleID} | Ruolo: {newRec.Ruolo}{Environment.NewLine}{exc}"); } } return answ; } public List AuthUserAll() { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetUsers .Include(c => c.Claims) .ThenInclude(r => r.RoleNav) .ToList(); } return dbResult; } public List AuthUserGetFilt(string userName) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetUsers .Where(x => x.Username == userName) .ToList(); } return dbResult; } public bool AuthUserUpsert(AuthUserModel newRec) { bool answ = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { var currData = localDbCtx .DbSetUsers .Where(x => x.UserID == newRec.UserID) .FirstOrDefault(); if (currData != null) { currData.Username = newRec.Username; currData.AD_Domain = newRec.AD_Domain; currData.AD_User = newRec.AD_User; currData.Cognome = newRec.Cognome; currData.Nome = newRec.Nome; // segno aggiornato localDbCtx.Entry(currData).State = EntityState.Modified; } else { localDbCtx .DbSetUsers .Add(newRec); } localDbCtx.SaveChanges(); answ = true; } catch (Exception exc) { Log.Error($"Errore in AuthUserUpsert | UserID: {newRec.UserID} | userName: {newRec.Username}{Environment.NewLine}{exc}"); } } return answ; } public bool DbForceMigrate() { bool answ = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { localDbCtx.DbForceMigrate(); answ = true; } catch (Exception exc) { Log.Error($"Eccezione in DbForceMigrate{Environment.NewLine}{exc}"); } } return answ; } public void Dispose() { // Clear database context //Log.Info("Dispose di GWMSController"); } /// /// Elimino una richiesta enroll (anche se già approvata...) /// /// licId record da eliminare public bool EnrollReqDelete(int idReq) { bool fatto = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // se trovo... procedo... var rec2del = localDbCtx .DbSetEnrollReq .Where(x => x.IdReq == idReq) .FirstOrDefault(); if (rec2del != null) { localDbCtx .DbSetEnrollReq .Remove(rec2del); // salvo localDbCtx.SaveChanges(); fatto = true; } } return fatto; } /// /// Elenco Enroll Attivi (non completati/cancellati) /// /// public List EnrollReqGetActive() { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetEnrollReq .Where(x => x.DtAppr == null) .OrderByDescending(x => x.DtReq) .ToList(); } return dbResult; } /// /// Elenco completo Enroll Req /// /// public List EnrollReqGetAll() { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetEnrollReq .OrderByDescending(x => x.DtReq) .ToList(); } return dbResult; } /// /// Recupero richiesta da licId (oppure empty...) /// /// /// public EnrollRequestModel EnrollReqGetById(int idReq) { EnrollRequestModel dbResult = new EnrollRequestModel(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetEnrollReq .FirstOrDefault(x => x.IdReq == idReq); } return dbResult; } /// /// Elenco filtrato Enroll Req x data /// /// /// /// public List EnrollReqGetFilt(DateTime dtFrom, DateTime dtTo) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetEnrollReq .Where(x => x.DtReq >= dtFrom && x.DtReq <= dtTo) .OrderByDescending(x => x.DtReq) .ToList(); } return dbResult; } /// /// Elimino eventuali richieste non approvate e scadute /// public bool EnrollReqPurgeInvalid() { bool fatto = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { List item2del = new List(); // cerco in primis richieste NON associate a licenza var list2check = localDbCtx .DbSetEnrollReq .Where(x => x.IdxLic == 0) .ToList(); var list2del = list2check .Where(x => x.IsScaduta) .ToList(); if (list2del != null) { localDbCtx .DbSetEnrollReq .RemoveRange(list2del); // salvo int numDone = localDbCtx.SaveChanges(); fatto = numDone != 0; } } return fatto; } /// /// Upsert record richiesta enroll /// /// /// public int EnrollReqUpsert(EnrollRequestModel newRec) { int answ = 0; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { var currData = localDbCtx .DbSetEnrollReq .Where(x => x.IdReq == newRec.IdReq && newRec.IdReq > 0) .FirstOrDefault(); if (currData != null) { currData.Passcode = newRec.Passcode; currData.ReqPayload = newRec.ReqPayload; currData.DtReq = newRec.DtReq; currData.DtAppr = newRec.DtAppr; currData.UserAppr = newRec.UserAppr; currData.IdxLic = newRec.IdxLic; // segno aggiornato localDbCtx.Entry(currData).State = EntityState.Modified; localDbCtx.SaveChanges(); answ = newRec.IdReq; } else { var result = localDbCtx .DbSetEnrollReq .Add(newRec); localDbCtx.SaveChanges(); answ = newRec.IdReq; } } catch (Exception exc) { Log.Error($"Errore in EnrollReqUpsert | Passcode: {newRec.Passcode} | DtReq: {newRec.DtReq}{Environment.NewLine}{exc}"); } } return answ; } /// /// Elenco files attach da registrare /// /// Identificativo del ticket /// Directory di salvataggio dei file /// lista risultati della funzione di upload /// public bool FileAdd(int idxTicket, string baseDir, List fileUploaded) { bool fatto = false; if (fileUploaded == null || fileUploaded.Count == 0) { Log.Error("Errore FileAdd: fileUploaded è vuoto/nullo"); } else { using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // verifico Ticket sia esistente var currTicket = localDbCtx .DbSetTicket .Where(x => x.IdxTicket == idxTicket) .FirstOrDefault(); if (currTicket != null) { var newFiles = fileUploaded .Select(x => new FileAttachModel() { IdxTicket = idxTicket, OriginalName = x.FileName, StorageName = x.StoredFileName, DtEvent = DateTime.Now, FullStoragePath = Path.Combine(baseDir, x.StoredFileName) }).ToList(); localDbCtx .DbSetFileAttach .AddRange(newFiles); localDbCtx.SaveChanges(); fatto = true; } } } return fatto; } /// /// Elenco file registrati dato ticket id /// /// Identificativo del ticket /// public List FileGetFilt(int idxTicket) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // recupero locenza... dbResult = localDbCtx .DbSetFileAttach .Where(x => x.IdxTicket == idxTicket) .ToList(); } return dbResult; } /// /// Elenco applicativi in scadenza nel periodo considerato (min-max) /// /// Data iniziale da considerare /// Data finale da considerare /// public List GetApplicativiExpiring(DateTime minDate, DateTime maxDate) { // cerco solo applicativi attivi bool hideData = true; List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; // generazione stringhe casuali.... https://jonathancrozier.com/blog/how-to-generate-a-random-string-with-c-sharp StringBuilder sbRandChiave = new StringBuilder(); StringBuilder sbRandEnigma = new StringBuilder(); StringBuilder sbRandPayload = new StringBuilder(); string stdChiave = ""; string stdEnigma = ""; string stdPayLoad = ""; int stdIdxLic = 0; DateTime stdDataEnigma = DateTime.Today; if (hideData) { int numChar = 80; Random random = new Random(); // idxLic stdIdxLic = random.Next(50000, 100000); // chiave random for (int i = 0; i < numChar; i++) { // Generate floating point numbers double myFloat = random.NextDouble(); // Generate the char using below logic var myChar = Convert.ToChar(Convert.ToInt32(Math.Floor(25 * myFloat) + 65)); sbRandChiave.Append(myChar); } stdChiave = $"{sbRandChiave}"; // random data enigma stdDataEnigma = DateTime.Today.AddDays(random.Next(0, 15)); // random enigma for (int i = 0; i < numChar; i++) { // Generate floating point numbers double myFloat = random.NextDouble(); // Generate the char using below logic var myChar = Convert.ToChar(Convert.ToInt32(Math.Floor(25 * myFloat) + 65)); sbRandEnigma.Append(myChar); } stdEnigma = $"{sbRandEnigma}"; // random payload for (int i = 0; i < numChar; i++) { // Generate floating point numbers double myFloat = random.NextDouble(); // Generate the char using below logic var myChar = Convert.ToChar(Convert.ToInt32(Math.Floor(25 * myFloat) + 65)); sbRandPayload.Append(myChar); } stdPayLoad = $"{sbRandPayload}"; } // calcolo DTO applicativi dbResult = localDbCtx .DbSetLicenze .Where(x => (x.Scadenza >= minDate && x.Scadenza < maxDate)) .OrderBy(o => o.Scadenza) .Select(x => new ApplicativoDTO() { IdxLic = hideData ? stdIdxLic : x.IdxLic, Chiave = hideData ? stdChiave : x.Chiave, CodApp = x.CodApp, CodInst = x.CodInst, Descrizione = x.Descrizione, Tipo = x.Tipo, Scadenza = x.Scadenza, NumLicenze = x.NumLicenze, NumLicenzeAttive = -1, DataEnigma = hideData ? stdDataEnigma : x.DataEnigma, Enigma = hideData ? stdEnigma : x.Enigma, Payload = hideData ? stdPayLoad : x.Payload }) .ToList(); } return dbResult; } public List GetApplicativiFilt(bool OnlyActive, string CodApp, string CodInst, bool hideData) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; // generazione stringhe casuali.... https://jonathancrozier.com/blog/how-to-generate-a-random-string-with-c-sharp StringBuilder sbRandChiave = new StringBuilder(); StringBuilder sbRandEnigma = new StringBuilder(); StringBuilder sbRandPayload = new StringBuilder(); string stdChiave = ""; string stdEnigma = ""; string stdPayLoad = ""; int stdIdxLic = 0; DateTime stdDataEnigma = DateTime.Today; if (hideData) { int numChar = 80; Random random = new Random(); // idxLic stdIdxLic = random.Next(50000, 100000); // chiave random for (int i = 0; i < numChar; i++) { // Generate floating point numbers double myFloat = random.NextDouble(); // Generate the char using below logic var myChar = Convert.ToChar(Convert.ToInt32(Math.Floor(25 * myFloat) + 65)); sbRandChiave.Append(myChar); } stdChiave = $"{sbRandChiave}"; // random data enigma stdDataEnigma = DateTime.Today.AddDays(random.Next(0, 15)); // random enigma for (int i = 0; i < numChar; i++) { // Generate floating point numbers double myFloat = random.NextDouble(); // Generate the char using below logic var myChar = Convert.ToChar(Convert.ToInt32(Math.Floor(25 * myFloat) + 65)); sbRandEnigma.Append(myChar); } stdEnigma = $"{sbRandEnigma}"; // random payload for (int i = 0; i < numChar; i++) { // Generate floating point numbers double myFloat = random.NextDouble(); // Generate the char using below logic var myChar = Convert.ToChar(Convert.ToInt32(Math.Floor(25 * myFloat) + 65)); sbRandPayload.Append(myChar); } stdPayLoad = $"{sbRandPayload}"; } // conteggio preliminare licenze impiegate var countSubLic = localDbCtx .DbSetSubLicenze .GroupBy(x => x.IdxLic) .Select(g => new { IdxLic = g.Key, NumLic = g.Count() }); // calcolo DTO applicativi dbResult = localDbCtx .DbSetLicenze .Where(x => (x.CodApp == CodApp || string.IsNullOrEmpty(CodApp)) && (x.CodInst == CodInst || string.IsNullOrEmpty(CodInst)) && (!OnlyActive || x.Scadenza > oggi)) .OrderByDescending(o => o.Scadenza) .Select(x => new ApplicativoDTO() { IdxLic = hideData ? stdIdxLic : x.IdxLic, Chiave = hideData ? stdChiave : x.Chiave, CodApp = x.CodApp, CodInst = x.CodInst, Descrizione = x.Descrizione, Tipo = x.Tipo, Scadenza = x.Scadenza, NumLicenze = x.NumLicenze, NumLicenzeAttive = countSubLic.Where(s => s.IdxLic == x.IdxLic).Select(c => c.NumLic).FirstOrDefault(), DataEnigma = hideData ? stdDataEnigma : x.DataEnigma, Enigma = hideData ? stdEnigma : x.Enigma, Payload = hideData ? stdPayLoad : x.Payload }) .ToList(); } return dbResult; } public List GetApplicazioni() { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetApp .ToList(); } return dbResult; } public ApplicativoModel GetApplicazioniFilt(string codApp) { ApplicativoModel dbResult = new ApplicativoModel(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { var rawData = localDbCtx .DbSetApp .Where(x => x.CodApp == codApp) .FirstOrDefault(); if (rawData != null) { dbResult = rawData; } } return dbResult; } public AttivazioneDTO GetAttivazione(string Chiave, string CodImpiego, bool hideData) { AttivazioneDTO dbResult = new AttivazioneDTO(); LicenzaModel mainLic = new LicenzaModel(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; int stdIdxLic = 0; // generazione stringhe casuali.... https://jonathancrozier.com/blog/how-to-generate-a-random-string-with-c-sharp StringBuilder sbRandChiave = new StringBuilder(); string stdChiave = ""; if (hideData) { int numChar = 80; Random random = new Random(); // idxLic stdIdxLic = random.Next(50000, 100000); // chiave random for (int i = 0; i < numChar; i++) { // Generate floating point numbers double myFloat = random.NextDouble(); // Generate the char using below logic var myChar = Convert.ToChar(Convert.ToInt32(Math.Floor(25 * myFloat) + 65)); sbRandChiave.Append(myChar); } stdChiave = $"{sbRandChiave}"; } else { // recupero se c'è licenza master mainLic = localDbCtx .DbSetLicenze .Where(x => x.Chiave == Chiave) .FirstOrDefault(); } // calcolo DTO applicativi dbResult = localDbCtx .DbSetSubLicenze .Where(x => x.LicenzaNav.Chiave == Chiave && x.CodImpiego == CodImpiego) .OrderBy(o => o.VetoUnlock) .Select(x => new AttivazioneDTO() { IdxLic = hideData ? stdIdxLic : x.IdxLic, IdxSubLic = x.IdxSubLic, CodImpiego = x.CodImpiego, CodApp = mainLic.CodApp, CodInst = mainLic.CodInst, Descrizione = mainLic.Descrizione, Tipo = x.Tipo, Chiave = hideData ? stdChiave : x.Chiave, VetoUnlock = x.VetoUnlock }) .FirstOrDefault(); } return dbResult; } /// /// Recupero da DB le attivazioni richieste /// /// Idx Licenza /// Indica se generare rand parametri sensibili public List GetAttivazioniByLic(int IdxLic, bool hideData) { List dbResult = new List(); LicenzaModel mainLic = new LicenzaModel(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; int stdIdxLic = 0; // generazione stringhe casuali.... https://jonathancrozier.com/blog/how-to-generate-a-random-string-with-c-sharp StringBuilder sbRandChiave = new StringBuilder(); string stdChiave = ""; if (hideData) { int numChar = 80; Random random = new Random(); // idxLic stdIdxLic = random.Next(50000, 100000); // chiave random for (int i = 0; i < numChar; i++) { // Generate floating point numbers double myFloat = random.NextDouble(); // Generate the char using below logic var myChar = Convert.ToChar(Convert.ToInt32(Math.Floor(25 * myFloat) + 65)); sbRandChiave.Append(myChar); } stdChiave = $"{sbRandChiave}"; } else { // recupero se c'è licenza master mainLic = localDbCtx .DbSetLicenze .Where(x => x.IdxLic == IdxLic) .FirstOrDefault(); } // calcolo DTO Attivazione dbResult = localDbCtx .DbSetSubLicenze .Where(x => x.IdxLic == IdxLic) .Select(x => new AttivazioneDTO() { IdxLic = hideData ? stdIdxLic : x.IdxLic, IdxSubLic = x.IdxSubLic, CodImpiego = x.CodImpiego, CodApp = mainLic.CodApp, CodInst = mainLic.CodInst, Descrizione = mainLic.Descrizione, Tipo = x.Tipo, Chiave = hideData ? stdChiave : x.Chiave, VetoUnlock = x.VetoUnlock }) .ToList(); } return dbResult; } public List GetInstallazioni() { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetInst .ToList(); } return dbResult; } public LicenzaModel GetLicenza(int IdxLic) { LicenzaModel dbResult = new LicenzaModel(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetLicenze .Where(x => x.IdxLic == IdxLic) .FirstOrDefault(); } return dbResult; } public LicenzaModel GetLicenza(string MasterKey) { LicenzaModel dbResult = new LicenzaModel(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetLicenze .Where(x => x.Chiave == MasterKey) .FirstOrDefault(); } return dbResult; } public List GetLicenze() { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetLicenze .ToList(); } return dbResult; } public List GetLicenzeFilt(bool OnlyActive, string CodApp, string CodInst) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; dbResult = localDbCtx .DbSetLicenze .Where(x => (x.CodApp == CodApp || string.IsNullOrEmpty(CodApp)) && (x.CodInst == CodInst || string.IsNullOrEmpty(CodInst)) && (!OnlyActive || x.Scadenza > oggi)) .Include(a => a.ApplicativoNav) .Include(a => a.Attivazioni) .Include(t => t.Tickets.Where(c => c.Status < StatoRichiesta.Approvata)) .OrderByDescending(o => o.Scadenza) .ToList(); } return dbResult; } /// /// Effettua refresh del payload della licenza dato info + enigma generato dal client /// /// /// /// /// /// public Task LicenseUpdatePayload(string codInst, string codApp, string masterKey, string enigma) { bool fatto = false; string newPayload = ""; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { LicenzaModel mainLic = localDbCtx .DbSetLicenze .Where(x => x.CodApp == codApp && x.CodInst == codInst && x.Chiave == masterKey) .Include(a => a.Attivazioni) .FirstOrDefault(); if (mainLic != null) { // se ho attivazioni... if (mainLic.Attivazioni != null && mainLic.Attivazioni.Count > 0) { // se ho trovato --> recupero info applicazioni.... var hashList = mainLic .Attivazioni .OrderBy(x => x.CodImpiego) .Select(x => x.CodImpiego) .ToList(); // costruisco stringa da elenco impieghi... StringBuilder sb = new StringBuilder(); foreach (var item in hashList) { sb.AppendLine(item); } string rawData = sb.ToString(); // hashing! using (var md5 = MD5.Create()) { byte[] InputBytes = Encoding.UTF8.GetBytes(rawData); var byteHash = md5.ComputeHash(InputBytes); newPayload = BitConverter.ToString(byteHash).Replace("-", "").ToLowerInvariant(); } } else { // tengo vecchio payload newPayload = mainLic.Payload; } // salvo info! mainLic.Enigma = enigma; mainLic.DataEnigma = DateTime.Now; mainLic.Payload = newPayload; // indico modificato localDbCtx.Entry(mainLic).State = EntityState.Modified; // salvo localDbCtx.SaveChanges(); fatto = true; } } // restituisco fatto return Task.FromResult(fatto); } /// /// Record licenza da ID /// /// /// public LicenzaModel LicenzaById(int licId) { LicenzaModel dbResult = new LicenzaModel(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; dbResult = localDbCtx .DbSetLicenze .FirstOrDefault(x => x.IdxLic == licId); } return dbResult; } /// /// Record licenza da MasterKey /// /// /// public LicenzaModel LicenzaByKey(string MasterKey) { LicenzaModel dbResult = new LicenzaModel(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime oggi = DateTime.Today; dbResult = localDbCtx .DbSetLicenze .FirstOrDefault(x => x.Chiave == MasterKey); } return dbResult; } /// /// Elenco LOG chiamate all'API dato filtro + limite record /// /// /// /// /// /// public List LogCallGetFilt(string CodApp, string CodInst, DateTime DateMax, int maxNumRec = 360) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // recupero lista... dbResult = localDbCtx .DbSetLogCall .Where(x => x.CodApp == CodApp && x.CodInst == CodInst && x.DataRif <= DateMax) .OrderByDescending(x => x.DataRif) .Take(maxNumRec) .ToList(); } return dbResult; } /// /// Update/insert record Loc chiamate API /// /// /// public async Task LogCallUpsert(LogCallModel currRequest) { bool fatto = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // cerco record esistente... var currRec = localDbCtx .DbSetLogCall .Where(x => x.CodApp == currRequest.CodApp && x.CodInst == currRequest.CodInst && x.DataRif == currRequest.DataRif && x.TargetUrl == currRequest.TargetUrl) .FirstOrDefault(); if (currRec != null) { // se trovo aggiorno currRec.NumCall = currRequest.NumCall; } else { //altrimenti aggiungo localDbCtx .DbSetLogCall .Add(currRequest); } // salvo await localDbCtx.SaveChangesAsync(); fatto = true; } return fatto; } public bool ReleaseDelete(ReleaseModel rec2del) { bool fatto = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // cerco record esistente... var currRec = localDbCtx .DbSetReleases .Where(x => x.IdxRel == rec2del.IdxRel && rec2del.IdxRel > 0) .FirstOrDefault(); if (currRec != null) { localDbCtx .DbSetReleases .Remove(currRec); // salvo localDbCtx.SaveChanges(); } fatto = true; } return fatto; } /// /// Elenco release (completo) dato un applicativo /// /// Codice applicativo /// public List ReleaseDtoGetByApp(string CodApp) { List dbResult = new List(); var rawData = ReleaseGetByApp(CodApp); dbResult = rawData .Where(x => x.IsReleased) .Select(x => new ReleaseDTO() { CodApp = x.CodApp, ReleaseDate = x.ReleaseDate, VersNum = x.VersNum, VersText = x.VersText, VersVal = x.VersVal, RelTags = x.RelTags }). ToList(); return dbResult; } /// /// Elenco release (completo) dato un applicativo applicativi /// /// Codice applicativo /// Versione minima richiesta /// public List ReleaseDtoGetByAppVers(string CodApp, string MinVers) { List dbResult = new List(); var rawData = ReleaseGetByAppVers(CodApp, MinVers); dbResult = rawData .Where(x => x.IsReleased) .Select(x => new ReleaseDTO() { CodApp = x.CodApp, ReleaseDate = x.ReleaseDate, VersNum = x.VersNum, VersText = x.VersText, VersVal = x.VersVal, RelTags = x.RelTags }). ToList(); return dbResult; } /// /// Elenco release (completo) dato un applicativo applicativi /// /// Codice applicativo /// Versione minima richiesta /// Versione massima consentita /// public List ReleaseDtoGetByAppVersLimit(string CodApp, string VersMin, string VersMax) { List dbResult = new List(); Version versLimit = new Version(VersMax); var rawData = ReleaseGetByAppVers(CodApp, VersMin); dbResult = rawData .Where(x => x.IsReleased) .Select(x => new ReleaseDTO() { CodApp = x.CodApp, ReleaseDate = x.ReleaseDate, VersNum = x.VersNum, VersText = x.VersText, VersVal = x.VersVal, RelTags = x.RelTags, IsPermitted = x.VersVal <= versLimit }). ToList(); return dbResult; } /// /// Elenco release (completo) dato un applicativo applicativi /// /// Codice applicativo /// public List ReleaseGetByApp(string CodApp) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // calcolo DTO applicativi dbResult = localDbCtx .DbSetReleases .Where(x => (x.CodApp.ToLower() == CodApp.ToLower())) .OrderBy(o => o.ReleaseDate) .ToList(); } return dbResult; } /// /// Elenco release (completo) dato un applicativo applicativi /// /// Codice applicativo /// Versione minima richiesta /// public List ReleaseGetByAppVers(string CodApp, string MinVers) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { Version mVers = new Version(MinVers); // calcolo DTO applicativi dbResult = localDbCtx .DbSetReleases .Where(x => (x.CodApp.ToLower() == CodApp.ToLower())) .ToList(); // verifico per il criterio versione... dbResult = dbResult .Where(x => x.VersVal >= mVers) .OrderBy(o => o.ReleaseDate) .ToList(); } return dbResult; } /// /// Elenco di TUTTE le release CRITICAL come dizionario CodApp - release /// /// Codice applicativo /// public Dictionary ReleaseGetCritical() { Dictionary dbResult = new Dictionary(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { DateTime adesso = DateTime.Now; var rawList = localDbCtx .DbSetReleases .Where(x => x.ReleaseDate <= adesso) .GroupBy(x => x.CodApp) .Select(g => new { key = g.Key, val = g.Where(x => x.ReleaseDate <= adesso) .ToList() }) .ToDictionary(x => x.key, x => x.val); // ordinamento per VERO numero versione è fatto in ram --> devo riordinare qui... var dictLast = rawList.ToDictionary(x => x.Key, x => x.Value.OrderByDescending(v => v.VersVal).FirstOrDefault()); // ora prendo SOLO quelli critical dbResult = dictLast .Where(x => x.Value.RelTags == "CRITICAL") .ToDictionary(x => x.Key, x => new ReleaseDTO() { CodApp = x.Value.CodApp, ReleaseDate = x.Value.ReleaseDate, VersText = x.Value.VersText, VersNum = x.Value.VersNum, VersVal = x.Value.VersVal, RelTags = x.Value.RelTags }); } return dbResult; } /// /// Upsert Record Release /// /// /// public async Task ReleaseUpsert(ReleaseModel currItem) { bool fatto = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // cerco record esistente... var currRec = localDbCtx .DbSetReleases .Where(x => (x.IdxRel == currItem.IdxRel && currItem.IdxRel > 0) || (x.CodApp == currItem.CodApp && x.VersNum == currItem.VersNum && x.VersText == currItem.VersText)) .FirstOrDefault(); if (currRec != null) { // se trovo aggiorno currRec.VersNum = currItem.VersNum; currRec.VersText = currItem.VersText; currRec.ReleaseDate = currItem.ReleaseDate; currRec.RelTags = currItem.RelTags; localDbCtx.Entry(currRec).State = EntityState.Modified; } else { // altrimenti aggiungo localDbCtx .DbSetReleases .Add(currItem); } // salvo await localDbCtx.SaveChangesAsync(); fatto = true; } return fatto; } /// /// Annulla modifiche su una specifica entity (cancel update) /// /// /// public bool rollBackEntity(object item) { bool answ = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { if (localDbCtx.Entry(item).State == EntityState.Deleted || localDbCtx.Entry(item).State == EntityState.Modified) { localDbCtx.Entry(item).Reload(); } } catch (Exception exc) { Log.Error($"Eccezione in rollBackEntity{Environment.NewLine}{exc}"); } } return answ; } /// /// Statistiche del LOGchiamate all'API dato filtro /// /// Data minima /// DataMax /// Valore cercato, se "" è tutti /// public List StatsLogCallGetFilt(DateTime DateFrom, DateTime DateTo, string SearchVal = "") { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { var dtFrom = new SqlParameter("@DateFrom", DateFrom); var dtTo = new SqlParameter("@DateTo", DateTo); var srcVal = new SqlParameter("@SearchVal", SearchVal); dbResult = localDbCtx .DbSetStatCall .FromSqlRaw("exec dbo.stp_StatsCall_filt @DateFrom, @DateTo, @SearchVal", dtFrom, dtTo, srcVal) .AsNoTracking() .ToList(); } return dbResult; } public bool TicketAddNew(SupportRequest currRequest) { bool fatto = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // recupero locenza... var currLic = localDbCtx .DbSetLicenze .Where(x => x.CodApp == currRequest.CodApp && x.CodInst == currRequest.CodInst) .FirstOrDefault(); if (currLic != null) { TicketModel newTicket = new TicketModel() { DtReq = DateTime.Now, IdxLic = currLic.IdxLic, IdxSubLic = currRequest.idxSubLic, CodImpiego = currRequest.CodImp, ContactEmail = currRequest.ContactEmail, ContactPhone = currRequest.ContactPhone, ReqBody = currRequest.ReqBody, Status = StatoRichiesta.Richiesta, Tipo = TipoLicenza.UserKey, TType = currRequest.Tipo }; localDbCtx .DbSetTicket .Add(newTicket); localDbCtx.SaveChanges(); fatto = true; } } return fatto; } public List TicketGetAll(bool onlyOpen, int maxNum) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetTicket .Where(x => (x.Status <= StatoRichiesta.Valutazione || !onlyOpen)) .OrderByDescending(x => x.IdxTicket) .Include(l => l.LicenzaNav) .Take(maxNum) .Select(x => new TicketDTO { CodApp = x.LicenzaNav.CodApp, CodInst = x.LicenzaNav.CodInst, IdxTicket = x.IdxTicket, IdxLic = x.IdxLic, IdxSubLic = x.IdxSubLic, CodImpiego = x.CodImpiego, ContactName = x.ContactName, ContactEmail = x.ContactEmail, ContactPhone = x.ContactPhone, DtReq = x.DtReq, ReqBody = x.ReqBody, Status = x.Status, SupplAnsw = x.SupplAnsw, SupplEmail = x.SupplEmail, SupplUserCode = x.SupplUserCode, Tipo = x.Tipo }) .ToList(); } return dbResult; } public List TicketGetFilt(bool onlyOpen, TipologiaTicket Tipo, string CodApp, string CodInst, string MasterKey, int maxNum) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // recupero licenza... var currLic = localDbCtx .DbSetLicenze .Where(x => x.CodApp == CodApp && x.CodInst == CodInst && x.Chiave == MasterKey) .FirstOrDefault(); if (currLic != null) { dbResult = localDbCtx .DbSetTicket .Where(x => x.IdxLic == currLic.IdxLic && (x.Status <= StatoRichiesta.Valutazione || !onlyOpen) && (x.TType == Tipo || Tipo == TipologiaTicket.ND)) .OrderByDescending(x => x.IdxTicket) .Take(maxNum) .Select(x => new TicketDTO { IdxTicket = x.IdxTicket, IdxLic = x.IdxLic, IdxSubLic = x.IdxSubLic, CodImpiego = x.CodImpiego, ContactName = x.ContactName, ContactEmail = x.ContactEmail, ContactPhone = x.ContactPhone, DtReq = x.DtReq, ReqBody = x.ReqBody, Status = x.Status, SupplAnsw = x.SupplAnsw, SupplEmail = x.SupplEmail, SupplUserCode = x.SupplUserCode, Tipo = x.Tipo }) .ToList(); } } return dbResult; } public List TicketGetFilt(bool onlyOpen, string CodApp, string CodInst) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetTicket .Where(x => (x.Status <= StatoRichiesta.Valutazione || !onlyOpen) && (x.LicenzaNav.CodApp == CodApp || string.IsNullOrEmpty(CodApp)) && (x.LicenzaNav.CodInst == CodInst || string.IsNullOrEmpty(CodInst))) .OrderByDescending(x => x.IdxTicket) .Include(l => l.LicenzaNav) .Select(x => new TicketDTO { CodApp = x.LicenzaNav.CodApp, CodInst = x.LicenzaNav.CodInst, IdxTicket = x.IdxTicket, IdxLic = x.IdxLic, IdxSubLic = x.IdxSubLic, CodImpiego = x.CodImpiego, ContactName = x.ContactName, ContactEmail = x.ContactEmail, ContactPhone = x.ContactPhone, DtReq = x.DtReq, ReqBody = x.ReqBody, Status = x.Status, SupplAnsw = x.SupplAnsw, SupplEmail = x.SupplEmail, SupplUserCode = x.SupplUserCode, Tipo = x.Tipo, TType = x.TType }) .ToList(); } return dbResult; } public List TicketGetFiltAllLic(bool onlyOpen, TipologiaTicket Tipo, string CodApp, string CodInst, int maxNum) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { // recupero locenza... var currLic = localDbCtx .DbSetLicenze .Where(x => x.CodApp == CodApp && x.CodInst == CodInst) .FirstOrDefault(); if (currLic != null) { dbResult = localDbCtx .DbSetTicket .Where(x => (x.LicenzaNav.CodApp == CodApp && x.LicenzaNav.CodInst == CodInst) && (x.Status <= StatoRichiesta.Valutazione || !onlyOpen) && (x.TType == Tipo || Tipo == TipologiaTicket.ND)) .OrderByDescending(x => x.IdxTicket) .Take(maxNum) .Select(x => new TicketDTO { IdxTicket = x.IdxTicket, IdxLic = x.IdxLic, IdxSubLic = x.IdxSubLic, CodImpiego = x.CodImpiego, ContactName = x.ContactName, ContactEmail = x.ContactEmail, ContactPhone = x.ContactPhone, DtReq = x.DtReq, ReqBody = x.ReqBody, Status = x.Status, SupplAnsw = x.SupplAnsw, SupplEmail = x.SupplEmail, SupplUserCode = x.SupplUserCode, Tipo = x.Tipo }) .ToList(); } } return dbResult; } public bool TicketUpdateState(int IdxTicket, StatoRichiesta NewStatus) { bool fatto = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { var currRec = localDbCtx .DbSetTicket .Where(x => x.IdxTicket == IdxTicket) .FirstOrDefault(); if (currRec != null) { currRec.Status = NewStatus; localDbCtx.SaveChanges(); fatto = true; } } return fatto; } public bool UpsertInstallazione(InstallazioneModel updItem) { bool done = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { InstallazioneModel currData = localDbCtx .DbSetInst .Where(x => x.CodInst == updItem.CodInst) .FirstOrDefault(); if (currData != null) { // aggiorno valori currData.Descrizione = updItem.Descrizione; currData.Cliente = updItem.Cliente; currData.Contatto = updItem.Contatto; currData.Email = updItem.Email; localDbCtx.Entry(currData).State = EntityState.Modified; } else { localDbCtx .DbSetInst .Add(updItem); } localDbCtx.SaveChanges(); done = true; } catch (Exception exc) { Log.Error($"Eccezione in UpdateApplicazioni:{Environment.NewLine}{exc}"); } } return done; } public bool UpsertLicenza(LicenzaModel updItem) { bool done = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { LicenzaModel currData = localDbCtx .DbSetLicenze .Where(x => x.IdxLic == updItem.IdxLic) .FirstOrDefault(); if (currData != null) { // storicizzo vecchia licenza in log var newLogLic = new LogLicenzaModel() { Chiave = currData.Chiave, CodApp = currData.CodApp, CodInst = currData.CodInst, Descrizione = currData.Descrizione, IdxLic = currData.IdxLic, Locked = true, NumLicenze = currData.NumLicenze, Scadenza = currData.Scadenza, Tipo = currData.Tipo }; localDbCtx .DbSetLogLicenze .Add(newLogLic); // aggiorno valori licenza currData.CodApp = updItem.CodApp; currData.CodInst = updItem.CodInst; currData.NumLicenze = updItem.NumLicenze; currData.Descrizione = updItem.Descrizione; currData.Chiave = updItem.ChiaveCalc; currData.Scadenza = updItem.Scadenza; currData.Locked = updItem.Locked; currData.Payload = updItem.Payload; currData.DataEnigma = updItem.DataEnigma; currData.Enigma = updItem.Enigma; localDbCtx.Entry(currData).State = EntityState.Modified; } else { localDbCtx .DbSetLicenze .Add(updItem); } localDbCtx.SaveChanges(); done = true; } catch (Exception exc) { Log.Error($"Eccezione in UpdateLicenze:{Environment.NewLine}{exc}"); } } return done; } public bool UpsertLogLic(LogLicenzaModel updItem) { bool done = false; using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { try { localDbCtx .DbSetLogLicenze .Add(updItem); localDbCtx.SaveChanges(); done = true; } catch (Exception exc) { Log.Error($"Eccezione in UpdateApplicazioni:{Environment.NewLine}{exc}"); } } return done; } #endregion Public Methods #region Private Fields private static IConfiguration _configuration; private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); #endregion Private Fields #if false public List TicketGetByLic(int IdxLic, int maxNum) { List dbResult = new List(); using (LMDbContext localDbCtx = new LMDbContext(_configuration)) { dbResult = localDbCtx .DbSetTicket .Where(x => x.IdxLic == IdxLic) .OrderByDescending(x => x.DtReq) .Take(maxNum) .ToList(); } return dbResult; } #endif } }