using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
namespace SteamWare
{
///
/// layer gestione vari tipi di memoria: cache, session...
///
public class memLayer
{
#region oggetti protected utilizzati
///
/// lettore file configurazione
///
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
{
get
{
return CRB("serializeSession");
}
}
///
/// classe gestione accessi a Session, cache, viewstate, configuration...
///
protected memLayer()
{
// istanzia il conf setting reader...
configAppSetReader = new AppSettingsReader();
// avvio e configuro TA
initTA();
setupConnectionStringBase();
}
///
/// 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 (answ == "")
{
answ = confReadString("PermessiConnectionString");
}
// se ancora vuota --> devAuth
if (answ == "")
{
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()
{
redFlushKey(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 (redHashPresent(ACBH))
{
AppConf = new Dictionary();
foreach (var item in redGetHash(ACBH))
{
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++;
}
redSaveHash(ACBH, valori);
lastUpdateAppConf = DateTime.Now;
}
}
catch (Exception exc)
{
logger.lg.scriviLog(string.Format("Errore in startupAppConf:{0}{1}", Environment.NewLine, exc));
}
}
}
///
/// 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();
foreach (DS_Utility.ConfigRow riga in taConfig.GetData())
{
answ.Add(riga.chiave, riga.valore);
}
return answ;
}
///
/// ultimo update in cache dei valori di AppConfig
///
public DateTime lastUpdateAppConf
{
get
{
DateTime answ = DateTime.Now.AddDays(-1);
try
{
answ = Convert.ToDateTime(objCacheObj("lastUpdateAppConf"));
}
catch { }
return answ;
}
set
{
setCacheVal("lastUpdateAppConf", value, true);
}
}
///
/// 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 (sennò rileggo)
if (AppConf.Count == 0)
{
resetAppConf();
}
// default 5 minuti x refresh...
int maxAge = 5;
try
{
maxAge = confReadInt("maxAgeAppConf_min");
}
catch
{ }
// controllo SE è passato più di 5 minuti, nel caso faccio refresh...
if (DateTime.Now.Subtract(lastUpdateAppConf).TotalMinutes > maxAge)
{
resetAppConf();
}
// provo a leggere da DICT
try
{
answ = AppConf[chiave];
}
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;
try
{
answ = Convert.ToBoolean(configDbVal(chiave));
}
catch
{ }
return answ;
}
///
/// Configurations da tabella DB Config (short form wrapper) convertito a INT
///
/// Valore chiave
///
public int cdvi(string chiave)
{
int answ = -1;
try
{
answ = Convert.ToInt32(configDbVal(chiave));
}
catch
{ }
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 (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 = "";
try
{
answ = HttpContext.Current.Request.QueryString[nome].ToString().Trim();
}
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)
{
answ = HttpContext.Current.Session[nomeVar].ToString();
}
}
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
{
answ = Convert.ToDateTime(memLayer.ML.objSessionObj(nomeVar));
}
catch
{
answ = DateTime.Now;
}
}
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)
{
addValInSession(nome, valore.ToString());
}
_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 è 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;
try
{
answ = HttpContext.Current.Request.Cookies[nome].Value != "";
}
catch
{ }
return answ;
}
///
/// restituisco un valore da cookie
///
///
///
public string getCookieVal(string nome)
{
string answ = "";
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;
}
///
/// 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
#region cache
///
/// Indica se usare la cache su REDIS (true) oppure cache applicativo IIS (false)
///
protected 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 = JsonConvert.DeserializeObject(getRSV(redHash(nomeVar)));
}
else
{
if (HttpContext.Current.Cache[nomeVar] != null)
{
answ = HttpContext.Current.Cache[nomeVar];
}
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)
{
// serializzo
string serVal = JsonConvert.SerializeObject(valore);
setRSV(redHash(nomeVar), serVal);
_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 è presente in cache l'oggetto richiesto
///
///
///
public bool isInCacheObject(string nomeVar)
{
bool answ = false;
bool stringAnsw = false;
if (cacheOnRedis)
{
answ = redHashPresent(redHash(nomeVar));
}
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
{ }
}
return answ;
}
///
/// elenco dictionary delle tab in cache da aggiornare con update svuotando da cache...
///
public Dictionary tabelleInCache
{
get
{
try
{
return (Dictionary)objCacheObj("tabelleInCache");
}
catch
{
return new Dictionary();
}
}
set
{
setCacheVal("tabelleInCache", 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
{ }
}
///
/// elenco dictionary dei valori in session da NON aggiornare con update...
///
public Dictionary valSess2SurvUpd
{
get
{
try
{
return (Dictionary)objSessionObj("valoriInSession2Survive");
}
catch
{
return new Dictionary();
}
}
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
{
_valoriInSession2Survive.Remove(nomePar);
}
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)
{
redDelKey(redHash(kvp.Value));
}
else
{
HttpContext.Current.Cache.Remove(kvp.Value);
}
}
if (cacheOnRedis)
{
redDelKey(redHash("tabelleInCache"));
}
else
{
HttpContext.Current.Cache.Remove("tabelleInCache");
}
}
#endregion
#endregion
#region gestione valori in RedisCache
///
/// 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;
}
///
/// Connessione lazy a redis...
///
private static Lazy lazyConnection = new Lazy(() =>
{
return ConnectionMultiplexer.Connect("127.0.0.1,abortConnect=false,ssl=false");
});
///
/// Connessione lazy a redis...
///
private static Lazy lazyConnectionAdmin = new Lazy(() =>
{
return ConnectionMultiplexer.Connect("127.0.0.1,abortConnect=false,ssl=false,allowAdmin=true");
});
///
/// Oggetto statico connessione redis
///
public static ConnectionMultiplexer connRedis
{
get
{
return lazyConnection.Value;
}
}
///
/// Oggetto statico connessione redis
///
public static 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())
{
var server = connRedisAdmin.GetServer(ep);
answ[i] = server;
i++;
}
}
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
{
IDatabase cache = connRedis.GetDatabase();
answ = cache.StringGet(chiave);
}
catch (Exception exc)
{
logger.lg.scriviLog(string.Format("Errore in getRSV:{0}{1}", Environment.NewLine, exc));
}
return answ;
}
///
/// Salva una chiave in RedisCache
///
///
///
///
public bool setRSV(string chiave, string valore)
{
bool answ = false;
try
{
IDatabase cache = connRedis.GetDatabase();
cache.StringSet(chiave, valore);
answ = true;
}
catch (Exception exc)
{
logger.lg.scriviLog(string.Format("Errore in setRSV:{0}{1}", Environment.NewLine, exc));
}
return answ;
}
///
/// Salva una chiave in RedisCache
///
///
///
/// in secondi
///
public bool setRSV(string chiave, string valore, int TTL_sec)
{
bool answ = false;
try
{
IDatabase cache = connRedis.GetDatabase();
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));
}
return answ;
}
///
/// Incrementa un contatore in Redis
///
///
///
public long setRCntI(string chiave)
{
long answ = 0;
try
{
IDatabase cache = connRedis.GetDatabase();
answ = cache.StringIncrement(chiave, 1);
}
catch (Exception exc)
{
logger.lg.scriviLog(string.Format("Errore in setRCI:{0}{1}", Environment.NewLine, exc));
}
return answ;
}
///
/// Decrementa un contatore in Redis
///
///
///
public long setRCntD(string chiave)
{
long answ = 0;
try
{
IDatabase cache = connRedis.GetDatabase();
answ = cache.StringDecrement(chiave, 1);
}
catch (Exception exc)
{
logger.lg.scriviLog(string.Format("Errore in setRCD:{0}{1}", Environment.NewLine, exc));
}
return answ;
}
///
/// Restituisce una chiave COUNTER in RedisCache
///
///
///
public int getRCnt(string chiave)
{
int answInt = 0;
string answ = "";
try
{
IDatabase cache = connRedis.GetDatabase();
answ = cache.StringGet(chiave);
answInt = Convert.ToInt32(answ);
}
catch (Exception exc)
{
logger.lg.scriviLog(string.Format("Errore in getRSV:{0}{1}", Environment.NewLine, exc));
}
return answInt;
}
///
/// Resetta (elimina) un contatore in Redis
///
///
///
public bool resetRCnt(string chiave)
{
bool answ = false;
try
{
IDatabase cache = connRedis.GetDatabase();
answ = cache.KeyDelete(chiave);
}
catch (Exception exc)
{
logger.lg.scriviLog(string.Format("Errore in resetRCnt:{0}{1}", Environment.NewLine, exc));
}
return answ;
}
///
/// Restituisce un set KVP (Key Value Pair) salvati in RedisCache
///
///
///
public RedisValue[] getRKeys(RedisKey[] chiavi)
{
RedisValue[] answ = null;
try
{
IDatabase cache = connRedis.GetDatabase();
answ = cache.StringGet(chiavi);
}
catch (Exception exc)
{
logger.lg.scriviLog(string.Format("Errore in getRKeys:{0}{1}", Environment.NewLine, exc));
}
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
{
IDatabase cache = connRedis.GetDatabase();
cache.StringSet(valori);
answ = true;
}
catch (Exception exc)
{
logger.lg.scriviLog(string.Format("Errore in setRKeys:{0}{1}", Environment.NewLine, exc));
}
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...
IDatabase cache = connRedis.GetDatabase();
try
{
answ = cache.HashGetAll(key).Length > 0;
}
catch
{ }
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...
IDatabase cache = connRedis.GetDatabase();
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;
}
///
/// 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...
IDatabase cache = connRedis.GetDatabase();
try
{
RedisKey chiave = hashKey;
HashEntry[] valori = cache.HashGetAll(chiave);
foreach (HashEntry item in valori)
{
answ.Add(item.Name, item.Value);
}
}
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...
IDatabase cache = connRedis.GetDatabase();
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...
IDatabase cache = connRedis.GetDatabase();
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;
}
///
/// 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...
IDatabase cache = connRedis.GetDatabase();
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;
}
///
/// 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...
IDatabase cache = connRedis.GetDatabase();
try
{
RedisKey chiave = hashKey;
answ = redSaveHash(hashKey, hashFields);
if (expireSeconds > 0)
{
cache.KeyExpire(chiave, DateTime.Now.AddSeconds(expireSeconds));
}
//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...
IDatabase cache = connRedis.GetDatabase();
try
{
RedisKey chiave = hashKey;
answ = redSaveHashDict(hashKey, hashFields);
if (expireSeconds > 0)
{
cache.KeyExpire(chiave, DateTime.Now.AddSeconds(expireSeconds));
}
//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...
IDatabase cache = connRedis.GetDatabase();
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...
IDatabase cache = connRedis.GetDatabase();
// se vuoto = ALL...
keyPattern = keyPattern == "" ? "**" : keyPattern;
try
{
foreach (var ep in connRedis.GetEndPoints())
{
var server = connRedis.GetServer(ep);
foreach (var key in server.Keys(pattern: keyPattern))
{
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...
IDatabase cache = connRedis.GetDatabase();
// se vuoto = ALL...
keyPattern = 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;
}
}
///
/// 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 = 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
}
}