From eb4809622b35eda28f9cfad5c8200de62a68f52a Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 2 Oct 2020 13:27:30 +0200 Subject: [PATCH 1/3] pulizia logger class --- SteamWare.Logger/log2note.cs | 316 ---------------------- SteamWare.Logger/logger.cs | 500 ----------------------------------- 2 files changed, 816 deletions(-) delete mode 100644 SteamWare.Logger/log2note.cs delete mode 100644 SteamWare.Logger/logger.cs diff --git a/SteamWare.Logger/log2note.cs b/SteamWare.Logger/log2note.cs deleted file mode 100644 index 21f96db..0000000 --- a/SteamWare.Logger/log2note.cs +++ /dev/null @@ -1,316 +0,0 @@ -using System; - -namespace SteamWare.Logger -{ - /// - /// classe gestione logging esteso di eventi e note utente (correlabili) - /// - public class log2note - { - #region area protected - - /// - /// TableAdapter di accesso alla tabella anagrafica filtraggi - /// - protected DS_loggingTableAdapters.T_anagFiltroTableAdapter taAnagFilt; - /// - /// TableAdapter di accesso alla tabella anagrafica record - /// - protected DS_loggingTableAdapters.T_anagRecordTableAdapter taAnagRec; - /// - /// TableAdapter di accesso alla tabella logging record di eventi - /// - protected DS_loggingTableAdapters.T_logRecordsTableAdapter taLogRec; - /// - /// TableAdapter di accesso alla tabella logging utente - /// - protected DS_loggingTableAdapters.T_logUtenteTableAdapter taLogUt; - /// - /// TableAdapter di accesso alla vista logging eventi - /// - public DS_loggingTableAdapters.v_logRecordsTableAdapter ta_vLogRec; - /// - /// TableAdapter di accesso alla vista logging utente - /// - public DS_loggingTableAdapters.v_logUtenteTableAdapter ta_vLogUt; - - /// - /// effettua setup dei connection strings da web.config delal singola applicazione - /// - protected void setupConnectionString() - { - // cambio le connString - string _connectionString = memLayer.ML.confReadString("LoggingConnectionString"); - taAnagFilt.Connection.ConnectionString = _connectionString; - taAnagRec.Connection.ConnectionString = _connectionString; - taLogRec.Connection.ConnectionString = _connectionString; - taLogUt.Connection.ConnectionString = _connectionString; - ta_vLogUt.Connection.ConnectionString = _connectionString; - ta_vLogRec.Connection.ConnectionString = _connectionString; - } - /// - /// avvio i tari tableAdapters - /// - private void setupTA() - { - taAnagFilt = new DS_loggingTableAdapters.T_anagFiltroTableAdapter(); - taAnagRec = new DS_loggingTableAdapters.T_anagRecordTableAdapter(); - taLogRec = new DS_loggingTableAdapters.T_logRecordsTableAdapter(); - taLogUt = new DS_loggingTableAdapters.T_logUtenteTableAdapter(); - ta_vLogRec = new DS_loggingTableAdapters.v_logRecordsTableAdapter(); - ta_vLogUt = new DS_loggingTableAdapters.v_logUtenteTableAdapter(); - } - /// - /// avvio della classe istanziando db e - /// - log2note() - { - setupTA(); - setupConnectionString(); - } - - - #endregion - - #region area public - - /// - /// oggetto statico di accesso ai metodi della classe... - /// - public static log2note l2n = new log2note(); - - #region area oggetti restituiti - - /// - /// tabella eventi - /// - /// - public DS_logging.v_logRecordsDataTable tabLogEventi() - { - return ta_vLogRec.GetData(); - } - /// - /// tabella note - /// - /// - public DS_logging.v_logUtenteDataTable tabLogNote() - { - return ta_vLogUt.GetData(); - } - /// - /// tabella eventi secondo filtro - /// - /// filtro gestito come condizione "LIKE '%{0}%'" rispetto al filtro salvato con l'evento - /// - public DS_logging.v_logRecordsDataTable tabLogEventi(string filtro) - { - return ta_vLogRec.getByFiltro(filtro); - } - /// - /// tabella note secondo filtro - /// - /// filtro gestito come condizione "LIKE '%{0}%'" rispetto al filtro salvato con l'evento - /// - public DS_logging.v_logUtenteDataTable tabLogNote(string filtro) - { - return ta_vLogUt.getByFiltro(filtro); - } - /// - /// tabella eventi secondo filtro e condizione ulteriore WHERE esplicitata - /// - /// filtro gestito come condizione "LIKE '%{0}%'" rispetto al filtro salvato con l'evento - /// ulteriore condizione WHERE per filtrare i dati (testo {0} della condizione "WHERE {0}" - /// - public DS_logging.v_logRecordsDataTable tabLogEventi(string filtro, string _where) - { - DS_logging.v_logRecordsDataTable _tab = new DS_logging.v_logRecordsDataTable(); - foreach (DS_logging.v_logRecordsRow riga in ta_vLogRec.getByFiltro(filtro).Select(_where)) - { - _tab.Addv_logRecordsRow(riga); - } - return _tab; - } - /// - /// tabella note secondo filtro e condizione ulteriore WHERE esplicitata - /// - /// filtro gestito come condizione "LIKE '%{0}%'" rispetto al filtro salvato con l'evento - /// ulteriore condizione WHERE per filtrare i dati (testo {0} della condizione "WHERE {0}" - /// - public DS_logging.v_logUtenteDataTable tabLogNote(string filtro, string _where) - { - DS_logging.v_logUtenteDataTable _tab = new DS_logging.v_logUtenteDataTable(); - foreach (DS_logging.v_logUtenteRow riga in ta_vLogUt.getByFiltro(filtro).Select(_where)) - { - _tab.Addv_logUtenteRow(riga); - } - return _tab; - } - - /// - /// tabella note secondo filtro - /// - /// filtro gestito come condizione "LIKE '%{0}%'" rispetto al filtro salvato con l'evento - /// - public DS_logging.T_logUtenteDataTable tabLogUt(string filtro) - { - return taLogUt.getByFiltro(filtro); - } - - - #endregion - - #region area insert valori - - /// - /// inserisce l'evento indicato dai parametri - /// - /// user che ha generato l'evento - /// pagina/form applicaizone in cui l'evento si � generato - /// valore originale(se c'�) - /// valore nuovo/modificato - /// descrizione evento (poi gestita con anagrafica interna) - /// filtro logico evento (poi gestita con anagrafica interna) - public void insEvento(string _userEv, string _pagina, string _valOrig, string _valNew, string _evento, string _filtro) - { - taLogRec.sp_insRecFull(_userEv, _pagina, _valOrig, _valNew, _evento, _filtro); - } - /// - /// inserisce la nota utente indicata dai parametri, restituisce idx della nota creata... - /// - /// user che ha inserito la nota - /// testo della nota - /// valore ulteriore da associare alla nota (es: label, codice, versione, ...) - /// filtro logico evento (poi gestita con anagrafica interna) - /// intero dell'idx della nota creata - public int insNota(string _userNota, string _nota, string _val, string _filtro) - { - int? answ = 0; - taLogUt.sp_insLogUtFull(_userNota, _nota, _val, _filtro, ref answ); - return (int)answ; - } - - #endregion - - #region area gestione eventi (cestina, delete, associazione a note,...) - - /// - /// associa l'evento e la nota indicati - /// - /// idx del record da associare - /// idx chiave della nota da associare - public void associaEvento2Nota(int idxRecord, int _idxNota) - { - taLogRec.sp_setRec2nota(idxRecord, _idxNota); - } - - /// - /// associa l'ultimo evento del filtro indicato alla nota - /// - /// filtro associato all'ultimo evento... - /// idx chiave della nota da associare - public void associaLastEvento2Nota(string filtro, int _idxNota) - { - taLogRec.sp_setLastRec2nota(filtro, _idxNota); - } - /// - /// segna come cestinati tutti gli eventi dell'utente indicato non ancora associati o cestinati - /// - /// utente generatore dell'evento - public void cestinaEventiUser(string _userEv) - { - taLogRec.sp_cestinaLogRecUt(_userEv); - } - /// - /// segna come cestinati tutti gli eventi dell'utente indicato non ancora associati o cestinati - /// - /// utente generatore dell'evento - public void cestinaEventiFiltro(string _filtro) - { - taLogRec.sp_cestinaLogRecFiltro(_filtro); - } - /// - /// Elimina gli eventi cestinati generati dall'utente indicato - /// - /// utente generatore dell'evento - public void eliminaEventiDaUser(string _userEv) - { - taLogRec.sp_deleteLogUser(_userEv); - } - /// - /// Elimina gli eventi cestinati anteriori alla data selezionata - /// - /// dataOra dell'evento - public void associaEvento2Nota(DateTime _dataOra) - { - taLogRec.sp_deleteLogMaxData(_dataOra); - } - - /// - /// effettua la registrazione dell'evento in session - /// - public void registraEventi(string _userEv, string _pagina) - { - // controllo: loggin SOLO se la scheda ha logging abilitato nella riga del db... - bool logEn = memLayer.ML.BoolSessionObj("logEn"); - memLayer.ML.emptySessionVal("logEn"); - if (logEn) - { - // leggo e svuoto info x logging - string ev2log = memLayer.ML.StringSessionObj("ev2log"); - memLayer.ML.emptySessionVal("ev2log"); - string valOrig = memLayer.ML.StringSessionObj("valOrig"); - memLayer.ML.emptySessionVal("valOrig"); - string valNew = memLayer.ML.StringSessionObj("valNew"); - memLayer.ML.emptySessionVal("valNew"); - string filtEv = memLayer.ML.StringSessionObj("filtEv"); - memLayer.ML.emptySessionVal("filtEv"); - // effettuo logging evento - l2n.insEvento(_userEv, _pagina, valOrig, valNew, ev2log, filtEv); - } - } - - #endregion - - #endregion - } - /// - /// metodo di comportamento del controllo di logging - /// - public enum logControlMode - { - /// - /// nasconde pannello log - /// - hideLog, - /// - /// memorizza log inserito - /// - recordLog, - /// - /// mostra pannello log - /// - showLog - } - /// - /// metodo di comportamento del controllo di logging - /// - public enum tipoApprovazione - { - /// - /// indica il primo step del doppio livello di approvazione (completamento) - /// - completamento, - /// - /// SOLO con incremento indice di revisione dell'oggetto approvato - /// - revisione, - /// - /// SOLO mantenendo indice di revisione corrente - /// - semplice, - /// - /// permette SIA con revisione che senza (e anche rev -1) - /// - tutto - } -} diff --git a/SteamWare.Logger/logger.cs b/SteamWare.Logger/logger.cs deleted file mode 100644 index 90d4da8..0000000 --- a/SteamWare.Logger/logger.cs +++ /dev/null @@ -1,500 +0,0 @@ -using System; -using System.IO; -using System.Threading; - -namespace SteamWare.Logger -{ - /// - /// classe gesione log files applicazioni - /// - public class logger - { - #region dichiarazione variabili - - /// - /// directory base x logs - /// - protected string _logBaseDir; - /// - /// nome del file corrente - /// - protected string _logfileName; - /// - /// max mb di log da accumulare - /// - protected int _logMaxMb; - /// - /// controlla se si debba mantenere sotto controllo la dimensioen della cartella logs - /// - protected bool _doShrinkFolder; - /// - /// Ultima verifica directory (x shrink) - /// - private static DateTime lastDirCheck; - /// - /// metodo gestione wirteLock su file log - /// - private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim(); - /// - /// Indica se sia abilitato log diagnostico esteso... - /// - protected bool enableDumpDiag = false; - - #endregion - - #region metodi esposti - - /// - /// singleton del logger - /// - public static logger lg = new logger(); - - /// - /// avvio del logger nella dir desiderata - /// - public logger() - { - string _logDir = memLayer.ML.confReadString("_logDir"); - try - { - _logBaseDir = SteamwareStrings.getFilePath(_logDir); - } - catch (Exception exc) - { - _logBaseDir = _logDir != "" ? _logDir : "~/logs/"; - } - _logMaxMb = 100; // di default 100 mb... - try - { - _doShrinkFolder = memLayer.ML.confReadBool("doShrinkFolder"); - } - catch - { - _doShrinkFolder = true; - } - try - { - enableDumpDiag = memLayer.ML.confReadBool("enableDumpDiag"); - } - catch - { - enableDumpDiag = false; - } - // all'avvio imposto ultimo check a 23 ore fa... cos� far� shrink DOPO 1 h da avvio - lastDirCheck = DateTime.Now.AddHours(-23); - } - /// - /// livello di log applicazione (da web.config, chiave '_logLevel') - /// - public int logLevel - { - get - { - int answ = -1; - try - { - answ = memLayer.ML.CRI("_logLevel"); - } - catch - { - scriviLog("non ho trovato chiave di registro x logLevel...", tipoLog.ERROR); - } - return answ; - } - } - /// - /// avvio del logger nella dir desiderata - /// - public logger(string _baseDir) - { - _logBaseDir = _baseDir; - _logMaxMb = 40; // di default 40 mb... - } - /// - /// avvio del logger nella dir desiderata con il max di dati indicato - /// - public logger(string _baseDir, int _logMaxMB) - { - _logBaseDir = _baseDir; - _logMaxMb = _logMaxMB; - } - /// - /// resetta il logfile odierno - /// - public void resetLogFile() - { - newLogfileName(); - FileInfo fi = new FileInfo(_logfileName); - fi.Delete(); - scriviLog("ResetFile", tipoLog.STARTUP); - } - /// - /// scrive sul file log di default il valore della variabile string passata su una riga... (tab delim?!?) - /// - /// testo iniziale del log - /// - public bool scriviLog(string _testoPre) - { - bool needWrite = false; - bool fatto = false; - // preparo hash redis - string hKey = _testoPre.Replace(":", "_").Replace("/", "_").Replace("#", "_").Replace("(", "").Replace(")", "").Replace("|", "_").Replace(" ", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_"); - //se troppo lunga trimmo... - if (hKey.Length > 100) - { - hKey = hKey.Substring(0, 100); - } - string hVetoErrore = memLayer.ML.redHash("Logger:Veto:" + hKey); - string hCountErrore = memLayer.ML.redHash("Logger:Counter:" + hKey); - bool redisEnabled = memLayer.ML.confReadBool("cacheOnRedis"); - // verifico mitigazione - int logMitigSec = 30; - try - { - if (memLayer.ML.confReadString("logMitigSec") != "") - { - logMitigSec = memLayer.ML.confReadInt("logMitigSec"); - } - } - catch - { } - // verifico SE HO redis (in quel caso gli errori li loggo 1 volta poi metto un VETO ed un counter) - if (redisEnabled) - { - // cerco se ho un veto precedente in redis - string vetoPar = memLayer.ML.getRSV(hVetoErrore); - if (vetoPar != null && vetoPar != "") - { - needWrite = false; - } - else - { - // metto veto per TTL default... (durata std = 30 sec) - memLayer.ML.setRSV(hVetoErrore, DateTime.UtcNow.ToString(), logMitigSec); - // abilito log... - needWrite = true; - } - memLayer.ML.setRCntI(hCountErrore); - } - else - { - // altrimenti log direttamente - needWrite = true; - } - // se devo DAVVERO scrivere - if (needWrite) - { - if (redisEnabled) - { - int numRep = memLayer.ML.getRCnt(hCountErrore); - if (numRep > 1) - { - // cambio messaggio con un inizio pari al num di ripetizioni... - _testoPre = string.Format("{0} x {1}", numRep, _testoPre); - } - // reset counter - memLayer.ML.resetRCnt(hCountErrore); - } - fatto = doScriviLog(_testoPre); - } - return fatto; - } - /// - /// Vera chiamata scrittura log x override con gestione REDIS di calmierazione - /// - /// - /// - private bool doScriviLog(string _testoPre) - { - bool fatto = false; - // attenzione: rimpiazzo eventuali "
" con newline... - string _testo = string.Format("{0:H:mm:ss ffff} \t{1}", DateTime.Now, _testoPre.Replace("
", Environment.NewLine).Replace("
", Environment.NewLine).Replace("
", Environment.NewLine)); - // se � configurato x shrink ed � passato almeno 1 gg da ultimo check... - if (_doShrinkFolder && lastDirCheck.AddDays(1) < DateTime.Now) - { - // verifica dim directory ed eventualmente cancella... - opzionale - shrinkDir(); - // salvo nuova ora di check - lastDirCheck = DateTime.Now; - } - // (ri)genera il nome del file di log... - newLogfileName(); - // scrivo thread safe - fatto = WriteToFileThreadSafe(_logfileName, _testo); - return fatto; - } - - /// - /// Esecuzione scrittura ThreadSafe - /// - /// - /// - public bool WriteToFileThreadSafe(string logPath, string text2write) - { - bool answ = false; - // Set Status to Locked - _readWriteLock.EnterWriteLock(); - try - { - // Append text to the file - using (StreamWriter sw = File.AppendText(logPath)) - { - sw.WriteLine(text2write); - sw.Close(); - answ = true; - } - } - finally - { - // Release lock - _readWriteLock.ExitWriteLock(); - } - return answ; - } - - /// - /// scrive un messaggio di log con etichetta pre - /// - /// testo messaggio - /// tipo di log da registrare (etichetta [...]) - /// - public bool scriviLog(string testoLog, tipoLog tipo) - { - bool answ = false; - answ = scriviLog(string.Format("[{0}] - {1}", tipo, testoLog)); - // se � un tipo EXCEPTION allora scrivo anche log diagnostico - if (tipo == tipoLog.EXCEPTION && enableDumpDiag) - { - try - { - string[] pingTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("pingTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text); - string[] wwwTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("wwwTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text); - // chiamo scrittura diagnostica - scriviDiagnostica("DUMP diagnostico causa Eccezione", pingTagets, wwwTagets); - } - catch - { } - } - return answ; - } - /// - /// scrive su log un dump di diagnostica - /// - /// Causale diagnostica - /// target per test PING - /// target x download www page - public void scriviDiagnostica(string testoLog, string[] pingTargets, string[] wwwTargets) - { - string txtDiag = ""; - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('+', 80))); - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('+', 80))); - scriviLog(string.Format("[{0}] - {1}{2}", tipoLog.DUMP_DIAGN, testoLog, Environment.NewLine)); - } - catch - { } - - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("UPTIME", Diagnostica.uptime))); - } - catch - { } - - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("STORAGE", Diagnostica.diskUsage))); - } - catch - { } - - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("USB", Diagnostica.usbDevices))); - } - catch - { } - - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("SERIAL", Diagnostica.serialPorts))); - } - catch - { } - - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (interfaces)", Diagnostica.networkInterfaces))); - } - catch - { } - - try - { - // se richiesto faccio PING test - if (pingTargets.Length > 0) - { - txtDiag = ""; - foreach (string target in pingTargets) - { - txtDiag += SteamwareStrings.addLine(Diagnostica.pingIp(target)); - } - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (ping)", txtDiag))); - } - } - catch - { } - - try - { - // se richiesto faccio PING test - if (wwwTargets.Length > 0) - { - txtDiag = ""; - foreach (string target in wwwTargets) - { - txtDiag += SteamwareStrings.addLine(string.Format("WebPage Test ({2}): {0}{1}", Environment.NewLine, Diagnostica.getPageContent(target), target)); - } - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (www)", txtDiag))); - } - } - catch - { } - - // chiudo - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('-', 80))); - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('-', 80))); - } - /// - /// formatta un blococ di diagnostica (titolo, contenuto / eccezione) - /// - /// - /// - /// - protected string formDiagBlock(string titolo, string contenuto) - { - string answ = SteamwareStrings.charTitle(titolo, '-', 60); - try - { - answ += SteamwareStrings.addLine(contenuto); - } - catch - { - answ += string.Format("Errore diagnostica {0}", titolo); - } - return answ; - } - - - #endregion - - #region metodi privati - - /// - /// fornisce il nome del file in cui loggare (ed eventualmente crea...) - /// - protected void newLogfileName() - { - DateTime CurrentDateTime = DateTime.Now; - _logfileName = _logBaseDir + String.Format("{0}.log", CurrentDateTime.ToString("yyyyMMdd")); - } - /// - /// provvede a verificare la dim della cartella dei log e cancella i + vecchi fino a restare a dim inferiori a _logMaxMb - /// - protected void shrinkDir() - { - // ottengo elenco files *.log - fileMover.obj.setDirectory(_logBaseDir); - FileInfo[] _fis = fileMover.obj.elencoFiles_FI("*.log"); - compressAndRemove(_fis); - // acnhe per i "Vecchi" formati .txt - _fis = fileMover.obj.elencoFiles_FI("*.txt"); - compressAndRemove(_fis); - } - - private void compressAndRemove(FileInfo[] _fis) - { - foreach (FileInfo _file in _fis) - { - if (_file.CreationTime < DateTime.Now.AddDays(-2)) // zippo files + vecchi di 2 gg... - { - fileMover.obj.zippaSingoloFile(_file); - // cancello l'originale... - fileMover.obj.eliminaFile(_file); - } - } - // verifico directory e dimensione... - while (fileMover.obj.totalMb() > _logMaxMb) - { - // cancello i + vecchi fino a rientrare alla dimensione max... - fileMover.obj.deleteOldest(); - } - } - - /// - /// fornisce il file + vecchio - /// - /// - /// - protected void deleteOldest(DirectoryInfo _di) - { - FileInfo[] _fis = _di.GetFiles(); - DateTime _oldest = DateTime.Now; - string _nome = ""; - foreach (FileInfo _file in _fis) - { - if (_file.CreationTime < _oldest) - { - _nome = _file.Name; - } - } - FileInfo fi = new FileInfo(_nome); - fi.Delete(); - } - - #endregion - } - /// - /// tipo di log ammesso - /// - public enum tipoLog - { - /// - /// informazioni di debug - /// - DEBUG, - /// - /// dump diagnostica - /// - DUMP_DIAGN, - /// - /// errori - /// - ERROR, - /// - /// eccezioni nell'esecuzione try/catch - /// - EXCEPTION, - /// - /// errori fatali - /// - FATAL, - /// - /// informazioni opzionali - /// - INFO, - /// - /// log dei lemmi invocati per traduzione da vocabolario - /// - LEMMA, - /// - /// fase di avvio componente - /// - STARTUP, - /// - /// avvisi - /// - WARNING - } -} From 2c8f04722abde9bf00ce29307f25a32147455c1a Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 2 Oct 2020 13:27:46 +0200 Subject: [PATCH 2/3] riorganizzazione classe logger.cs --- SteamWare.IO/app.config | 65 +- SteamWare.Logger/SteamWare.Logger.csproj | 18 + SteamWareLib/logger.cs | 937 ++++++++++++----------- 3 files changed, 532 insertions(+), 488 deletions(-) diff --git a/SteamWare.IO/app.config b/SteamWare.IO/app.config index b2b295d..1495331 100644 --- a/SteamWare.IO/app.config +++ b/SteamWare.IO/app.config @@ -1,61 +1,64 @@ - - - - - - + + + + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - + + + + \ No newline at end of file diff --git a/SteamWare.Logger/SteamWare.Logger.csproj b/SteamWare.Logger/SteamWare.Logger.csproj index 26ba1a9..195c06e 100644 --- a/SteamWare.Logger/SteamWare.Logger.csproj +++ b/SteamWare.Logger/SteamWare.Logger.csproj @@ -52,6 +52,13 @@ SteamWare.cs + + True + True + DS_logging.xsd + + + @@ -60,6 +67,17 @@ .editorconfig + + DS_logging.xsd + + + MSDataSetGenerator + DS_logging.Designer.cs + Designer + + + DS_logging.xsd + Always diff --git a/SteamWareLib/logger.cs b/SteamWareLib/logger.cs index c94cc1e..8c810d7 100644 --- a/SteamWareLib/logger.cs +++ b/SteamWareLib/logger.cs @@ -4,497 +4,520 @@ using System.Threading; namespace SteamWare { - /// - /// classe gesione log files applicazioni - /// - public class logger - { - #region dichiarazione variabili - /// - /// directory base x logs + /// tipo di log ammesso /// - protected string _logBaseDir; - /// - /// nome del file corrente - /// - protected string _logfileName; - /// - /// max mb di log da accumulare - /// - protected int _logMaxMb; - /// - /// controlla se si debba mantenere sotto controllo la dimensioen della cartella logs - /// - protected bool _doShrinkFolder; - /// - /// Ultima verifica directory (x shrink) - /// - private static DateTime lastDirCheck; - /// - /// metodo gestione wirteLock su file log - /// - private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim(); - /// - /// Indica se sia abilitato log diagnostico esteso... - /// - protected bool enableDumpDiag = false; - - #endregion - - #region metodi esposti - - /// - /// singleton del logger - /// - public static logger lg = new logger(); - - /// - /// avvio del logger nella dir desiderata - /// - public logger() + public enum tipoLog { - string _logDir = memLayer.ML.confReadString("_logDir"); - try - { - _logBaseDir = fileMover.getFilePath(_logDir); - } - catch (Exception exc) - { - _logBaseDir = _logDir != "" ? _logDir : "~/logs/"; - } - _logMaxMb = 100; // di default 100 mb... - try - { - _doShrinkFolder = memLayer.ML.confReadBool("doShrinkFolder"); - } - catch - { - _doShrinkFolder = true; - } - try - { - enableDumpDiag = memLayer.ML.confReadBool("enableDumpDiag"); - } - catch - { - enableDumpDiag = false; - } - // all'avvio imposto ultimo check a 23 ore fa... così farà shrink DOPO 1 h da avvio - lastDirCheck = DateTime.Now.AddHours(-23); + /// + /// informazioni di debug + /// + DEBUG, + + /// + /// dump diagnostica + /// + DUMP_DIAGN, + + /// + /// errori + /// + ERROR, + + /// + /// eccezioni nell'esecuzione try/catch + /// + EXCEPTION, + + /// + /// errori fatali + /// + FATAL, + + /// + /// informazioni opzionali + /// + INFO, + + /// + /// log dei lemmi invocati per traduzione da vocabolario + /// + LEMMA, + + /// + /// fase di avvio componente + /// + STARTUP, + + /// + /// avvisi + /// + WARNING } + /// - /// livello di log applicazione (da web.config, chiave '_logLevel') + /// classe gesione log files applicazioni /// - public int logLevel + public class logger { - get - { - int answ = -1; - try + #region dichiarazione variabili + + /// + /// controlla se si debba mantenere sotto controllo la dimensioen della cartella logs + /// + protected bool _doShrinkFolder; + + /// + /// directory base x logs + /// + protected string _logBaseDir; + + /// + /// nome del file corrente + /// + protected string _logfileName; + + /// + /// max mb di log da accumulare + /// + protected int _logMaxMb; + + /// + /// Indica se sia abilitato log diagnostico esteso... + /// + protected bool enableDumpDiag = false; + + /// + /// metodo gestione wirteLock su file log + /// + private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim(); + + /// + /// Ultima verifica directory (x shrink) + /// + private static DateTime lastDirCheck; + + #endregion dichiarazione variabili + + #region metodi esposti + + /// + /// singleton del logger + /// + public static logger lg = new logger(); + + /// + /// avvio del logger nella dir desiderata + /// + public logger() { - answ = memLayer.ML.CRI("_logLevel"); + string _logDir = memLayer.ML.confReadString("_logDir"); + try + { + _logBaseDir = fileMover.getFilePath(_logDir); + } + catch (Exception exc) + { + _logBaseDir = _logDir != "" ? _logDir : "~/logs/"; + } + _logMaxMb = 100; // di default 100 mb... + try + { + _doShrinkFolder = memLayer.ML.confReadBool("doShrinkFolder"); + } + catch + { + _doShrinkFolder = true; + } + try + { + enableDumpDiag = memLayer.ML.confReadBool("enableDumpDiag"); + } + catch + { + enableDumpDiag = false; + } + // all'avvio imposto ultimo check a 23 ore fa... così farà shrink DOPO 1 h da avvio + lastDirCheck = DateTime.Now.AddHours(-23); } - catch + + /// + /// avvio del logger nella dir desiderata + /// + public logger(string _baseDir) { - scriviLog("non ho trovato chiave di registro x logLevel...", tipoLog.ERROR); + _logBaseDir = _baseDir; + _logMaxMb = 40; // di default 40 mb... } - return answ; - } - } - /// - /// avvio del logger nella dir desiderata - /// - public logger(string _baseDir) - { - _logBaseDir = _baseDir; - _logMaxMb = 40; // di default 40 mb... - } - /// - /// avvio del logger nella dir desiderata con il max di dati indicato - /// - public logger(string _baseDir, int _logMaxMB) - { - _logBaseDir = _baseDir; - _logMaxMb = _logMaxMB; - } - /// - /// resetta il logfile odierno - /// - public void resetLogFile() - { - newLogfileName(); - FileInfo fi = new FileInfo(_logfileName); - fi.Delete(); - scriviLog("ResetFile", tipoLog.STARTUP); - } - /// - /// scrive sul file log di default il valore della variabile string passata su una riga... (tab delim?!?) - /// - /// testo iniziale del log - /// - public bool scriviLog(string _testoPre) - { - bool needWrite = false; - bool fatto = false; - // preparo hash redis - string hKey = _testoPre.Replace(":", "_").Replace("/", "_").Replace("#", "_").Replace("(", "").Replace(")", "").Replace("|", "_").Replace(" ", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_"); - //se troppo lunga trimmo... - if (hKey.Length > 100) - { - hKey = hKey.Substring(0, 100); - } - string hVetoErrore = memLayer.ML.redHash("Logger:Veto:" + hKey); - string hCountErrore = memLayer.ML.redHash("Logger:Counter:" + hKey); - bool redisEnabled = memLayer.ML.confReadBool("cacheOnRedis"); - // verifico mitigazione - int logMitigSec = 30; - try - { - if (memLayer.ML.confReadString("logMitigSec") != "") + + /// + /// avvio del logger nella dir desiderata con il max di dati indicato + /// + public logger(string _baseDir, int _logMaxMB) { - logMitigSec = memLayer.ML.confReadInt("logMitigSec"); + _logBaseDir = _baseDir; + _logMaxMb = _logMaxMB; } - } - catch - { } - // verifico SE HO redis (in quel caso gli errori li loggo 1 volta poi metto un VETO ed un counter) - if (redisEnabled) - { - // cerco se ho un veto precedente in redis - string vetoPar = memLayer.ML.getRSV(hVetoErrore); - if (vetoPar != null && vetoPar != "") + + /// + /// livello di log applicazione (da web.config, chiave '_logLevel') + /// + public int logLevel { - needWrite = false; + get + { + int answ = -1; + try + { + answ = memLayer.ML.CRI("_logLevel"); + } + catch + { + scriviLog("non ho trovato chiave di registro x logLevel...", tipoLog.ERROR); + } + return answ; + } } - else + + /// + /// resetta il logfile odierno + /// + public void resetLogFile() { - // metto veto per TTL default... (durata std = 30 sec) - memLayer.ML.setRSV(hVetoErrore, DateTime.UtcNow.ToString(), logMitigSec); - // abilito log... - needWrite = true; + newLogfileName(); + FileInfo fi = new FileInfo(_logfileName); + fi.Delete(); + scriviLog("ResetFile", tipoLog.STARTUP); } - memLayer.ML.setRCntI(hCountErrore); - } - else - { - // altrimenti log direttamente - needWrite = true; - } - // se devo DAVVERO scrivere - if (needWrite) - { - if (redisEnabled) + + /// + /// scrive su log un dump di diagnostica + /// + /// Causale diagnostica + /// target per test PING + /// target x download www page + public void scriviDiagnostica(string testoLog, string[] pingTargets, string[] wwwTargets) { - int numRep = memLayer.ML.getRCnt(hCountErrore); - if (numRep > 1) - { - // cambio messaggio con un inizio pari al num di ripetizioni... - _testoPre = string.Format("{0} x {1}", numRep, _testoPre); - } - // reset counter - memLayer.ML.resetRCnt(hCountErrore); - } - fatto = doScriviLog(_testoPre); - } - return fatto; - } - /// - /// Vera chiamata scrittura log x override con gestione REDIS di calmierazione - /// - /// - /// - private bool doScriviLog(string _testoPre) - { - bool fatto = false; - // attenzione: rimpiazzo eventuali "
" con newline... - string _testo = string.Format("{0:H:mm:ss ffff} \t{1}", DateTime.Now, _testoPre.Replace("
", Environment.NewLine).Replace("
", Environment.NewLine).Replace("
", Environment.NewLine)); - // se è configurato x shrink ed è passato almeno 1 gg da ultimo check... - if (_doShrinkFolder && lastDirCheck.AddDays(1) < DateTime.Now) - { - // verifica dim directory ed eventualmente cancella... - opzionale - shrinkDir(); - // salvo nuova ora di check - lastDirCheck = DateTime.Now; - } - // (ri)genera il nome del file di log... - newLogfileName(); - // scrivo thread safe - fatto = WriteToFileThreadSafe(_logfileName, _testo); - return fatto; - } + string txtDiag = ""; + try + { + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('+', 80))); + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('+', 80))); + scriviLog(string.Format("[{0}] - {1}{2}", tipoLog.DUMP_DIAGN, testoLog, Environment.NewLine)); + } + catch + { } - /// - /// Esecuzione scrittura ThreadSafe - /// - /// - /// - public bool WriteToFileThreadSafe(string logPath, string text2write) - { - bool answ = false; - // Set Status to Locked - _readWriteLock.EnterWriteLock(); - try - { - // Append text to the file - using (StreamWriter sw = File.AppendText(logPath)) + try + { + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("UPTIME", Diagnostica.uptime))); + } + catch + { } + + try + { + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("STORAGE", Diagnostica.diskUsage))); + } + catch + { } + + try + { + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("USB", Diagnostica.usbDevices))); + } + catch + { } + + try + { + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("SERIAL", Diagnostica.serialPorts))); + } + catch + { } + + try + { + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (interfaces)", Diagnostica.networkInterfaces))); + } + catch + { } + + try + { + // se richiesto faccio PING test + if (pingTargets.Length > 0) + { + txtDiag = ""; + foreach (string target in pingTargets) + { + txtDiag += SteamwareStrings.addLine(Diagnostica.pingIp(target)); + } + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (ping)", txtDiag))); + } + } + catch + { } + + try + { + // se richiesto faccio PING test + if (wwwTargets.Length > 0) + { + txtDiag = ""; + foreach (string target in wwwTargets) + { + txtDiag += SteamwareStrings.addLine(string.Format("WebPage Test ({2}): {0}{1}", Environment.NewLine, Diagnostica.getPageContent(target), target)); + } + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (www)", txtDiag))); + } + } + catch + { } + + // chiudo + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('-', 80))); + scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('-', 80))); + } + + /// + /// scrive sul file log di default il valore della variabile string passata su una riga... (tab delim?!?) + /// + /// testo iniziale del log + /// + public bool scriviLog(string _testoPre) { - sw.WriteLine(text2write); - sw.Close(); - answ = true; + bool needWrite = false; + bool fatto = false; + // preparo hash redis + string hKey = _testoPre.Replace(":", "_").Replace("/", "_").Replace("#", "_").Replace("(", "").Replace(")", "").Replace("|", "_").Replace(" ", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_"); + //se troppo lunga trimmo... + if (hKey.Length > 100) + { + hKey = hKey.Substring(0, 100); + } + string hVetoErrore = memLayer.ML.redHash("Logger:Veto:" + hKey); + string hCountErrore = memLayer.ML.redHash("Logger:Counter:" + hKey); + bool redisEnabled = memLayer.ML.confReadBool("cacheOnRedis"); + // verifico mitigazione + int logMitigSec = 30; + try + { + if (memLayer.ML.confReadString("logMitigSec") != "") + { + logMitigSec = memLayer.ML.confReadInt("logMitigSec"); + } + } + catch + { } + // verifico SE HO redis (in quel caso gli errori li loggo 1 volta poi metto un VETO ed un counter) + if (redisEnabled) + { + // cerco se ho un veto precedente in redis + string vetoPar = memLayer.ML.getRSV(hVetoErrore); + if (vetoPar != null && vetoPar != "") + { + needWrite = false; + } + else + { + // metto veto per TTL default... (durata std = 30 sec) + memLayer.ML.setRSV(hVetoErrore, DateTime.UtcNow.ToString(), logMitigSec); + // abilito log... + needWrite = true; + } + memLayer.ML.setRCntI(hCountErrore); + } + else + { + // altrimenti log direttamente + needWrite = true; + } + // se devo DAVVERO scrivere + if (needWrite) + { + if (redisEnabled) + { + int numRep = memLayer.ML.getRCnt(hCountErrore); + if (numRep > 1) + { + // cambio messaggio con un inizio pari al num di ripetizioni... + _testoPre = string.Format("{0} x {1}", numRep, _testoPre); + } + // reset counter + memLayer.ML.resetRCnt(hCountErrore); + } + fatto = doScriviLog(_testoPre); + } + return fatto; } - } - finally - { - // Release lock - _readWriteLock.ExitWriteLock(); - } - return answ; - } - /// - /// scrive un messaggio di log con etichetta pre - /// - /// testo messaggio - /// tipo di log da registrare (etichetta [...]) - /// - public bool scriviLog(string testoLog, tipoLog tipo) - { - bool answ = false; - answ = scriviLog(string.Format("[{0}] - {1}", tipo, testoLog)); - // se è un tipo EXCEPTION allora scrivo anche log diagnostico - if (tipo == tipoLog.EXCEPTION && enableDumpDiag) - { - try + /// + /// scrive un messaggio di log con etichetta pre + /// + /// testo messaggio + /// tipo di log da registrare (etichetta [...]) + /// + public bool scriviLog(string testoLog, tipoLog tipo) { - string[] pingTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("pingTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text); - string[] wwwTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("wwwTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text); - // chiamo scrittura diagnostica - scriviDiagnostica("DUMP diagnostico causa Eccezione", pingTagets, wwwTagets); + bool answ = false; + answ = scriviLog(string.Format("[{0}] - {1}", tipo, testoLog)); + // se è un tipo EXCEPTION allora scrivo anche log diagnostico + if (tipo == tipoLog.EXCEPTION && enableDumpDiag) + { + try + { + string[] pingTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("pingTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text); + string[] wwwTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("wwwTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text); + // chiamo scrittura diagnostica + scriviDiagnostica("DUMP diagnostico causa Eccezione", pingTagets, wwwTagets); + } + catch + { } + } + return answ; } - catch - { } - } - return answ; - } - /// - /// scrive su log un dump di diagnostica - /// - /// Causale diagnostica - /// target per test PING - /// target x download www page - public void scriviDiagnostica(string testoLog, string[] pingTargets, string[] wwwTargets) - { - string txtDiag = ""; - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('+', 80))); - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('+', 80))); - scriviLog(string.Format("[{0}] - {1}{2}", tipoLog.DUMP_DIAGN, testoLog, Environment.NewLine)); - } - catch - { } - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("UPTIME", Diagnostica.uptime))); - } - catch - { } - - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("STORAGE", Diagnostica.diskUsage))); - } - catch - { } - - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("USB", Diagnostica.usbDevices))); - } - catch - { } - - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("SERIAL", Diagnostica.serialPorts))); - } - catch - { } - - try - { - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (interfaces)", Diagnostica.networkInterfaces))); - } - catch - { } - - try - { - // se richiesto faccio PING test - if (pingTargets.Length > 0) + /// + /// Esecuzione scrittura ThreadSafe + /// + /// + /// + public bool WriteToFileThreadSafe(string logPath, string text2write) { - txtDiag = ""; - foreach (string target in pingTargets) - { - txtDiag += SteamwareStrings.addLine(Diagnostica.pingIp(target)); - } - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (ping)", txtDiag))); + bool answ = false; + // Set Status to Locked + _readWriteLock.EnterWriteLock(); + try + { + // Append text to the file + using (StreamWriter sw = File.AppendText(logPath)) + { + sw.WriteLine(text2write); + sw.Close(); + answ = true; + } + } + finally + { + // Release lock + _readWriteLock.ExitWriteLock(); + } + return answ; } - } - catch - { } - try - { - // se richiesto faccio PING test - if (wwwTargets.Length > 0) + /// + /// formatta un blococ di diagnostica (titolo, contenuto / eccezione) + /// + /// + /// + /// + protected string formDiagBlock(string titolo, string contenuto) { - txtDiag = ""; - foreach (string target in wwwTargets) - { - txtDiag += SteamwareStrings.addLine(string.Format("WebPage Test ({2}): {0}{1}", Environment.NewLine, Diagnostica.getPageContent(target), target)); - } - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (www)", txtDiag))); + string answ = SteamwareStrings.charTitle(titolo, '-', 60); + try + { + answ += SteamwareStrings.addLine(contenuto); + } + catch + { + answ += string.Format("Errore diagnostica {0}", titolo); + } + return answ; } - } - catch - { } - // chiudo - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('-', 80))); - scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('-', 80))); - } - /// - /// formatta un blococ di diagnostica (titolo, contenuto / eccezione) - /// - /// - /// - /// - protected string formDiagBlock(string titolo, string contenuto) - { - string answ = SteamwareStrings.charTitle(titolo, '-', 60); - try - { - answ += SteamwareStrings.addLine(contenuto); - } - catch - { - answ += string.Format("Errore diagnostica {0}", titolo); - } - return answ; - } - - - #endregion - - #region metodi privati - - /// - /// fornisce il nome del file in cui loggare (ed eventualmente crea...) - /// - protected void newLogfileName() - { - DateTime CurrentDateTime = DateTime.Now; - _logfileName = _logBaseDir + String.Format("{0}.log", CurrentDateTime.ToString("yyyyMMdd")); - } - /// - /// provvede a verificare la dim della cartella dei log e cancella i + vecchi fino a restare a dim inferiori a _logMaxMb - /// - protected void shrinkDir() - { - // ottengo elenco files *.log - fileMover.obj.setDirectory(_logBaseDir); - FileInfo[] _fis = fileMover.obj.elencoFiles_FI("*.log"); - compressAndRemove(_fis); - // acnhe per i "Vecchi" formati .txt - _fis = fileMover.obj.elencoFiles_FI("*.txt"); - compressAndRemove(_fis); - } - - private void compressAndRemove(FileInfo[] _fis) - { - foreach (FileInfo _file in _fis) - { - if (_file.CreationTime < DateTime.Now.AddDays(-2)) // zippo files + vecchi di 2 gg... + /// + /// Vera chiamata scrittura log x override con gestione REDIS di calmierazione + /// + /// + /// + private bool doScriviLog(string _testoPre) { - fileMover.obj.zippaSingoloFile(_file); - // cancello l'originale... - fileMover.obj.eliminaFile(_file); + bool fatto = false; + // attenzione: rimpiazzo eventuali "
" con newline... + string _testo = string.Format("{0:H:mm:ss ffff} \t{1}", DateTime.Now, _testoPre.Replace("
", Environment.NewLine).Replace("
", Environment.NewLine).Replace("
", Environment.NewLine)); + // se è configurato x shrink ed è passato almeno 1 gg da ultimo check... + if (_doShrinkFolder && lastDirCheck.AddDays(1) < DateTime.Now) + { + // verifica dim directory ed eventualmente cancella... - opzionale + shrinkDir(); + // salvo nuova ora di check + lastDirCheck = DateTime.Now; + } + // (ri)genera il nome del file di log... + newLogfileName(); + // scrivo thread safe + fatto = WriteToFileThreadSafe(_logfileName, _testo); + return fatto; } - } - // verifico directory e dimensione... - while (fileMover.obj.totalMb() > _logMaxMb) - { - // cancello i + vecchi fino a rientrare alla dimensione max... - fileMover.obj.deleteOldest(); - } - } - /// - /// fornisce il file + vecchio - /// - /// - /// - protected void deleteOldest(DirectoryInfo _di) - { - FileInfo[] _fis = _di.GetFiles(); - DateTime _oldest = DateTime.Now; - string _nome = ""; - foreach (FileInfo _file in _fis) - { - if (_file.CreationTime < _oldest) + #endregion metodi esposti + + #region metodi privati + + /// + /// fornisce il file + vecchio + /// + /// + /// + protected void deleteOldest(DirectoryInfo _di) { - _nome = _file.Name; + FileInfo[] _fis = _di.GetFiles(); + DateTime _oldest = DateTime.Now; + string _nome = ""; + foreach (FileInfo _file in _fis) + { + if (_file.CreationTime < _oldest) + { + _nome = _file.Name; + } + } + FileInfo fi = new FileInfo(_nome); + fi.Delete(); } - } - FileInfo fi = new FileInfo(_nome); - fi.Delete(); - } - #endregion - } - /// - /// tipo di log ammesso - /// - public enum tipoLog - { - /// - /// informazioni di debug - /// - DEBUG, - /// - /// dump diagnostica - /// - DUMP_DIAGN, - /// - /// errori - /// - ERROR, - /// - /// eccezioni nell'esecuzione try/catch - /// - EXCEPTION, - /// - /// errori fatali - /// - FATAL, - /// - /// informazioni opzionali - /// - INFO, - /// - /// log dei lemmi invocati per traduzione da vocabolario - /// - LEMMA, - /// - /// fase di avvio componente - /// - STARTUP, - /// - /// avvisi - /// - WARNING - } -} + /// + /// fornisce il nome del file in cui loggare (ed eventualmente crea...) + /// + protected void newLogfileName() + { + DateTime CurrentDateTime = DateTime.Now; + _logfileName = _logBaseDir + String.Format("{0}.log", CurrentDateTime.ToString("yyyyMMdd")); + } + + /// + /// provvede a verificare la dim della cartella dei log e cancella i + vecchi fino a restare a dim inferiori a _logMaxMb + /// + protected void shrinkDir() + { + // ottengo elenco files *.log + fileMover.obj.setDirectory(_logBaseDir); + FileInfo[] _fis = fileMover.obj.elencoFiles_FI("*.log"); + compressAndRemove(_fis); + // acnhe per i "Vecchi" formati .txt + _fis = fileMover.obj.elencoFiles_FI("*.txt"); + compressAndRemove(_fis); + } + + private void compressAndRemove(FileInfo[] _fis) + { + foreach (FileInfo _file in _fis) + { + if (_file.CreationTime < DateTime.Now.AddDays(-2)) // zippo files + vecchi di 2 gg... + { + fileMover.obj.zippaSingoloFile(_file); + // cancello l'originale... + fileMover.obj.eliminaFile(_file); + } + } + // verifico directory e dimensione... + while (fileMover.obj.totalMb() > _logMaxMb) + { + // cancello i + vecchi fino a rientrare alla dimensione max... + fileMover.obj.deleteOldest(); + } + } + + #endregion metodi privati + } +} \ No newline at end of file From 70ac609d1549afaf8a5d7e2153f4376958f4b3b1 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 2 Oct 2020 15:50:37 +0200 Subject: [PATCH 3/3] Revisione metodi di veto log su Redis x evitare esplosione chaivi... --- Jenkinsfile | 2 +- SteamWare.Logger/SteamWare.Logger.csproj | 18 - SteamWareLib/logger.cs | 100 +- SteamWareLib/memLayer.cs | 4343 +++++++++++----------- 4 files changed, 2305 insertions(+), 2158 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index ba072e3..5efa16d 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -7,7 +7,7 @@ pipeline { steps { /* calcolo numero versione... diverso x branch MASTER/DEVELOP */ script { - withEnv(['NEXT_BUILD_NUMBER=739']) { + withEnv(['NEXT_BUILD_NUMBER=740']) { // env.versionNumber = VersionNumber(versionNumberString : '4.9.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true) env.versionNumber = VersionNumber(versionNumberString : '4.9.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}') env.versionNumberBeta = VersionNumber(versionNumberString : '4.9.${BUILD_DATE_FORMATTED, "yyMM"}-beta.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}') diff --git a/SteamWare.Logger/SteamWare.Logger.csproj b/SteamWare.Logger/SteamWare.Logger.csproj index 195c06e..26ba1a9 100644 --- a/SteamWare.Logger/SteamWare.Logger.csproj +++ b/SteamWare.Logger/SteamWare.Logger.csproj @@ -52,13 +52,6 @@ SteamWare.cs - - True - True - DS_logging.xsd - - - @@ -67,17 +60,6 @@ .editorconfig
- - DS_logging.xsd - - - MSDataSetGenerator - DS_logging.Designer.cs - Designer - - - DS_logging.xsd - Always diff --git a/SteamWareLib/logger.cs b/SteamWareLib/logger.cs index 8c810d7..ecd345c 100644 --- a/SteamWareLib/logger.cs +++ b/SteamWareLib/logger.cs @@ -207,42 +207,36 @@ namespace SteamWare } catch { } - try { scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("UPTIME", Diagnostica.uptime))); } catch { } - try { scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("STORAGE", Diagnostica.diskUsage))); } catch { } - try { scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("USB", Diagnostica.usbDevices))); } catch { } - try { scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("SERIAL", Diagnostica.serialPorts))); } catch { } - try { scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (interfaces)", Diagnostica.networkInterfaces))); } catch { } - try { // se richiesto faccio PING test @@ -258,7 +252,6 @@ namespace SteamWare } catch { } - try { // se richiesto faccio PING test @@ -274,7 +267,6 @@ namespace SteamWare } catch { } - // chiudo scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('-', 80))); scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('-', 80))); @@ -283,14 +275,15 @@ namespace SteamWare /// /// scrive sul file log di default il valore della variabile string passata su una riga... (tab delim?!?) /// - /// testo iniziale del log + /// TOPIC del log + /// Contenuto del log /// - public bool scriviLog(string _testoPre) + public bool scriviLog(string topic, string fullMessage) { bool needWrite = false; bool fatto = false; // preparo hash redis - string hKey = _testoPre.Replace(":", "_").Replace("/", "_").Replace("#", "_").Replace("(", "").Replace(")", "").Replace("|", "_").Replace(" ", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_"); + string hKey = topic.Replace(":", "_").Replace("/", "_").Replace("#", "_").Replace("(", "").Replace(")", "").Replace("|", "_").Replace(" ", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_"); //se troppo lunga trimmo... if (hKey.Length > 100) { @@ -315,7 +308,7 @@ namespace SteamWare { // cerco se ho un veto precedente in redis string vetoPar = memLayer.ML.getRSV(hVetoErrore); - if (vetoPar != null && vetoPar != "") + if (!string.IsNullOrEmpty(vetoPar)) { needWrite = false; } @@ -327,6 +320,8 @@ namespace SteamWare needWrite = true; } memLayer.ML.setRCntI(hCountErrore); + // controllo eventuali messaggi vecchi da "scodare" dal log redis + purgeOldVeto(); } else { @@ -342,26 +337,63 @@ namespace SteamWare if (numRep > 1) { // cambio messaggio con un inizio pari al num di ripetizioni... - _testoPre = string.Format("{0} x {1}", numRep, _testoPre); + fullMessage = string.Format("{0} x {1}", numRep, fullMessage); } // reset counter memLayer.ML.resetRCnt(hCountErrore); } - fatto = doScriviLog(_testoPre); + fatto = doScriviLog(fullMessage); } return fatto; } + /// + /// scrive sul file log di default il valore della variabile string passata su una riga... (tab delim?!?) + /// + /// testo iniziale del log + /// + public bool scriviLog(string fullMessage) + { + return scriviLog(fullMessage, fullMessage); + } + /// /// scrive un messaggio di log con etichetta pre /// - /// testo messaggio + /// testo messaggio /// tipo di log da registrare (etichetta [...]) /// - public bool scriviLog(string testoLog, tipoLog tipo) + public bool scriviLog(string fullMessage, tipoLog tipo) { bool answ = false; - answ = scriviLog(string.Format("[{0}] - {1}", tipo, testoLog)); + answ = scriviLog(string.Format("[{0}] - {1}", tipo, fullMessage)); + // se è un tipo EXCEPTION allora scrivo anche log diagnostico + if (tipo == tipoLog.EXCEPTION && enableDumpDiag) + { + try + { + string[] pingTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("pingTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text); + string[] wwwTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("wwwTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text); + // chiamo scrittura diagnostica + scriviDiagnostica("DUMP diagnostico causa Eccezione", pingTagets, wwwTagets); + } + catch + { } + } + return answ; + } + + /// + /// scrive un messaggio di log con etichetta pre + /// + /// topic messaggio + /// testo messaggio + /// tipo di log da registrare (etichetta [...]) + /// + public bool scriviLog(string topic, string fullMessage, tipoLog tipo) + { + bool answ = false; + answ = scriviLog($"{tipo}:{topic}", $"[{tipo}] - {fullMessage}"); // se è un tipo EXCEPTION allora scrivo anche log diagnostico if (tipo == tipoLog.EXCEPTION && enableDumpDiag) { @@ -451,6 +483,40 @@ namespace SteamWare return fatto; } + /// + /// Effettua verifica e pulizia eventuali vecchi messaggi errore... + /// + private void purgeOldVeto() + { + // limite minimo di chaivi salvate per cui procedere coi controlli + int checkLimit = 100; + // limito cleanup x avere un operazione graduale... + int maxCleanup = checkLimit / 2; + // parto recuperando i valori VETO.... se > 100... + string redKeyCounters = memLayer.ML.redHash("Logger:Counter:*"); + int numCount = memLayer.ML.redCountKey(redKeyCounters); + if (numCount > checkLimit) + { + var redKeysList2check = memLayer.ML.redGetKeys(redKeyCounters); + foreach (StackExchange.Redis.RedisKey item in redKeysList2check) + { + // cerco il duale... se NON lo trovo + if (!memLayer.ML.redHashPresentSz(item.ToString().Replace(":Logger:Counter:", ":Logger:Veto:"))) + { + // loggo! + doScriviLog(item); + // elimino... + memLayer.ML.redDelKey(item); + maxCleanup--; + } + if (maxCleanup <= 0) + { + break; + } + } + } + } + #endregion metodi esposti #region metodi privati diff --git a/SteamWareLib/memLayer.cs b/SteamWareLib/memLayer.cs index 7c0114b..2715664 100644 --- a/SteamWareLib/memLayer.cs +++ b/SteamWareLib/memLayer.cs @@ -10,2229 +10,2328 @@ using System.Web; namespace SteamWare { - /// - /// layer gestione vari tipi di memoria: cache, session... - /// - public class memLayer - { - #region oggetti protected utilizzati - /// - /// lettore file configurazione + /// layer gestione vari tipi di memoria: cache, session... /// - protected AppSettingsReader configAppSetReader; - - #endregion - - /// - /// Table adapter accesso conf parameters - /// - public DS_UtilityTableAdapters.ConfigTableAdapter taConfig; - - /// - /// Table adapter accesso conf parameters TMP (x import/check) - /// - public DS_UtilityTableAdapters.ConfigTmpTableAdapter taConfigTmp; - - /// - /// oggetto singleton x accesso al layer di memoria - /// - public static memLayer ML = new memLayer(); - /// - /// Verifica se si debba serializzare ogni valore complesso (tabelle/righe) in sessione (per impiego di sessioni avanzate come Redis) - /// - public bool serializeSession + public class memLayer { - get - { - return CRB("serializeSession"); - } - } + #region oggetti protected utilizzati - /// - /// classe gestione accessi a Session, cache, viewstate, configuration... - /// - protected memLayer() - { - // istanzia il conf setting reader... - configAppSetReader = new AppSettingsReader(); - // avvio e configuro TA - initTA(); - setupConnectionStringBase(); - setupMongo(); - } + /// + /// lettore file configurazione + /// + protected AppSettingsReader configAppSetReader; - /// - /// init dei table adapters - /// - protected void initTA() - { - taConfig = new DS_UtilityTableAdapters.ConfigTableAdapter(); - taConfigTmp = new DS_UtilityTableAdapters.ConfigTmpTableAdapter(); - } - /// - /// stringa conn x DB CONF - /// - protected string connStringDbConf - { - get - { - string answ = ""; - answ = confReadString("DbConfConnectionString"); - // se fosse vuota fallback a path dei permessi... - if (string.IsNullOrEmpty(answ)) + #endregion oggetti protected utilizzati + + /// + /// oggetto singleton x accesso al layer di memoria + /// + public static memLayer ML = new memLayer(); + + /// + /// Table adapter accesso conf parameters + /// + public DS_UtilityTableAdapters.ConfigTableAdapter taConfig; + + /// + /// Table adapter accesso conf parameters TMP (x import/check) + /// + public DS_UtilityTableAdapters.ConfigTmpTableAdapter taConfigTmp; + + /// + /// classe gestione accessi a Session, cache, viewstate, configuration... + /// + protected memLayer() { - answ = confReadString("PermessiConnectionString"); + // istanzia il conf setting reader... + configAppSetReader = new AppSettingsReader(); + // avvio e configuro TA + initTA(); + setupConnectionStringBase(); + setupMongo(); } - // se ancora vuota --> devAuth - if (string.IsNullOrEmpty(answ)) + + /// + /// Verifica se si debba serializzare ogni valore complesso (tabelle/righe) in sessione (per impiego di sessioni avanzate come Redis) + /// + public bool serializeSession { - answ = confReadString("DevicesAuthConnectionString"); - } - return answ; - } - } - - /// - /// effettua setup dei connection strings da web.config delal singola applicazione - /// - protected virtual void setupConnectionStringBase() - { - // connections del db - taConfig.Connection.ConnectionString = connStringDbConf; - taConfigTmp.Connection.ConnectionString = connStringDbConf; - } - - #region area gestione config su DB - - /// - /// Nome della variabile AppConf da utilizzare... - /// - public string ACBH - { - get - { - string answ = "AppConf"; - try - { - answ = string.Format("{0}:{1}:{2}:AppConf", confReadString("CodModulo"), taConfig.Connection.DataSource, taConfig.Connection.Database).Replace("\\", "_"); - } - catch - { } - return answ; - } - } - - /// - /// oggetto dizionario con chiave / valore x configurazioni applicazione - /// - public Dictionary AppConf; - /// - /// resetta AppConfig svuotando e rileggendo i dati... - /// - public void resetAppConf() - { - redDelKey(ACBH); - startupAppConf(); - } - /// - /// avvio oggetto AppConf in ram - /// - protected void startupAppConf() - { - // SOLO SE ho la chiave x abilitare config su DB... - if (confReadString("DbConfConnectionString") != "") - { - try - { - if (redKeyPresent(ACBH)) - { - AppConf = new Dictionary(); - foreach (var item in redGetHash(ACBH)) + get { - if (AppConf.ContainsKey(item.Key)) - { - AppConf[item.Key] = item.Value; - } - else - { - AppConf.Add(item.Key, item.Value); - } + return CRB("serializeSession"); } - } - else - { - AppConf = ricaricaAppConf(); - KeyValuePair[] valori = new KeyValuePair[AppConf.Count]; - int i = 0; - foreach (var item in AppConf) - { - valori[i] = new KeyValuePair(item.Key, item.Value); - i++; - } - // salvo in redis valori (con TTL) - redSaveHash(ACBH, valori, maxAgeAppConf); - logger.lg.scriviLog("Completato procedura startupAppConf ", tipoLog.INFO); - } } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in startupAppConf:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - } - } - /// - /// Numero record salvati in AppConf - /// - public int numRecAppConf - { - get - { - int answ = 0; - try - { - answ = AppConf.Count; - } - catch - { } - return answ; - } - } - /// - /// carica in ram oggetto AppConf - /// - /// - protected Dictionary ricaricaAppConf() - { - Dictionary answ = new Dictionary(); - // istanzio un NUOVO oggetto x evitare problemi init contestuali - memLayer nML = new memLayer(); - var tabDati = nML.taConfig.GetData(); - // carico - foreach (DS_Utility.ConfigRow riga in tabDati) - { - try - { - answ.Add(riga.chiave, riga.valore); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore procedura ricaricaAppConf per kvp: {0} / {1}{2}{3}", riga.chiave, riga.valore, Environment.NewLine, exc), tipoLog.EXCEPTION); - } - } - // log ricarica - logger.lg.scriviLog(string.Format("Effettuata procedura ricaricaAppConf per {0} records", answ.Count), tipoLog.INFO); - return answ; - } - /// - /// Recupera il TTL x appConf (secondi) - /// - public int maxAgeAppConf - { - get - { - // default 5 minuti x refresh... - int maxAge = 5; - try - { - maxAge = confReadInt("maxAgeAppConf_min"); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in lettura valore maxAgeAppConf_min{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return maxAge * 60; - } - } - /// - /// Configurations da tabella DB Config - /// - /// Valore chiave - /// - public string configDbVal(string chiave) - { - string answ = ""; - if (confReadString("DbConfConnectionString") != "") - { - // verifico esista oggetto... - if (AppConf == null) + /// + /// stringa conn x DB CONF + /// + protected string connStringDbConf { - resetAppConf(); + get + { + string answ = ""; + answ = confReadString("DbConfConnectionString"); + // se fosse vuota fallback a path dei permessi... + if (string.IsNullOrEmpty(answ)) + { + answ = confReadString("PermessiConnectionString"); + } + // se ancora vuota --> devAuth + if (string.IsNullOrEmpty(answ)) + { + answ = confReadString("DevicesAuthConnectionString"); + } + return answ; + } } - if (AppConf != null) + + /// + /// init dei table adapters + /// + protected void initTA() { - // controllo se ho dati, altrimenti rileggo - if (AppConf.Count == 0) - { - resetAppConf(); - } - // controllo SE in redis ci sia ancora il valore, altrimenti rileggo... - if (!redKeyPresent(ACBH)) - { - logger.lg.scriviLog(string.Format("Manca HASH in redis --> rileggo da DB --> REDIS --> Memoria | {0} | {1}", ACBH, chiave), tipoLog.INFO); - resetAppConf(); - } - // provo a leggere da DICT - if (AppConf.ContainsKey(chiave)) - { + taConfig = new DS_UtilityTableAdapters.ConfigTableAdapter(); + taConfigTmp = new DS_UtilityTableAdapters.ConfigTmpTableAdapter(); + } + + /// + /// effettua setup dei connection strings da web.config delal singola applicazione + /// + protected virtual void setupConnectionStringBase() + { + // connections del db + taConfig.Connection.ConnectionString = connStringDbConf; + taConfigTmp.Connection.ConnectionString = connStringDbConf; + } + + #region area gestione config su DB + + /// + /// oggetto dizionario con chiave / valore x configurazioni applicazione + /// + public Dictionary AppConf; + + /// + /// Nome della variabile AppConf da utilizzare... + /// + public string ACBH + { + get + { + string answ = "AppConf"; + try + { + answ = string.Format("{0}:{1}:{2}:AppConf", confReadString("CodModulo"), taConfig.Connection.DataSource, taConfig.Connection.Database).Replace("\\", "_"); + } + catch + { } + return answ; + } + } + + /// + /// Recupera il TTL x appConf (secondi) + /// + public int maxAgeAppConf + { + get + { + // default 5 minuti x refresh... + int maxAge = 5; + try + { + maxAge = confReadInt("maxAgeAppConf_min"); + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in lettura valore maxAgeAppConf_min{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + } + return maxAge * 60; + } + } + + /// + /// Numero record salvati in AppConf + /// + public int numRecAppConf + { + get + { + int answ = 0; + try + { + answ = AppConf.Count; + } + catch + { } + return answ; + } + } + + /// + /// Configurations da tabella DB Config (short form wrapper) + /// + /// Valore chiave + /// + public string cdv(string chiave) + { + return configDbVal(chiave); + } + + /// + /// Configurations da tabella DB Config (short form wrapper) convertito a bOOL + /// + /// Valore chiave + /// + public bool cdvb(string chiave) + { + bool answ = false; + string sVal = configDbVal(chiave); + if (sVal != "") + { + try + { + //answ = Convert.ToBoolean(configDbVal(chiave)); + bool fatto = bool.TryParse(sVal, out answ); + if (!fatto) + { + logger.lg.scriviLog($"Errore in lettura chiave [{chiave}] durante cdvb: ricevuto {sVal}", tipoLog.EXCEPTION); + } + } + catch (Exception exc) + { + logger.lg.scriviLog($"Errore in lettura chiave [{chiave}] durante cdvb{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + } + } + return answ; + } + + /// + /// Configurations da tabella DB Config (short form wrapper) convertito a INT + /// + /// Valore chiave + /// + public int cdvi(string chiave) + { + int answ = -1; + string sVal = configDbVal(chiave); + if (sVal != "") + { + try + { + //answ = Convert.ToInt32(configDbVal(chiave)); + bool fatto = int.TryParse(sVal, out answ); + if (!fatto) + { + logger.lg.scriviLog($"Errore in lettura chiave [{chiave}] durante cdvi: ricevuto {sVal}", tipoLog.EXCEPTION); + } + } + catch (Exception exc) + { + logger.lg.scriviLog($"Errore in lettura chiave [{chiave}] durante cdvi{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + } + } + return answ; + } + + /// + /// Configurations da tabella DB Config + /// + /// Valore chiave + /// + public string configDbVal(string chiave) + { + string answ = ""; + if (confReadString("DbConfConnectionString") != "") + { + // verifico esista oggetto... + if (AppConf == null) + { + resetAppConf(); + } + if (AppConf != null) + { + // controllo se ho dati, altrimenti rileggo + if (AppConf.Count == 0) + { + resetAppConf(); + } + // controllo SE in redis ci sia ancora il valore, altrimenti rileggo... + if (!redKeyPresent(ACBH)) + { + logger.lg.scriviLog(string.Format("Manca HASH in redis --> rileggo da DB --> REDIS --> Memoria | {0} | {1}", ACBH, chiave), tipoLog.INFO); + resetAppConf(); + } + // provo a leggere da DICT + if (AppConf.ContainsKey(chiave)) + { + try + { + answ = AppConf[chiave]; + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in lettura AppConf[{0}] durante configDbVal{1}{2}", chiave, Environment.NewLine, exc), tipoLog.EXCEPTION); + } + } + } + } + return answ; + } + + /// + /// resetta AppConfig svuotando e rileggendo i dati... + /// + public void resetAppConf() + { + redDelKey(ACBH); + startupAppConf(); + } + + /// + /// carica in ram oggetto AppConf + /// + /// + protected Dictionary ricaricaAppConf() + { + Dictionary answ = new Dictionary(); + // istanzio un NUOVO oggetto x evitare problemi init contestuali + memLayer nML = new memLayer(); + var tabDati = nML.taConfig.GetData(); + // carico + foreach (DS_Utility.ConfigRow riga in tabDati) + { + try + { + answ.Add(riga.chiave, riga.valore); + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore procedura ricaricaAppConf per kvp: {0} / {1}{2}{3}", riga.chiave, riga.valore, Environment.NewLine, exc), tipoLog.EXCEPTION); + } + } + // log ricarica + logger.lg.scriviLog(string.Format("Effettuata procedura ricaricaAppConf per {0} records", answ.Count), tipoLog.INFO); + return answ; + } + + /// + /// avvio oggetto AppConf in ram + /// + protected void startupAppConf() + { + // SOLO SE ho la chiave x abilitare config su DB... + if (confReadString("DbConfConnectionString") != "") + { + try + { + if (redKeyPresent(ACBH)) + { + AppConf = new Dictionary(); + foreach (var item in redGetHash(ACBH)) + { + if (AppConf.ContainsKey(item.Key)) + { + AppConf[item.Key] = item.Value; + } + else + { + AppConf.Add(item.Key, item.Value); + } + } + } + else + { + AppConf = ricaricaAppConf(); + KeyValuePair[] valori = new KeyValuePair[AppConf.Count]; + int i = 0; + foreach (var item in AppConf) + { + valori[i] = new KeyValuePair(item.Key, item.Value); + i++; + } + // salvo in redis valori (con TTL) + redSaveHash(ACBH, valori, maxAgeAppConf); + logger.lg.scriviLog("Completato procedura startupAppConf ", tipoLog.INFO); + } + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in startupAppConf:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + } + } + } + + #endregion area gestione config su DB + + #region utility gestione conf settings + + /// + /// legge dalla config un valore bool + /// + /// + /// + public bool confReadBool(string nomeParam) + { + bool answ = false; try { - answ = AppConf[chiave]; + answ = (bool)configAppSetReader.GetValue(nomeParam, typeof(bool)); + } + catch + { } + return answ; + } + + /// + /// legge dalla config un valore int + /// + /// + /// + public double confReadDouble(string nomeParam) + { + double answ = -1; + try + { + answ = Convert.ToDouble(configAppSetReader.GetValue(nomeParam, typeof(double))); + } + catch + { } + return answ; + } + + /// + /// legge dalla config un valore int + /// + /// + /// + public int confReadInt(string nomeParam) + { + int answ = -1; + try + { + answ = (int)configAppSetReader.GetValue(nomeParam, typeof(int)); + } + catch + { } + return answ; + } + + /// + /// legge dalla config un valore string + /// + /// + /// + public string confReadString(string nomeParam) + { + string answ = ""; + try + { + answ = (string)configAppSetReader.GetValue(nomeParam, typeof(string)); + } + catch + { } + return answ; + } + + /// + /// shot-form di confReadBool: legge dalla config un valore bool + /// + /// + /// + public bool CRB(string nomeParam) + { + bool answ = false; + // PROVO IN PRIMIS a cercare su DB... + if (cdv(nomeParam) != "") + { + answ = cdvb(nomeParam); + } + else + { + answ = confReadBool(nomeParam); + } + return answ; + } + + /// + /// shot-form di confReadDouble: legge dalla config un valore double + /// + /// + /// + public double CRD(string nomeParam) + { + double answ = -1; + // PROVO IN PRIMIS a cercare su DB... + try + { + answ = Convert.ToDouble(cdv(nomeParam)); + } + catch + { } + // se non trovato... + if (answ < 0) + { + answ = confReadDouble(nomeParam); + } + return answ; + } + + /// + /// shot-form di confReadInt: legge dalla config un valore int + /// + /// + /// + public int CRI(string nomeParam) + { + int answ = -1; + // PROVO IN PRIMIS a cercare su DB... + answ = cdvi(nomeParam); + // se non trovato... + if (answ < 0) + { + answ = confReadInt(nomeParam); + } + return answ; + } + + /// + /// shot-form di confReadString: legge dalla config un valore string + /// + /// + /// + public string CRS(string nomeParam) + { + string answ = ""; + // PROVO IN PRIMIS a cercare su DB... + answ = cdv(nomeParam); + if (string.IsNullOrEmpty(answ)) + { + answ = confReadString(nomeParam); + } + return answ; + } + + #endregion utility gestione conf settings + + #region utility gestione querystring, cookie, session e cache + + #region querystring + + /// + /// recupera valore querystring BOOL + /// + /// + /// valore string + public bool QSB(string nome) + { + bool answ = false; + try + { + answ = Convert.ToBoolean(HttpContext.Current.Request.QueryString[nome]); + } + catch + { } + return answ; + } + + /// + /// recupera valore querystring DATE + /// + /// + /// valore DATE + public DateTime QSD(string nome) + { + DateTime answ = DateTime.Now; + try + { + answ = Convert.ToDateTime(HttpContext.Current.Request.QueryString[nome]); + } + catch + { } + return answ; + } + + /// + /// recupera valore querystring INT + /// + /// + /// valore INT + public int QSI(string nome) + { + int answ = 0; + try + { + answ = Convert.ToInt32(HttpContext.Current.Request.QueryString[nome]); + } + catch + { } + return answ; + } + + /// + /// recupera valore querystring STRING + /// + /// + /// valore string + public string QSS(string nome) + { + string answ = ""; + if (HttpContext.Current.Request.QueryString[nome] != null) + { + try + { + answ = HttpContext.Current.Request.QueryString[nome].ToString().Trim(); + } + catch + { } + } + return answ; + } + + #endregion querystring + + #region session + + /// + /// carica dalla sessione un dato di tipo boolean (se vuoto false) + /// + /// + /// + public bool BoolSessionObj(string nomeVar) + { + if (HttpContext.Current.Session[nomeVar] != null) + { + return (bool)HttpContext.Current.Session[nomeVar]; + } + else + { + return false; + } + } + + /// + /// carica dalla sessione un dato di tipo DateTime + /// + /// + /// + public DateTime DateTimeSessionObj(string nomeVar) + { + DateTime answ = DateTime.Now; + // se li ho in sessione ricarico valori... + if (HttpContext.Current.Session[nomeVar] != null) + { + try + { + answ = Convert.ToDateTime(memLayer.ML.objSessionObj(nomeVar)); + } + catch + { + answ = DateTime.Now; + } + } + return answ; + } + + /// + /// carica dalla sessione un dato di tipo DataSet NON Tipizzato + /// + /// + /// + public DataSet dsSessionObj(string nomeVar) + { + if (HttpContext.Current.Session[nomeVar] != null) + { + string valSer = ML.StringSessionObj(nomeVar); + DataSet dataSet = JsonConvert.DeserializeObject(valSer); + return dataSet; + } + else + { + return null; + } + } + + /// + /// svuota una variabile dalla session + /// + /// + public bool emptySessionVal(string nome) + { + bool _done = false; + try + { + HttpContext.Current.Session.Remove(nome); + _done = true; + } + catch + { } + return _done; + } + + /// + /// carica dalla sessione un dato di tipo int + /// + /// + /// + public int IntSessionObj(string nomeVar) + { + if (HttpContext.Current.Session[nomeVar] != null) + { + return Convert.ToInt32(HttpContext.Current.Session[nomeVar].ToString()); + } + else + { + return -1; + } + } + + /// + /// restituisce true se sia presente in session l'oggetto richiesto + /// + /// + /// + public bool isInSessionObject(string nomeVar) + { + bool answ = false; + bool stringAnsw = false; + // cerco se ci sia... + try + { + //stringAnsw = (string)HttpContext.Current.Session[nomeVar].ToString() != ""; + stringAnsw = HttpContext.Current.Session[nomeVar] != null; + } + catch + { } + // infine condizione doppia... + try + { + answ = (HttpContext.Current.Session[nomeVar] != null && stringAnsw); + } + catch + { } + return answ; + } + + /// + /// carica dalla sessione un dato di tipo long + /// + /// + /// + public long LongSessionObj(string nomeVar) + { + if (HttpContext.Current.Session[nomeVar] != null) + { + return Convert.ToInt32(HttpContext.Current.Session[nomeVar].ToString()); + } + else + { + return 0; + } + } + + /// + /// carica dalla sessione un dato di tipo object generico + /// + /// + /// + public object objSessionObj(string nomeVar) + { + if (HttpContext.Current.Session[nomeVar] != null) + { + return HttpContext.Current.Session[nomeVar]; + } + else + { + return ""; + } + } + + /// + /// inserisce in session un DataSet (serializzandolo) + /// + /// nome della variabile + /// DataSet da salvare + public bool setSessionDataSet(string nome, DataSet dSet) + { + bool _done = false; + try + { + string dataSer = JsonConvert.SerializeObject(dSet); + _done = setSessionVal(nome, dataSer); + } + catch + { } + return _done; + } + + /// + /// inserisce in session un DataSet (serializzandolo) + /// + /// nome della variabile + /// DataSet da salvare + /// indica se debba sopravvivere ad update (inserita in elenco valSess2SurvUpd) + /// + public bool setSessionDataSet(string nome, DataSet dSet, bool surviveUpdate) + { + bool _done = false; + try + { + string dataSer = JsonConvert.SerializeObject(dSet); + _done = setSessionVal(nome, dataSer, surviveUpdate); + } + catch + { } + return _done; + } + + /// + /// inserisce in session un DataSet (serializzandolo) + /// + /// nome della variabile + /// DataTable da salvare + public bool setSessionDataTable(string nome, DataTable dTable) + { + bool _done = false; + try + { + DataSet dataSet = new DataSet("dataSet"); + dataSet.Tables.Add(dTable); + string dataSer = JsonConvert.SerializeObject(dataSet); + _done = setSessionVal(nome, dataSer); + } + catch + { } + return _done; + } + + /// + /// inserisce in session un DataSet (serializzandolo) + /// + /// nome della variabile + /// DataTable da salvare + /// indica se debba sopravvivere ad update (inserita in elenco valSess2SurvUpd) + public bool setSessionDataTable(string nome, DataTable dTable, bool surviveUpdate) + { + bool _done = false; + try + { + DataSet dataSet = new DataSet("dataSet"); + dataSet.Tables.Add(dTable); + string dataSer = JsonConvert.SerializeObject(dataSet); + _done = setSessionVal(nome, dataSer, surviveUpdate); + } + catch + { } + return _done; + } + + /// + /// inserisce in session un valore + /// + /// + /// + public bool setSessionVal(string nome, object valore) + { + bool _done = false; + try + { + HttpContext.Current.Session[nome] = valore; + _done = true; + } + catch + { } + return _done; + } + + /// + /// inserisce in session un valore + /// + /// nome della variabile + /// valore associato + /// indica se debba sopravvivere ad update (inserita in elenco valSess2SurvUpd) + /// + public bool setSessionVal(string nome, object valore, bool surviveUpdate) + { + bool _done = false; + try + { + HttpContext.Current.Session[nome] = valore; + if (surviveUpdate) + { + addValInSession(nome, valore.ToString()); + } + _done = true; + } + catch + { } + return _done; + } + + /// + /// carica dalla sessione un dato di tipo string + /// + /// + /// + public string StringSessionObj(string nomeVar) + { + string answ = ""; + try + { + if (HttpContext.Current.Session[nomeVar] != null) + { + answ = HttpContext.Current.Session[nomeVar].ToString(); + } + } + catch + { } + return answ; + } + + #endregion session + + #region cookie + + /// + /// elimina un cookie + /// + /// + public bool emptyCookieVal(string nome) + { + bool _done = false; + HttpCookie aCookie; + try + { + aCookie = new HttpCookie(nome); + aCookie.Expires = DateTime.Now.AddDays(-1); + HttpContext.Current.Response.Cookies.Add(aCookie); + _done = true; + } + catch + { } + return _done; + } + + /// + /// restituisco un valore da cookie + /// + /// + /// + public string getCookieVal(string nome) + { + string answ = ""; + if (hasCookieVal(nome)) + { + try + { + answ = HttpContext.Current.Request.Cookies[nome].Value; + } + catch + { } + } + return answ; + } + + /// + /// restituisco se ci sia un dato cookie + /// + /// + /// + public bool hasCookieVal(string nome) + { + bool answ = false; + if (HttpContext.Current.Request.Cookies[nome] != null) + { + try + { + answ = HttpContext.Current.Request.Cookies[nome].Value != ""; + } + catch + { } + } + return answ; + } + + /// + /// salvo un valore come cookie + /// + /// + /// + /// + public bool setCookieVal(string nome, string valore) + { + bool _done = false; + try + { + HttpCookie newCookie = new HttpCookie(nome, valore); + HttpContext.Current.Response.AppendCookie(newCookie); + _done = true; + } + catch + { } + return _done; + } + + /// + /// salvo un valore come cookie con expiry date esplicita + /// + /// + /// + /// + /// + public bool setCookieVal(string nome, string valore, DateTime expiryDate) + { + bool _done = false; + try + { + // rimuovo vecchio cookie + emptyCookieVal(nome); + // creo nuovo cookie + HttpCookie newCookie = new HttpCookie(nome, valore); + newCookie.Expires = expiryDate; + HttpContext.Current.Response.AppendCookie(newCookie); + _done = true; + } + catch + { } + return _done; + } + + #endregion cookie + + #region cache + + /// + /// Indica se usare la cache su REDIS (true) oppure cache applicativo IIS (false) + /// + public bool cacheOnRedis + { + get + { + bool answ = confReadBool("cacheOnRedis"); + return answ; + } + } + + /// + /// elenco dictionary delle tab in cache da aggiornare con update svuotando da cache... + /// + public Dictionary tabelleInCache + { + get + { + Dictionary answ = new Dictionary(); + try + { + var cacheVal = objCacheObj("tabelleInCache"); + if (cacheVal != null) + { + answ = JsonConvert.DeserializeObject>(cacheVal.ToString()); + } + } + catch (Exception exc) + { + answ = new Dictionary(); + logger.lg.scriviLog(string.Format("Errore in tabelleInCache{0}{1}", Environment.NewLine, exc)); + } + return answ; + } + set + { + string serVal = JsonConvert.SerializeObject(value); + setCacheVal("tabelleInCache", serVal); + } + } + + /// + /// elenco dictionary dei valori in session da NON aggiornare con update... + /// + public Dictionary valSess2SurvUpd + { + get + { + Dictionary answ = new Dictionary(); + if (isInSessionObject("valoriInSession2Survive")) + { + try + { + answ = (Dictionary)objSessionObj("valoriInSession2Survive"); + } + catch + { + answ = new Dictionary(); + } + } + return answ; + } + set + { + setSessionVal("valoriInSession2Survive", value); + } + } + + /// + /// aggiunge la stringa corrente nel dictionary delle tabelle messe in cache e da aggiornare su comando update + /// + /// + public void addTabInCache(string nuovaTab) + { + // provo ad aggiungere nuova tab in elenco... + Dictionary _tabelleInCache = tabelleInCache; + try + { + _tabelleInCache.Add(nuovaTab, nuovaTab); + tabelleInCache = _tabelleInCache; + } + catch + { } + } + + /// + /// aggiunge la stringa corrente nel dictionary delle tabelle messe in session che vanno preservate da comando update (es: oggetto selezionato...) + /// + /// + /// + public void addValInSession(string nomePar, string valore) + { + // provo ad aggiungere nuova tab in elenco... + Dictionary _valoriInSession2Survive = valSess2SurvUpd; + // verifico se fare update o insert... + if (_valoriInSession2Survive.ContainsKey(nomePar)) + { + // update, rimuovo vecchio valore... + try + { + _valoriInSession2Survive.Remove(nomePar); + } + catch + { } + } + // insert + try + { + _valoriInSession2Survive.Add(nomePar, valore); + valSess2SurvUpd = _valoriInSession2Survive; + } + catch + { } + } + + /// + /// carica dalla Cachee un dato di tipo boolean (se vuoto false) + /// + /// + /// + public bool BoolCacheObj(string nomeVar) + { + bool answ = false; + // ...se uso redis... + if (cacheOnRedis) + { + string redVal = JsonConvert.DeserializeObject(getRSV(redHash(nomeVar))).ToString(); + bool.TryParse(redVal, out answ); + } + else + { + if (HttpContext.Current.Cache[nomeVar] != null) + { + answ = (bool)HttpContext.Current.Cache[nomeVar]; + } + else + { + answ = false; + } + } + return answ; + } + + /// + /// svuota una variabile dalla Cache + /// + /// + public bool emptyCacheVal(string nomeVar) + { + bool _done = false; + if (cacheOnRedis) + { + redDelKey(redHash(nomeVar)); + } + else + { + try + { + HttpContext.Current.Cache.Remove(nomeVar); + _done = true; + } + catch + { } + } + return _done; + } + + /// + /// forza lo svuotamento delle tabelle indicate come in cache... + /// + public void flushRegisteredCache() + { + // elimino tutte le tab nella pos tabInCache... + foreach (KeyValuePair kvp in tabelleInCache) + { + if (cacheOnRedis) + { + redDelKey(redHash(kvp.Value)); + } + else + { + HttpContext.Current.Cache.Remove(kvp.Value); + } + } + if (cacheOnRedis) + { + redDelKey(redHash("tabelleInCache")); + } + else + { + HttpContext.Current.Cache.Remove("tabelleInCache"); + } + } + + /// + /// restituisce true se sia presente in cache l'oggetto richiesto + /// + /// + /// + public bool isInCacheObject(string nomeVar) + { + bool answ = false; + bool stringAnsw = false; + if (cacheOnRedis) + { + try + { + // cerco come key... + answ = redKeyPresent(redHash(nomeVar)); + if (!answ) + { + // cerco come hash... + answ = redHashPresent(redHash(nomeVar)); + } + // cerco come variabile se NON trovata... + if (!answ) + { + var redVal = getRSV(redHash(nomeVar)); + answ = redVal != null && redVal != ""; + } + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in verifica isInCacheObject REDIS per chiave{0}{1}{2}", nomeVar, Environment.NewLine, exc)); + } + } + else + { + // cerco di fare cast a stringa... + try + { + stringAnsw = HttpContext.Current.Cache[nomeVar].ToString() != ""; + } + catch + { } + // infine condizione doppia... + try + { + answ = (HttpContext.Current.Cache[nomeVar] != null && stringAnsw); + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in verifica isInCacheObject per chiave{0}{1}{2}", nomeVar, Environment.NewLine, exc)); + } + } + return answ; + } + + /// + /// carica dalla Cache un dato di tipo object generico + /// + /// + /// + public object objCacheObj(string nomeVar) + { + object answ = null; + // ...se uso redis... + if (cacheOnRedis) + { + answ = getRSV(redHash(nomeVar)); + } + else + { + if (HttpContext.Current.Cache[nomeVar] != null) + { + answ = HttpContext.Current.Cache[nomeVar]; + } + else + { + answ = ""; + } + } + return answ; + } + + /// + /// inserisce in Cache un valore + /// + /// nome della variabile + /// valore + public bool setCacheVal(string nomeVar, object valore) + { + bool _done = false; + if (cacheOnRedis) + { + setRSV(redHash(nomeVar), valore.ToString()); + _done = true; + } + else + { + try + { + HttpContext.Current.Cache[nomeVar] = valore; + _done = true; + } + catch + { } + } + return _done; + } + + /// + /// inserisce in Cache un valore e su richiesta regitra tra le tab in cache da svuotare on update.. + /// + /// nome della variabile + /// valore + /// da registrare come tabella da svuotare on update + /// + public bool setCacheVal(string nome, object valore, bool setInTabInCache) + { + bool _done = setCacheVal(nome, valore); + if (setInTabInCache) + { + addTabInCache(nome); + } + return _done; + } + + /// + /// carica dalla Cachee un dato di tipo string + /// + /// + /// + public string StringCacheObj(string nomeVar) + { + string answ = ""; + // ...se uso redis... + if (cacheOnRedis) + { + answ = JsonConvert.DeserializeObject(getRSV(redHash(nomeVar))).ToString(); + } + else + { + if (HttpContext.Current.Cache[nomeVar] != null) + { + answ = HttpContext.Current.Cache[nomeVar].ToString(); + } + else + { + answ = ""; + } + } + return answ; + } + + #endregion cache + + #endregion utility gestione querystring, cookie, session e cache + + #region gestione valori in RedisCache + + /// + /// Connessione lazy a redis... + /// + private Lazy lazyConnection = new Lazy(() => + { + string RedisConn = memLayer.ML.confReadString("RedisConn"); + if (string.IsNullOrEmpty(RedisConn)) + { + RedisConn = "localhost,abortConnect=false,ssl=false"; + } + + return ConnectionMultiplexer.Connect(RedisConn); + }); + + /// + /// Connessione lazy a redis... + /// + private Lazy lazyConnectionAdmin = new Lazy(() => + { + string RedisConnAdmin = memLayer.ML.confReadString("RedisConnAdmin"); + if (string.IsNullOrEmpty(RedisConnAdmin)) + { + RedisConnAdmin = "localhost,abortConnect=false,ssl=false,allowAdmin=true"; + } + + return ConnectionMultiplexer.Connect(RedisConnAdmin); + }); + + /// + /// Tipologia di ordinamento x liste KVP + /// + public enum kvpOrderBy + { + /// + /// Ordinamento ASCending per KEY + /// + KeyAsc, + + /// + /// Ordinamento DESCending per KEY + /// + KeyDesc, + + /// + /// Ordinamento ASCending per VAL + /// + ValAsc, + + /// + /// Ordinamento DESCending per VAL + /// + ValDesc + } + + /// + /// Oggetto DB REDIS corrente + /// + public IDatabase cache //currDB + { + get + { + IDatabase answ; + // se già valorizzato uso oggetto private... + if (_currDB != null) + { + answ = _currDB; + } + else + { + // init DB (sullo 0) + answ = connRedis.GetDatabase(); + // gestione override... + if (confReadInt("redisDb") >= 0) + { + // in questo caso uso il DB configurato in app.config... + answ = connRedis.GetDatabase(confReadInt("redisDb")); + } + _currDB = answ; + } + // restituisco oggetto DB + return answ; + } + } + + /// + /// Oggetto statico connessione redis + /// + public ConnectionMultiplexer connRedis + { + get + { + return lazyConnection.Value; + } + } + + /// + /// Oggetto statico connessione redis + /// + public ConnectionMultiplexer connRedisAdmin + { + get + { + return lazyConnectionAdmin.Value; + } + } + + /// + /// Restituisce numero record in Redis DB + /// + public long numRecRedis + { + get + { + long answ = 0; + try + { + foreach (var ep in connRedis.GetEndPoints()) + { + var server = connRedis.GetServer(ep); + answ += server.DatabaseSize(); + } + } + catch + { } + return answ; + } + } + + /// + /// Oggetto currentDb locale + /// + private IDatabase _currDB { get; set; } + + /// + /// Effettua comaprazione x VALORE in KVP ASC + /// + /// + /// + /// + public int CompareVal(KeyValuePair x, KeyValuePair y) + { + return x.Value.CompareTo(y.Value); + } + + /// + /// Effettua comaprazione x VALORE in KVP DESC + /// + /// + /// + /// + public int CompareValDesc(KeyValuePair x, KeyValuePair y) + { + return y.Value.CompareTo(x.Value); + } + + /// + /// Deserializzazione di un valore string in oggetto generico + /// + /// + /// + public object deserializeVal(string serVal) + { + object answ = ""; + try + { + answ = JsonConvert.DeserializeObject(serVal); + } + catch { } + return answ; + } + + /// + /// Restituisce una chiave COUNTER in RedisCache + /// + /// + /// + public int getRCnt(string chiave) + { + int answInt = 0; + string answ = ""; + try + { + answ = cache.StringGet(chiave); + answInt = Convert.ToInt32(answ); } catch (Exception exc) { - logger.lg.scriviLog(string.Format("Errore in lettura AppConf[{0}] durante configDbVal{1}{2}", chiave, Environment.NewLine, exc), tipoLog.EXCEPTION); + logger.lg.scriviLog(string.Format("Errore in getRSV:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); } - } + return answInt; } - } - return answ; - } - /// - /// Configurations da tabella DB Config (short form wrapper) - /// - /// Valore chiave - /// - public string cdv(string chiave) - { - return configDbVal(chiave); - } - /// - /// Configurations da tabella DB Config (short form wrapper) convertito a bOOL - /// - /// Valore chiave - /// - public bool cdvb(string chiave) - { - bool answ = false; - string sVal = configDbVal(chiave); - if (sVal != "") - { - try + + /// + /// Restituisce un pò di info sul server redis connesso + /// + /// + public string getRedisInfoData() { - //answ = Convert.ToBoolean(configDbVal(chiave)); - bool fatto = bool.TryParse(sVal, out answ); - if (!fatto) - { - logger.lg.scriviLog($"Errore in lettura chiave [{chiave}] durante cdvb: ricevuto {sVal}", tipoLog.EXCEPTION); - } + string answ = ""; + StringBuilder sb = new StringBuilder(); + try + { + sb.AppendLine($"Configuration: {connRedis.Configuration}"); + sb.AppendLine($"Connected: {connRedis.IsConnected}"); + sb.AppendLine($"ClientName: {connRedis.ClientName}"); + sb.AppendLine($"Total Ops: {connRedis.OperationCount}"); + sb.AppendLine($"Status: {connRedis.GetStatus()}"); + answ = sb.ToString(); + } + catch + { } + return answ; } - catch (Exception exc) + + /// + /// Restituisce un set KVP (Key Value Pair) salvati in RedisCache + /// + /// + /// + public RedisValue[] getRKeys(RedisKey[] chiavi) { - logger.lg.scriviLog($"Errore in lettura chiave [{chiave}] durante cdvb{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + RedisValue[] answ = null; + try + { + answ = cache.StringGet(chiavi); + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in getRKeys:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + } + return answ; } - } - return answ; - } - /// - /// Configurations da tabella DB Config (short form wrapper) convertito a INT - /// - /// Valore chiave - /// - public int cdvi(string chiave) - { - int answ = -1; - string sVal = configDbVal(chiave); - if (sVal != "") - { - try + + /// + /// Restituisce una chiave salvata in RedisCache + /// + /// + /// + public string getRSV(string chiave) { - //answ = Convert.ToInt32(configDbVal(chiave)); - bool fatto = int.TryParse(sVal, out answ); - if (!fatto) - { - logger.lg.scriviLog($"Errore in lettura chiave [{chiave}] durante cdvi: ricevuto {sVal}", tipoLog.EXCEPTION); - } + string answ = ""; + try + { + answ = cache.StringGet(chiave); + } + catch (Exception exc) + { + //logger.lg.scriviLog(string.Format("Errore in getRSV:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + } + return answ; } - catch (Exception exc) + + /// + /// Conta num oggetti cache redis che rispondono a pattern + /// + /// ** = tutti + /// + public int redCountKey(string keyPattern) { - logger.lg.scriviLog($"Errore in lettura chiave [{chiave}] durante cdvi{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + int answ = 0; + // cerco se ci sia valore in redis... + // se vuoto = ALL... + keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; + try + { + foreach (var ep in connRedis.GetEndPoints()) + { + var server = connRedis.GetServer(ep); + foreach (var key in server.Keys(pattern: keyPattern)) + { + answ++; + } + } + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("{0}", exc), tipoLog.EXCEPTION); + } + return answ; } - } - return answ; - } - #endregion - - #region utility gestione conf settings - - /// - /// shot-form di confReadBool: legge dalla config un valore bool - /// - /// - /// - public bool CRB(string nomeParam) - { - bool answ = false; - // PROVO IN PRIMIS a cercare su DB... - if (cdv(nomeParam) != "") - { - answ = cdvb(nomeParam); - } - else - { - answ = confReadBool(nomeParam); - } - return answ; - } - /// - /// legge dalla config un valore bool - /// - /// - /// - public bool confReadBool(string nomeParam) - { - bool answ = false; - try - { - answ = (bool)configAppSetReader.GetValue(nomeParam, typeof(bool)); - } - catch - { } - return answ; - } - - /// - /// shot-form di confReadString: legge dalla config un valore string - /// - /// - /// - public string CRS(string nomeParam) - { - string answ = ""; - // PROVO IN PRIMIS a cercare su DB... - answ = cdv(nomeParam); - if (string.IsNullOrEmpty(answ)) - { - answ = confReadString(nomeParam); - } - return answ; - } - /// - /// legge dalla config un valore string - /// - /// - /// - public string confReadString(string nomeParam) - { - string answ = ""; - try - { - answ = (string)configAppSetReader.GetValue(nomeParam, typeof(string)); - } - catch - { } - return answ; - } - - /// - /// shot-form di confReadInt: legge dalla config un valore int - /// - /// - /// - public int CRI(string nomeParam) - { - int answ = -1; - // PROVO IN PRIMIS a cercare su DB... - answ = cdvi(nomeParam); - // se non trovato... - if (answ < 0) - { - answ = confReadInt(nomeParam); - } - return answ; - } - /// - /// legge dalla config un valore int - /// - /// - /// - public int confReadInt(string nomeParam) - { - int answ = -1; - try - { - answ = (int)configAppSetReader.GetValue(nomeParam, typeof(int)); - } - catch - { } - return answ; - } - /// - /// shot-form di confReadDouble: legge dalla config un valore double - /// - /// - /// - public double CRD(string nomeParam) - { - double answ = -1; - // PROVO IN PRIMIS a cercare su DB... - try - { - answ = Convert.ToDouble(cdv(nomeParam)); - } - catch - { } - // se non trovato... - if (answ < 0) - { - answ = confReadDouble(nomeParam); - } - return answ; - } - /// - /// legge dalla config un valore int - /// - /// - /// - public double confReadDouble(string nomeParam) - { - double answ = -1; - try - { - answ = Convert.ToDouble(configAppSetReader.GetValue(nomeParam, typeof(double))); - } - catch - { } - return answ; - } - - - #endregion - - #region utility gestione querystring, cookie, session e cache - - #region querystring - - /// - /// recupera valore querystring STRING - /// - /// - /// valore string - public string QSS(string nome) - { - string answ = ""; - if (HttpContext.Current.Request.QueryString[nome] != null) - { - try + /// + /// Elimina una key (hash, string) + /// + /// + /// + public bool redDelKey(string key) { - answ = HttpContext.Current.Request.QueryString[nome].ToString().Trim(); + bool answ = false; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = key; + cache.KeyDelete(chiave); + answ = true; + } + catch + { } + return answ; } - catch - { } - } - return answ; - } - /// - /// recupera valore querystring INT - /// - /// - /// valore INT - public int QSI(string nome) - { - int answ = 0; - try - { - answ = Convert.ToInt32(HttpContext.Current.Request.QueryString[nome]); - } - catch - { } - return answ; - } - /// - /// recupera valore querystring BOOL - /// - /// - /// valore string - public bool QSB(string nome) - { - bool answ = false; - try - { - answ = Convert.ToBoolean(HttpContext.Current.Request.QueryString[nome]); - } - catch - { } - return answ; - } - /// - /// recupera valore querystring DATE - /// - /// - /// valore DATE - public DateTime QSD(string nome) - { - DateTime answ = DateTime.Now; - try - { - answ = Convert.ToDateTime(HttpContext.Current.Request.QueryString[nome]); - } - catch - { } - return answ; - } - #endregion - - #region session - - /// - /// carica dalla sessione un dato di tipo DataSet NON Tipizzato - /// - /// - /// - public DataSet dsSessionObj(string nomeVar) - { - if (HttpContext.Current.Session[nomeVar] != null) - { - string valSer = ML.StringSessionObj(nomeVar); - DataSet dataSet = JsonConvert.DeserializeObject(valSer); - return dataSet; - } - else - { - return null; - } - } - - /// - /// carica dalla sessione un dato di tipo object generico - /// - /// - /// - public object objSessionObj(string nomeVar) - { - if (HttpContext.Current.Session[nomeVar] != null) - { - return HttpContext.Current.Session[nomeVar]; - } - else - { - return ""; - } - } - - /// - /// carica dalla sessione un dato di tipo boolean (se vuoto false) - /// - /// - /// - public bool BoolSessionObj(string nomeVar) - { - if (HttpContext.Current.Session[nomeVar] != null) - { - return (bool)HttpContext.Current.Session[nomeVar]; - } - else - { - return false; - } - } - - /// - /// carica dalla sessione un dato di tipo string - /// - /// - /// - public string StringSessionObj(string nomeVar) - { - string answ = ""; - try - { - if (HttpContext.Current.Session[nomeVar] != null) + /// + /// Flush completo cache redis + /// + /// ** = tutti + /// + public bool redFlushKey(string keyPattern) { - answ = HttpContext.Current.Session[nomeVar].ToString(); + bool answ = false; + // cerco se ci sia valore in redis... + // se vuoto = ALL... + keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; + try + { + foreach (var ep in connRedis.GetEndPoints()) + { + var server = connRedis.GetServer(ep); + var keys = server.Keys(database: confReadInt("redisDb"), pattern: $"{keyPattern}*"); + foreach (var key in keys) + { + cache.KeyDelete(key); + } + } + answ = true; + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("{0}", exc), tipoLog.EXCEPTION); + } + return answ; } - } - catch - { } - return answ; - } - /// - /// carica dalla sessione un dato di tipo DateTime - /// - /// - /// - public DateTime DateTimeSessionObj(string nomeVar) - { - DateTime answ = DateTime.Now; - // se li ho in sessione ricarico valori... - if (HttpContext.Current.Session[nomeVar] != null) - { - try + /// + /// Restituisce oggetti cache redis che rispondono a pattern + /// + /// ** = tutti + /// Tipo di ordinamento per kvp + /// + public List> redGetCounterByKey(string keyPattern, kvpOrderBy orderBy) { - answ = Convert.ToDateTime(memLayer.ML.objSessionObj(nomeVar)); + int numAnsw = redCountKey(keyPattern); + RedisKey[] chiavi = new RedisKey[numAnsw]; + List> answ = new List>(); + // se vuoto = ALL... + keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; + + // recupero in primis elenco chiavi + try + { + int i = 0; + foreach (var ep in connRedis.GetEndPoints()) + { + var server = connRedis.GetServer(ep); + foreach (var key in server.Keys(pattern: keyPattern)) + { + chiavi[i] = key; + i++; + } + } + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("{0}", exc), tipoLog.EXCEPTION); + } + // ora recupero valori! + var valori = getRKeys(chiavi); + int currVal = 0; + // popolo rispsota + try + { + for (int i = 0; i < numAnsw; i++) + { + Int32.TryParse(valori[i], out currVal); + answ.Add(new KeyValuePair(chiavi[i], currVal)); + } + } + catch + { } + // se richiesto riordino... + switch (orderBy) + { + case kvpOrderBy.KeyAsc: + answ.Sort(CompareKey); + break; + + case kvpOrderBy.KeyDesc: + answ.Sort(CompareKeyDesc); + break; + + case kvpOrderBy.ValAsc: + answ.Sort(CompareVal); + break; + + case kvpOrderBy.ValDesc: + answ.Sort(CompareValDesc); + break; + + default: + break; + } + return answ; } - catch + + /// + /// Recupera tutti i valori dalla hash + /// + /// + /// + public KeyValuePair[] redGetHash(string hashKey) { - answ = DateTime.Now; + KeyValuePair[] answ = new KeyValuePair[1]; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + HashEntry[] valori = cache.HashGetAll(chiave); + answ = new KeyValuePair[valori.Length]; + int i = 0; + foreach (HashEntry item in valori) + { + answ[i] = new KeyValuePair(item.Name, item.Value); + i++; + } + } + catch + { } + return answ; } - } - return answ; - } - /// - /// carica dalla sessione un dato di tipo long - /// - /// - /// - public long LongSessionObj(string nomeVar) - { - if (HttpContext.Current.Session[nomeVar] != null) - { - return Convert.ToInt32(HttpContext.Current.Session[nomeVar].ToString()); - } - else - { - return 0; - } - } - - /// - /// carica dalla sessione un dato di tipo int - /// - /// - /// - public int IntSessionObj(string nomeVar) - { - if (HttpContext.Current.Session[nomeVar] != null) - { - return Convert.ToInt32(HttpContext.Current.Session[nomeVar].ToString()); - } - else - { - return -1; - } - } - - /// - /// inserisce in session un valore - /// - /// - /// - public bool setSessionVal(string nome, object valore) - { - bool _done = false; - try - { - HttpContext.Current.Session[nome] = valore; - _done = true; - } - catch - { } - return _done; - } - /// - /// inserisce in session un valore - /// - /// nome della variabile - /// valore associato - /// indica se debba sopravvivere ad update (inserita in elenco valSess2SurvUpd) - /// - public bool setSessionVal(string nome, object valore, bool surviveUpdate) - { - bool _done = false; - try - { - HttpContext.Current.Session[nome] = valore; - if (surviveUpdate) + /// + /// Recupera tutti i valori dalla hash in formato Dictionary + /// + /// + /// + public Dictionary redGetHashDict(string hashKey) { - addValInSession(nome, valore.ToString()); + Dictionary answ = new Dictionary(); + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + HashEntry[] valori = cache.HashGetAll(chiave); + foreach (HashEntry item in valori) + { + answ.Add(item.Name, item.Value); + } + } + catch + { } + return answ; } - _done = true; - } - catch - { } - return _done; - } - /// - /// inserisce in session un DataSet (serializzandolo) - /// - /// nome della variabile - /// DataTable da salvare - public bool setSessionDataTable(string nome, DataTable dTable) - { - bool _done = false; - try - { - DataSet dataSet = new DataSet("dataSet"); - dataSet.Tables.Add(dTable); - string dataSer = JsonConvert.SerializeObject(dataSet); - _done = setSessionVal(nome, dataSer); - } - catch - { } - return _done; - } - /// - /// inserisce in session un DataSet (serializzandolo) - /// - /// nome della variabile - /// DataTable da salvare - /// indica se debba sopravvivere ad update (inserita in elenco valSess2SurvUpd) - public bool setSessionDataTable(string nome, DataTable dTable, bool surviveUpdate) - { - bool _done = false; - try - { - DataSet dataSet = new DataSet("dataSet"); - dataSet.Tables.Add(dTable); - string dataSer = JsonConvert.SerializeObject(dataSet); - _done = setSessionVal(nome, dataSer, surviveUpdate); - } - catch - { } - return _done; - } - /// - /// inserisce in session un DataSet (serializzandolo) - /// - /// nome della variabile - /// DataSet da salvare - public bool setSessionDataSet(string nome, DataSet dSet) - { - bool _done = false; - try - { - string dataSer = JsonConvert.SerializeObject(dSet); - _done = setSessionVal(nome, dataSer); - } - catch - { } - return _done; - } - /// - /// inserisce in session un DataSet (serializzandolo) - /// - /// nome della variabile - /// DataSet da salvare - /// indica se debba sopravvivere ad update (inserita in elenco valSess2SurvUpd) - /// - public bool setSessionDataSet(string nome, DataSet dSet, bool surviveUpdate) - { - bool _done = false; - try - { - string dataSer = JsonConvert.SerializeObject(dSet); - _done = setSessionVal(nome, dataSer, surviveUpdate); - } - catch - { } - return _done; - } - - /// - /// svuota una variabile dalla session - /// - /// - public bool emptySessionVal(string nome) - { - bool _done = false; - try - { - HttpContext.Current.Session.Remove(nome); - _done = true; - } - catch - { } - return _done; - } - - /// - /// restituisce true se sia presente in session l'oggetto richiesto - /// - /// - /// - public bool isInSessionObject(string nomeVar) - { - bool answ = false; - bool stringAnsw = false; - // cerco se ci sia... - try - { - //stringAnsw = (string)HttpContext.Current.Session[nomeVar].ToString() != ""; - stringAnsw = HttpContext.Current.Session[nomeVar] != null; - } - catch - { } - // infine condizione doppia... - try - { - answ = (HttpContext.Current.Session[nomeVar] != null && stringAnsw); - } - catch - { } - return answ; - } - - #endregion - - #region cookie - - - /// - /// restituisco se ci sia un dato cookie - /// - /// - /// - public bool hasCookieVal(string nome) - { - bool answ = false; - if (HttpContext.Current.Request.Cookies[nome] != null) - { - try + /// + /// Recupera UN SINGOLO VALORE dalla hash per un dato field + /// + /// + /// + /// + public string redGetHashField(string hashKey, string hashField) { - answ = HttpContext.Current.Request.Cookies[nome].Value != ""; + string answ = ""; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + RedisValue campo = hashField; + RedisValue valOut = cache.HashGet(chiave, campo); + answ = valOut.ToString(); + } + catch + { } + return answ; } - catch - { } - } - return answ; - } - /// - /// restituisco un valore da cookie - /// - /// - /// - public string getCookieVal(string nome) - { - string answ = ""; - if (hasCookieVal(nome)) - { - try + /// + /// Elenco oggetti cache redis che rispondono a pattern + /// + /// ** = tutti + /// + public List redGetKeys(string keyPattern) { - answ = HttpContext.Current.Request.Cookies[nome].Value; + List answ = new List(); + // cerco se ci sia valore in redis... + // se vuoto = ALL... + keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; + try + { + foreach (var ep in connRedis.GetEndPoints()) + { + var server = connRedis.GetServer(ep); + foreach (var key in server.Keys(pattern: keyPattern)) + { + answ.Add(key); + } + } + } + catch (Exception exc) + { + Log.Instance.Error(exc, $"{exc}", tipoLog.EXCEPTION); + } + return answ; } - catch - { } - } - return answ; - } - /// - /// salvo un valore come cookie - /// - /// - /// - /// - public bool setCookieVal(string nome, string valore) - { - bool _done = false; - try - { - HttpCookie newCookie = new HttpCookie(nome, valore); - HttpContext.Current.Response.AppendCookie(newCookie); - _done = true; - } - catch - { } - return _done; - } - /// - /// salvo un valore come cookie con expiry date esplicita - /// - /// - /// - /// - /// - public bool setCookieVal(string nome, string valore, DateTime expiryDate) - { - bool _done = false; - try - { - // rimuovo vecchio cookie - emptyCookieVal(nome); - // creo nuovo cookie - HttpCookie newCookie = new HttpCookie(nome, valore); - newCookie.Expires = expiryDate; - HttpContext.Current.Response.AppendCookie(newCookie); - _done = true; - } - catch - { } - return _done; - } - /// - /// elimina un cookie - /// - /// - public bool emptyCookieVal(string nome) - { - bool _done = false; - HttpCookie aCookie; - try - { - aCookie = new HttpCookie(nome); - aCookie.Expires = DateTime.Now.AddDays(-1); - HttpContext.Current.Response.Cookies.Add(aCookie); - _done = true; - } - catch - { } - return _done; - } - #endregion + /// + /// Nome della variabile HASH da utilizzare (dato CodModulo / Server / DB impiegato da funzionalita' DbConfig) + keyName richiesto... + /// + public string redHash(string keyName) + { + string answ = keyName; + try + { + answ = string.Format("{0}:{1}:{2}:{3}", confReadString("CodModulo"), taConfig.Connection.DataSource, taConfig.Connection.Database, keyName).Replace("\\", "_"); + } + catch + { } + return answ; + } - #region cache + /// + /// Verifica se ci siano valori nella hash indicata... + /// + /// + /// + public bool redHashPresent(RedisKey key) + { + bool answ = false; + // cerco se ci sia valore in redis... + try + { + answ = cache.HashGetAll(key).Length > 0; + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in redHashPresent per la key {2}{0}{1}", Environment.NewLine, exc, key), tipoLog.EXCEPTION); + } + return answ; + } - /// - /// Indica se usare la cache su REDIS (true) oppure cache applicativo IIS (false) - /// - public bool cacheOnRedis - { - get - { - bool answ = confReadBool("cacheOnRedis"); - return answ; - } - } - /// - /// carica dalla Cache un dato di tipo object generico - /// - /// - /// - public object objCacheObj(string nomeVar) - { - object answ = null; - // ...se uso redis... - if (cacheOnRedis) - { - answ = getRSV(redHash(nomeVar)); - } - else - { - if (HttpContext.Current.Cache[nomeVar] != null) + /// + /// Verifica se ci siano valori nella hash indicata (string) + /// + /// + /// + public bool redHashPresentSz(string key) { - answ = HttpContext.Current.Cache[nomeVar]; + bool answ = false; + try + { + RedisKey chiave = key; + answ = redHashPresent(chiave); + } + catch + { } + return answ; } - else - { - answ = ""; - } - } - return answ; - } - /// - /// carica dalla Cachee un dato di tipo boolean (se vuoto false) - /// - /// - /// - public bool BoolCacheObj(string nomeVar) - { - bool answ = false; - // ...se uso redis... - if (cacheOnRedis) - { - string redVal = JsonConvert.DeserializeObject(getRSV(redHash(nomeVar))).ToString(); - bool.TryParse(redVal, out answ); - } - else - { - if (HttpContext.Current.Cache[nomeVar] != null) - { - answ = (bool)HttpContext.Current.Cache[nomeVar]; - } - else - { - answ = false; - } - } - return answ; - } - /// - /// carica dalla Cachee un dato di tipo string - /// - /// - /// - public string StringCacheObj(string nomeVar) - { - string answ = ""; - // ...se uso redis... - if (cacheOnRedis) - { - answ = JsonConvert.DeserializeObject(getRSV(redHash(nomeVar))).ToString(); - } - else - { - if (HttpContext.Current.Cache[nomeVar] != null) - { - answ = HttpContext.Current.Cache[nomeVar].ToString(); - } - else - { - answ = ""; - } - } - return answ; - } - /// - /// inserisce in Cache un valore - /// - /// nome della variabile - /// valore - public bool setCacheVal(string nomeVar, object valore) - { - bool _done = false; - if (cacheOnRedis) - { - setRSV(redHash(nomeVar), valore.ToString()); - _done = true; - } - else - { - try - { - HttpContext.Current.Cache[nomeVar] = valore; - _done = true; - } - catch - { } - } - return _done; - } - /// - /// inserisce in Cache un valore e su richiesta regitra tra le tab in cache da svuotare on update.. - /// - /// nome della variabile - /// valore - /// da registrare come tabella da svuotare on update - /// - public bool setCacheVal(string nome, object valore, bool setInTabInCache) - { - bool _done = setCacheVal(nome, valore); - if (setInTabInCache) - { - addTabInCache(nome); - } - return _done; - } - /// - /// svuota una variabile dalla Cache - /// - /// - public bool emptyCacheVal(string nomeVar) - { - bool _done = false; - if (cacheOnRedis) - { - redDelKey(redHash(nomeVar)); - } - else - { - try - { - HttpContext.Current.Cache.Remove(nomeVar); - _done = true; - } - catch - { } - } - return _done; - } - /// - /// restituisce true se sia presente in cache l'oggetto richiesto - /// - /// - /// - public bool isInCacheObject(string nomeVar) - { - bool answ = false; - bool stringAnsw = false; - if (cacheOnRedis) - { - try + /// + /// Verifica se ci siano valori nella KEY indicata... + /// + /// + /// + public bool redKeyPresent(RedisKey key) { - // cerco come key... - answ = redKeyPresent(redHash(nomeVar)); - if (!answ) - { - // cerco come hash... - answ = redHashPresent(redHash(nomeVar)); - } - // cerco come variabile se NON trovata... - if (!answ) - { - var redVal = getRSV(redHash(nomeVar)); - answ = redVal != null && redVal != ""; - } + bool answ = false; + // cerco se ci sia valore in redis... + try + { + answ = cache.KeyExists(key); + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in redKeyPresent per la key {2}:{0}{1}", Environment.NewLine, exc, key), tipoLog.EXCEPTION); + } + return answ; } - catch (Exception exc) + + /// + /// Verifica se ci siano valori nella KEY indicata (string) + /// + /// + /// + public bool redKeyPresentSz(string key) { - logger.lg.scriviLog(string.Format("Errore in verifica isInCacheObject REDIS per chiave{0}{1}{2}", nomeVar, Environment.NewLine, exc)); + bool answ = false; + try + { + RedisKey chiave = key; + answ = redKeyPresent(chiave); + } + catch + { } + return answ; } - } - else - { - // cerco di fare cast a stringa... - try + + /// + /// Salvataggio di una hash di valori + /// + /// chiave + /// valori + /// + public bool redSaveHash(string hashKey, KeyValuePair[] hashFields) { - stringAnsw = HttpContext.Current.Cache[nomeVar].ToString() != ""; + bool answ = false; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + HashEntry[] valori = new HashEntry[hashFields.Length]; + int i = 0; + foreach (KeyValuePair kvp in hashFields) + { + valori[i] = new HashEntry(kvp.Key, kvp.Value); + i++; + } + cache.HashSet(chiave, valori); + answ = true; + } + catch + { } + return answ; } - catch - { } - // infine condizione doppia... - try + + /// + /// Salvataggio di una hash di valori + /// + /// chiave + /// valori + /// scadenza preimpostata hash (secondi) | defaoult = -1 (non scade) + /// + public bool redSaveHash(string hashKey, KeyValuePair[] hashFields, double expireSeconds = -1) { - answ = (HttpContext.Current.Cache[nomeVar] != null && stringAnsw); + bool answ = false; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + answ = redSaveHash(hashKey, hashFields); + if (expireSeconds > 0) + { + cache.KeyExpire(chiave, DateTime.Now.AddSeconds(expireSeconds)); + } + //answ = true; + } + catch + { } + return answ; } - catch (Exception exc) + + /// + /// Salvataggio di una hash di valori in formato Dictionary + /// + /// chiave + /// valori + /// + public bool redSaveHashDict(string hashKey, Dictionary hashFields) { - logger.lg.scriviLog(string.Format("Errore in verifica isInCacheObject per chiave{0}{1}{2}", nomeVar, Environment.NewLine, exc)); + bool answ = false; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + HashEntry[] valori = new HashEntry[hashFields.Count]; + int i = 0; + foreach (KeyValuePair kvp in hashFields) + { + valori[i] = new HashEntry(kvp.Key, kvp.Value); + i++; + } + cache.HashSet(chiave, valori); + answ = true; + } + catch + { } + return answ; } - } - return answ; - } - /// - /// elenco dictionary delle tab in cache da aggiornare con update svuotando da cache... - /// - public Dictionary tabelleInCache - { - get - { - Dictionary answ = new Dictionary(); - try + + /// + /// Salvataggio di una hash di valori in formato Dictionary + /// + /// chiave + /// valori + /// scadenza preimpostata hash (secondi) | defaoult = -1 (non scade) + /// + public bool redSaveHashDict(string hashKey, Dictionary hashFields, double expireSeconds = -1) { - var cacheVal = objCacheObj("tabelleInCache"); - if (cacheVal != null) - { - answ = JsonConvert.DeserializeObject>(cacheVal.ToString()); - } + bool answ = false; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + answ = redSaveHashDict(hashKey, hashFields); + if (expireSeconds > 0) + { + cache.KeyExpire(chiave, DateTime.Now.AddSeconds(expireSeconds)); + } + //answ = true; + } + catch + { } + return answ; } - catch (Exception exc) + + /// + /// Salvataggio di una hash di valori + /// + /// chiave + /// valori come lista KVP + /// + public bool redSaveHashList(string hashKey, List> hashListKVP) { - answ = new Dictionary(); - logger.lg.scriviLog(string.Format("Errore in tabelleInCache{0}{1}", Environment.NewLine, exc)); + bool answ = false; + if (connRedis.IsConnected) + { + // cerco se ci sia valore in redis... + IDatabase cache = connRedis.GetDatabase(); + try + { + RedisKey chiave = hashKey; + HashEntry[] valori = new HashEntry[hashListKVP.Count]; + int i = 0; + foreach (KeyValuePair kvp in hashListKVP) + { + valori[i] = new HashEntry(kvp.Key, kvp.Value); + i++; + } + cache.HashSet(chiave, valori); + answ = true; + } + catch + { } + } + return answ; } - return answ; - } - set - { - string serVal = JsonConvert.SerializeObject(value); - setCacheVal("tabelleInCache", serVal); - } - } - /// - /// aggiunge la stringa corrente nel dictionary delle tabelle messe in cache e da aggiornare su comando update - /// - /// - public void addTabInCache(string nuovaTab) - { - // provo ad aggiungere nuova tab in elenco... - Dictionary _tabelleInCache = tabelleInCache; - try - { - _tabelleInCache.Add(nuovaTab, nuovaTab); - tabelleInCache = _tabelleInCache; - } - catch - { } - } - /// - /// elenco dictionary dei valori in session da NON aggiornare con update... - /// - public Dictionary valSess2SurvUpd - { - get - { - Dictionary answ = new Dictionary(); - if (isInSessionObject("valoriInSession2Survive")) + /// + /// Restituisce info dei server connessi... + /// + /// + public IServer[] redServInfo() { - try - { - answ = (Dictionary)objSessionObj("valoriInSession2Survive"); - } - catch - { - answ = new Dictionary(); - } + IServer[] answ = new IServer[1]; + try + { + answ = new IServer[connRedisAdmin.GetEndPoints().Length]; + int i = 0; + foreach (var ep in connRedisAdmin.GetEndPoints()) + { + var server = connRedisAdmin.GetServer(ep); + answ[i] = server; + i++; + } + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("{0}", exc), tipoLog.EXCEPTION); + } + return answ; } - return answ; - } - set - { - setSessionVal("valoriInSession2Survive", value); - } - } - /// - /// aggiunge la stringa corrente nel dictionary delle tabelle messe in session che vanno preservate da comando update (es: oggetto selezionato...) - /// - /// - /// - public void addValInSession(string nomePar, string valore) - { - // provo ad aggiungere nuova tab in elenco... - Dictionary _valoriInSession2Survive = valSess2SurvUpd; - // verifico se fare update o insert... - if (_valoriInSession2Survive.ContainsKey(nomePar)) - { - // update, rimuovo vecchio valore... - try + + /// + /// Resetta (elimina) un contatore in Redis + /// + /// + /// + public bool resetRCnt(string chiave) { - _valoriInSession2Survive.Remove(nomePar); + bool answ = false; + try + { + answ = cache.KeyDelete(chiave); + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in resetRCnt:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + } + return answ; } - catch - { } - } - // insert - try - { - _valoriInSession2Survive.Add(nomePar, valore); - valSess2SurvUpd = _valoriInSession2Survive; - } - catch - { } - } - /// - /// forza lo svuotamento delle tabelle indicate come in cache... - /// - public void flushRegisteredCache() - { - // elimino tutte le tab nella pos tabInCache... - foreach (KeyValuePair kvp in tabelleInCache) - { - if (cacheOnRedis) + + /// + /// Serializzazione di un oggetto generico + /// + /// + /// + public string serializeVal(object origVal) { - redDelKey(redHash(kvp.Value)); + string answ = ""; + try + { + answ = JsonConvert.SerializeObject(origVal); + } + catch { } + return answ; } - else + + /// + /// Decrementa un contatore in Redis + /// + /// + /// + public long setRCntD(string chiave) { - HttpContext.Current.Cache.Remove(kvp.Value); + long answ = 0; + try + { + answ = cache.StringDecrement(chiave, 1); + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in setRCD:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + } + return answ; } - } - if (cacheOnRedis) - { - redDelKey(redHash("tabelleInCache")); - } - else - { - HttpContext.Current.Cache.Remove("tabelleInCache"); - } - } - #endregion - - #endregion - - #region gestione valori in RedisCache - - /// - /// Restituisce un pò di info sul server redis connesso - /// - /// - public string getRedisInfoData() - { - string answ = ""; - StringBuilder sb = new StringBuilder(); - try - { - sb.AppendLine($"Configuration: {connRedis.Configuration}"); - sb.AppendLine($"Connected: {connRedis.IsConnected}"); - sb.AppendLine($"ClientName: {connRedis.ClientName}"); - sb.AppendLine($"Total Ops: {connRedis.OperationCount}"); - sb.AppendLine($"Status: {connRedis.GetStatus()}"); - answ = sb.ToString(); - } - catch - { } - return answ; - } - /// - /// Oggetto currentDb locale - /// - private IDatabase _currDB { get; set; } - /// - /// Oggetto DB REDIS corrente - /// - public IDatabase cache //currDB - { - get - { - IDatabase answ; - // se già valorizzato uso oggetto private... - if (_currDB != null) + /// + /// Incrementa un contatore in Redis + /// + /// + /// + public long setRCntI(string chiave) { - answ = _currDB; + long answ = 0; + try + { + answ = cache.StringIncrement(chiave, 1); + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in setRCI:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + } + return answ; } - else + + /// + /// Salva un set KVP (Key Value Pair) in RedisCache + /// + /// Set KVP chiave-valore da salvare + /// + public bool setRKeys(KeyValuePair[] valori) { - // init DB (sullo 0) - answ = connRedis.GetDatabase(); - // gestione override... - if (confReadInt("redisDb") >= 0) - { - // in questo caso uso il DB configurato in app.config... - answ = connRedis.GetDatabase(confReadInt("redisDb")); - } - _currDB = answ; + bool answ = false; + try + { + cache.StringSet(valori); + answ = true; + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in setRKeys:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + } + return answ; } - // restituisco oggetto DB - return answ; - } - } - - /// - /// Nome della variabile HASH da utilizzare (dato CodModulo / Server / DB impiegato da funzionalita' DbConfig) + keyName richiesto... - /// - public string redHash(string keyName) - { - string answ = keyName; - try - { - answ = string.Format("{0}:{1}:{2}:{3}", confReadString("CodModulo"), taConfig.Connection.DataSource, taConfig.Connection.Database, keyName).Replace("\\", "_"); - } - catch - { } - return answ; - } - /// - /// Serializzazione di un oggetto generico - /// - /// - /// - public string serializeVal(object origVal) - { - string answ = ""; - try - { - answ = JsonConvert.SerializeObject(origVal); - } - catch { } - return answ; - } - /// - /// Deserializzazione di un valore string in oggetto generico - /// - /// - /// - public object deserializeVal(string serVal) - { - object answ = ""; - try - { - answ = JsonConvert.DeserializeObject(serVal); - } - catch { } - return answ; - } - - - - /// - /// Connessione lazy a redis... - /// - private Lazy lazyConnection = new Lazy(() => - { - string RedisConn = memLayer.ML.confReadString("RedisConn"); - if (string.IsNullOrEmpty(RedisConn)) - { - RedisConn = "localhost,abortConnect=false,ssl=false"; - } - - return ConnectionMultiplexer.Connect(RedisConn); - }); - /// - /// Connessione lazy a redis... - /// - private Lazy lazyConnectionAdmin = new Lazy(() => - { - string RedisConnAdmin = memLayer.ML.confReadString("RedisConnAdmin"); - if (string.IsNullOrEmpty(RedisConnAdmin)) - { - RedisConnAdmin = "localhost,abortConnect=false,ssl=false,allowAdmin=true"; - } - - return ConnectionMultiplexer.Connect(RedisConnAdmin); - }); - - /// - /// Oggetto statico connessione redis - /// - public ConnectionMultiplexer connRedis - { - get - { - return lazyConnection.Value; - } - } - /// - /// Oggetto statico connessione redis - /// - public ConnectionMultiplexer connRedisAdmin - { - get - { - return lazyConnectionAdmin.Value; - } - } - /// - /// Restituisce info dei server connessi... - /// - /// - public IServer[] redServInfo() - { - IServer[] answ = new IServer[1]; - try - { - answ = new IServer[connRedisAdmin.GetEndPoints().Length]; - int i = 0; - foreach (var ep in connRedisAdmin.GetEndPoints()) + /// + /// Salva una chiave in RedisCache + /// + /// + /// + /// + public bool setRSV(string chiave, string valore) { - var server = connRedisAdmin.GetServer(ep); - answ[i] = server; - i++; + bool answ = false; + try + { + cache.StringSet(chiave, valore); + answ = true; + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in setRSV:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + } + return answ; } - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("{0}", exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Restituisce una chiave salvata in RedisCache - /// - /// - /// - public string getRSV(string chiave) - { - string answ = ""; - try - { - answ = cache.StringGet(chiave); - } - catch (Exception exc) - { - //logger.lg.scriviLog(string.Format("Errore in getRSV:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Salva una chiave in RedisCache - /// - /// - /// - /// - public bool setRSV(string chiave, string valore) - { - bool answ = false; - try - { - cache.StringSet(chiave, valore); - answ = true; - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in setRSV:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Salva una chiave in RedisCache - /// - /// - /// - /// in secondi - /// - public bool setRSV(string chiave, string valore, int TTL_sec) - { - bool answ = false; - try - { - TimeSpan expT = new TimeSpan(0, 0, TTL_sec); - // salvo con expyry... - cache.StringSet(chiave, valore, expT); - answ = true; - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in setRSV:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Incrementa un contatore in Redis - /// - /// - /// - public long setRCntI(string chiave) - { - long answ = 0; - try - { - answ = cache.StringIncrement(chiave, 1); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in setRCI:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Decrementa un contatore in Redis - /// - /// - /// - public long setRCntD(string chiave) - { - long answ = 0; - try - { - answ = cache.StringDecrement(chiave, 1); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in setRCD:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Restituisce una chiave COUNTER in RedisCache - /// - /// - /// - public int getRCnt(string chiave) - { - int answInt = 0; - string answ = ""; - try - { - answ = cache.StringGet(chiave); - answInt = Convert.ToInt32(answ); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in getRSV:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answInt; - } - /// - /// Resetta (elimina) un contatore in Redis - /// - /// - /// - public bool resetRCnt(string chiave) - { - bool answ = false; - try - { - answ = cache.KeyDelete(chiave); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in resetRCnt:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Restituisce un set KVP (Key Value Pair) salvati in RedisCache - /// - /// - /// - public RedisValue[] getRKeys(RedisKey[] chiavi) - { - RedisValue[] answ = null; - try - { - answ = cache.StringGet(chiavi); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in getRKeys:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Salva un set KVP (Key Value Pair) in RedisCache - /// - /// Set KVP chiave-valore da salvare - /// - public bool setRKeys(KeyValuePair[] valori) - { - bool answ = false; - try - { - cache.StringSet(valori); - answ = true; - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in setRKeys:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Verifica se ci siano valori nella KEY indicata... - /// - /// - /// - public bool redKeyPresent(RedisKey key) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - answ = cache.KeyExists(key); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in redKeyPresent per la key {2}:{0}{1}", Environment.NewLine, exc, key), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Verifica se ci siano valori nella KEY indicata (string) - /// - /// - /// - public bool redKeyPresentSz(string key) - { - bool answ = false; - try - { - RedisKey chiave = key; - answ = redKeyPresent(chiave); - } - catch - { } - return answ; - } - /// - /// Verifica se ci siano valori nella hash indicata... - /// - /// - /// - public bool redHashPresent(RedisKey key) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - answ = cache.HashGetAll(key).Length > 0; - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in redHashPresent per la key {2}{0}{1}", Environment.NewLine, exc, key), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Verifica se ci siano valori nella hash indicata (string) - /// - /// - /// - public bool redHashPresentSz(string key) - { - bool answ = false; - try - { - RedisKey chiave = key; - answ = redHashPresent(chiave); - } - catch - { } - return answ; - } - /// - /// Recupera tutti i valori dalla hash - /// - /// - /// - public KeyValuePair[] redGetHash(string hashKey) - { - KeyValuePair[] answ = new KeyValuePair[1]; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - HashEntry[] valori = cache.HashGetAll(chiave); - answ = new KeyValuePair[valori.Length]; - int i = 0; - foreach (HashEntry item in valori) + + /// + /// Salva una chiave in RedisCache + /// + /// + /// + /// in secondi + /// + public bool setRSV(string chiave, string valore, int TTL_sec) { - answ[i] = new KeyValuePair(item.Name, item.Value); - i++; + bool answ = false; + try + { + TimeSpan expT = new TimeSpan(0, 0, TTL_sec); + // salvo con expyry... + cache.StringSet(chiave, valore, expT); + answ = true; + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore in setRSV:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + } + return answ; } - } - catch - { } - return answ; - } - /// - /// Recupera tutti i valori dalla hash in formato Dictionary - /// - /// - /// - public Dictionary redGetHashDict(string hashKey) - { - Dictionary answ = new Dictionary(); - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - HashEntry[] valori = cache.HashGetAll(chiave); - foreach (HashEntry item in valori) + + /// + /// Effettua comaprazione x CHIAVE in KVP ASC + /// + /// + /// + /// + private int CompareKey(KeyValuePair x, KeyValuePair y) { - answ.Add(item.Name, item.Value); + return x.Key.CompareTo(y.Key); } - } - catch - { } - return answ; - } - /// - /// Recupera UN SINGOLO VALORE dalla hash per un dato field - /// - /// - /// - /// - public string redGetHashField(string hashKey, string hashField) - { - string answ = ""; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - RedisValue campo = hashField; - RedisValue valOut = cache.HashGet(chiave, campo); - answ = valOut.ToString(); - } - catch - { } - return answ; - } - /// - /// Salvataggio di una hash di valori - /// - /// chiave - /// valori - /// - public bool redSaveHash(string hashKey, KeyValuePair[] hashFields) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - HashEntry[] valori = new HashEntry[hashFields.Length]; - int i = 0; - foreach (KeyValuePair kvp in hashFields) + + /// + /// Effettua comaprazione x CHIAVE in KVP DESC + /// + /// + /// + /// + private int CompareKeyDesc(KeyValuePair x, KeyValuePair y) { - valori[i] = new HashEntry(kvp.Key, kvp.Value); - i++; + return y.Key.CompareTo(x.Key); } - cache.HashSet(chiave, valori); - answ = true; - } - catch - { } - return answ; - } - /// - /// Salvataggio di una hash di valori in formato Dictionary - /// - /// chiave - /// valori - /// - public bool redSaveHashDict(string hashKey, Dictionary hashFields) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - HashEntry[] valori = new HashEntry[hashFields.Count]; - int i = 0; - foreach (KeyValuePair kvp in hashFields) + + #endregion gestione valori in RedisCache + + #region URL corretti immagini + + /// + /// Formattazione stringa URL immagini con gestione "base url" + /// + /// + /// + public static string imgUrl(string urlRelPath) { - valori[i] = new HashEntry(kvp.Key, kvp.Value); - i++; + return string.Format("{0}/{1}", SteamWare.memLayer.ML.CRS("baseUrl"), urlRelPath); } - cache.HashSet(chiave, valori); - answ = true; - } - catch - { } - return answ; - } - /// - /// Salvataggio di una hash di valori - /// - /// chiave - /// valori come lista KVP - /// - public bool redSaveHashList(string hashKey, List> hashListKVP) - { - bool answ = false; - if (connRedis.IsConnected) - { - // cerco se ci sia valore in redis... - IDatabase cache = connRedis.GetDatabase(); - try + #endregion URL corretti immagini + + #region gestione mongoDb + + /// + /// Oggetto MongoDbCLient x accesso al motore + /// + protected MongoClient currMongoClient; + + /// + /// Stringa di connessione mongoDb + /// + protected string mongoConnString { - RedisKey chiave = hashKey; - HashEntry[] valori = new HashEntry[hashListKVP.Count]; - int i = 0; - foreach (KeyValuePair kvp in hashListKVP) - { - valori[i] = new HashEntry(kvp.Key, kvp.Value); - i++; - } - cache.HashSet(chiave, valori); - answ = true; + get + { + string answ = ""; + answ = confReadString("mdbConnString"); + if (string.IsNullOrEmpty(answ)) + { + answ = "mongodb://W2019-MONGODB:27017"; + } + return answ; + } } - catch - { } - } - return answ; - } - /// - /// Salvataggio di una hash di valori - /// - /// chiave - /// valori - /// scadenza preimpostata hash (secondi) | defaoult = -1 (non scade) - /// - public bool redSaveHash(string hashKey, KeyValuePair[] hashFields, double expireSeconds = -1) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - answ = redSaveHash(hashKey, hashFields); - if (expireSeconds > 0) + + /// + /// Restituisce oggetto DB richiesto + /// + /// + /// + public IMongoDatabase getMongoDatabase(string dbName) { - cache.KeyExpire(chiave, DateTime.Now.AddSeconds(expireSeconds)); + IMongoDatabase answ = currMongoClient.GetDatabase(dbName); + return answ; } - //answ = true; - } - catch - { } - return answ; - } - /// - /// Salvataggio di una hash di valori in formato Dictionary - /// - /// chiave - /// valori - /// scadenza preimpostata hash (secondi) | defaoult = -1 (non scade) - /// - public bool redSaveHashDict(string hashKey, Dictionary hashFields, double expireSeconds = -1) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - answ = redSaveHashDict(hashKey, hashFields); - if (expireSeconds > 0) + + /// + /// Init accesso MongoDb + /// + private void setupMongo() { - cache.KeyExpire(chiave, DateTime.Now.AddSeconds(expireSeconds)); + currMongoClient = new MongoClient(mongoConnString); } - //answ = true; - } - catch - { } - return answ; - } - /// - /// Elimina una key (hash, string) - /// - /// - /// - public bool redDelKey(string key) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = key; - cache.KeyDelete(chiave); - answ = true; - } - catch - { } - return answ; - } - /// - /// Flush completo cache redis - /// - /// ** = tutti - /// - public bool redFlushKey(string keyPattern) - { - bool answ = false; - // cerco se ci sia valore in redis... - // se vuoto = ALL... - keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; - try - { - foreach (var ep in connRedis.GetEndPoints()) - { - var server = connRedis.GetServer(ep); - var keys = server.Keys(database: confReadInt("redisDb"), pattern: $"{keyPattern}*"); - foreach (var key in keys) - { - cache.KeyDelete(key); - } - } - answ = true; - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("{0}", exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Conta num oggetti cache redis che rispondono a pattern - /// - /// ** = tutti - /// - public int redCountKey(string keyPattern) - { - int answ = 0; - // cerco se ci sia valore in redis... - // se vuoto = ALL... - keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; - try - { - foreach (var ep in connRedis.GetEndPoints()) - { - var server = connRedis.GetServer(ep); - foreach (var key in server.Keys(pattern: keyPattern)) - { - answ++; - } - } - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("{0}", exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Restituisce numero record in Redis DB - /// - public long numRecRedis - { - get - { - long answ = 0; - try - { - foreach (var ep in connRedis.GetEndPoints()) - { - var server = connRedis.GetServer(ep); - answ += server.DatabaseSize(); - } - } - catch - { } - return answ; - } + #endregion gestione mongoDb } - /// - /// Restituisce oggetti cache redis che rispondono a pattern - /// - /// ** = tutti - /// Tipo di ordinamento per kvp - /// - public List> redGetCounterByKey(string keyPattern, kvpOrderBy orderBy) - { - int numAnsw = redCountKey(keyPattern); - RedisKey[] chiavi = new RedisKey[numAnsw]; - List> answ = new List>(); - // se vuoto = ALL... - keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; - - // recupero in primis elenco chiavi - try - { - int i = 0; - foreach (var ep in connRedis.GetEndPoints()) - { - var server = connRedis.GetServer(ep); - foreach (var key in server.Keys(pattern: keyPattern)) - { - chiavi[i] = key; - i++; - } - } - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("{0}", exc), tipoLog.EXCEPTION); - } - // ora recupero valori! - var valori = getRKeys(chiavi); - int currVal = 0; - // popolo rispsota - try - { - for (int i = 0; i < numAnsw; i++) - { - Int32.TryParse(valori[i], out currVal); - answ.Add(new KeyValuePair(chiavi[i], currVal)); - } - } - catch - { } - // se richiesto riordino... - switch (orderBy) - { - case kvpOrderBy.KeyAsc: - answ.Sort(CompareKey); - break; - case kvpOrderBy.KeyDesc: - answ.Sort(CompareKeyDesc); - break; - case kvpOrderBy.ValAsc: - answ.Sort(CompareVal); - break; - case kvpOrderBy.ValDesc: - answ.Sort(CompareValDesc); - break; - default: - break; - } - return answ; - } - /// - /// Effettua comaprazione x CHIAVE in KVP ASC - /// - /// - /// - /// - private int CompareKey(KeyValuePair x, KeyValuePair y) - { - return x.Key.CompareTo(y.Key); - } - /// - /// Effettua comaprazione x VALORE in KVP ASC - /// - /// - /// - /// - public int CompareVal(KeyValuePair x, KeyValuePair y) - { - return x.Value.CompareTo(y.Value); - } - /// - /// Effettua comaprazione x CHIAVE in KVP DESC - /// - /// - /// - /// - private int CompareKeyDesc(KeyValuePair x, KeyValuePair y) - { - return y.Key.CompareTo(x.Key); - } - /// - /// Effettua comaprazione x VALORE in KVP DESC - /// - /// - /// - /// - public int CompareValDesc(KeyValuePair x, KeyValuePair y) - { - return y.Value.CompareTo(x.Value); - } - - /// - /// Tipologia di ordinamento x liste KVP - /// - public enum kvpOrderBy - { - /// - /// Ordinamento ASCending per KEY - /// - KeyAsc, - /// - /// Ordinamento DESCending per KEY - /// - KeyDesc, - /// - /// Ordinamento ASCending per VAL - /// - ValAsc, - /// - /// Ordinamento DESCending per VAL - /// - ValDesc - } - - - - #endregion - - #region URL corretti immagini - - /// - /// Formattazione stringa URL immagini con gestione "base url" - /// - /// - /// - public static string imgUrl(string urlRelPath) - { - return string.Format("{0}/{1}", SteamWare.memLayer.ML.CRS("baseUrl"), urlRelPath); - } - - #endregion - - #region gestione mongoDb - - /// - /// Stringa di connessione mongoDb - /// - protected string mongoConnString - { - get - { - string answ = ""; - answ = confReadString("mdbConnString"); - if (string.IsNullOrEmpty(answ)) - { - answ = "mongodb://W2019-MONGODB:27017"; - } - return answ; - } - } - /// - /// Oggetto MongoDbCLient x accesso al motore - /// - protected MongoClient currMongoClient; - /// - /// Init accesso MongoDb - /// - private void setupMongo() - { - currMongoClient = new MongoClient(mongoConnString); - } - /// - /// Restituisce oggetto DB richiesto - /// - /// - /// - public IMongoDatabase getMongoDatabase(string dbName) - { - IMongoDatabase answ = currMongoClient.GetDatabase(dbName); - return answ; - } - - - - #endregion - - } -} +} \ No newline at end of file