using System;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Web;
using NLog;
using System.Net.Mail;
namespace ETS_Data
{
public class utils
{
protected AppSettingsReader configAppSetReader;
//public Logger lg = LogManager.GetCurrentClassLogger();
#region area table adapters
public DS_AnagraficaTableAdapters.UtentiTableAdapter taUtenti;
public DS_AnagraficaTableAdapters.DirittiTableAdapter taDiritti;
public DS_utilsTableAdapters.v_selFontiTableAdapter taSelFonti;
public DS_utilsTableAdapters.v_selCommesseTableAdapter taSelCommesse;
public DS_utilsTableAdapters.v_selFasiTableAdapter taSelFasi;
public DS_utilsTableAdapters.v_selAutoriTableAdapter taSelAutori;
public DS_utilsTableAdapters.v_tbDocs_selFontiTableAdapter taTDSelFonti;
public DS_utilsTableAdapters.v_tbDocs_selCommesseTableAdapter taTDSelCommesse;
public DS_utilsTableAdapters.v_tbDocs_selFasiTableAdapter taTDSelFasi;
public DS_utilsTableAdapters.v_tbDocs_selOggettoTableAdapter taTDSelOggetti;
public DS_utilsTableAdapters.v_tbDocs_selRedattoreTableAdapter taTDSelRedattore;
public DS_utilsTableAdapters.stp_calcolaProtocolloTableAdapter taCalcProto;
public DS_utilsTableAdapters.v_selEmailFornitoriTableAdapter taEmailForn;
public DS_utilsTableAdapters.AnagSuggestTagsTableAdapter taAST;
public DS_utilsTableAdapters.v_selFonti_explTableAdapter taVSFE;
public DS_WebScipTableAdapters.tbDocumentiTableAdapter taDoc;
public DS_WebScipTableAdapters.Tags2DocTableAdapter taTags2Doc;
public DS_WebScipTableAdapters.tbMetaDataSetTableAdapter taTMD;
public DS_WebScipTableAdapters.stp_userLoginRefreshDbTableAdapter taDBRefresh;
///
/// init dei table adapters
///
protected void initTA()
{
taUtenti = new DS_AnagraficaTableAdapters.UtentiTableAdapter();
taDiritti = new DS_AnagraficaTableAdapters.DirittiTableAdapter();
taSelFonti = new DS_utilsTableAdapters.v_selFontiTableAdapter();
taSelCommesse = new DS_utilsTableAdapters.v_selCommesseTableAdapter();
taSelFasi = new DS_utilsTableAdapters.v_selFasiTableAdapter();
taSelAutori = new DS_utilsTableAdapters.v_selAutoriTableAdapter();
taTDSelFonti = new DS_utilsTableAdapters.v_tbDocs_selFontiTableAdapter();
taTDSelCommesse = new DS_utilsTableAdapters.v_tbDocs_selCommesseTableAdapter();
taTDSelFasi = new DS_utilsTableAdapters.v_tbDocs_selFasiTableAdapter();
taTDSelOggetti = new DS_utilsTableAdapters.v_tbDocs_selOggettoTableAdapter();
taTDSelRedattore = new DS_utilsTableAdapters.v_tbDocs_selRedattoreTableAdapter();
taCalcProto = new DS_utilsTableAdapters.stp_calcolaProtocolloTableAdapter();
taEmailForn = new DS_utilsTableAdapters.v_selEmailFornitoriTableAdapter();
taAST = new DS_utilsTableAdapters.AnagSuggestTagsTableAdapter();
taVSFE = new DS_utilsTableAdapters.v_selFonti_explTableAdapter();
taDoc = new DS_WebScipTableAdapters.tbDocumentiTableAdapter();
taTags2Doc = new DS_WebScipTableAdapters.Tags2DocTableAdapter();
taTMD = new DS_WebScipTableAdapters.tbMetaDataSetTableAdapter();
taDBRefresh = new DS_WebScipTableAdapters.stp_userLoginRefreshDbTableAdapter();
}
///
/// effettua setup dei connection strings da web.config delal singola applicazione
///
protected virtual void setupConnectionStringBase()
{
string connStringETS_WS = (string)configAppSetReader.GetValue("ETS_WSConnectionString", typeof(string));
string connStringETS_WAnagrafica = (string)configAppSetReader.GetValue("ETS_AnagraficaConnectionString", typeof(string));
// connections del db
taUtenti.Connection.ConnectionString = connStringETS_WAnagrafica;
taDiritti.Connection.ConnectionString = connStringETS_WAnagrafica;
taSelFonti.Connection.ConnectionString = connStringETS_WS;
taSelCommesse.Connection.ConnectionString = connStringETS_WS;
taSelFasi.Connection.ConnectionString = connStringETS_WS;
taSelAutori.Connection.ConnectionString = connStringETS_WS;
taTDSelFonti.Connection.ConnectionString = connStringETS_WS;
taTDSelCommesse.Connection.ConnectionString = connStringETS_WS;
taTDSelFasi.Connection.ConnectionString = connStringETS_WS;
taTDSelOggetti.Connection.ConnectionString = connStringETS_WS;
taTDSelRedattore.Connection.ConnectionString = connStringETS_WS;
taCalcProto.Connection.ConnectionString = connStringETS_WS;
taEmailForn.Connection.ConnectionString = connStringETS_WS;
taAST.Connection.ConnectionString = connStringETS_WS;
taVSFE.Connection.ConnectionString = connStringETS_WS;
taDoc.Connection.ConnectionString = connStringETS_WS;
taTags2Doc.Connection.ConnectionString = connStringETS_WS;
taTMD.Connection.ConnectionString = connStringETS_WS;
taDBRefresh.Connection.ConnectionString = connStringETS_WS;
}
#endregion
#region Inizializzazione
protected utils()
{
configAppSetReader = new AppSettingsReader();
initTA();
setupConnectionStringBase();
}
///
/// oggetto static per fare chiamate sul magazzino
///
public static utils obj = new utils();
#endregion
#region gestione email & log...
///
/// classe di gestione delle email
///
public class gestEmail
{
protected Logger lg = LogManager.GetCurrentClassLogger();
///
/// stringa del nome DNS o dell'ip del server SMTP
///
protected string _smtpCli;
///
/// stringa username x server SMTP
///
protected string _username;
///
/// stringa pwd x server SMTP
///
protected string _password;
///
/// metodo static per la gestione delle email
///
///
public gestEmail(string smtpCli)
{
lg.Info("[Modulo gestEmail]: avviato con parametro smtp {0}", smtpCli);
_smtpCli = smtpCli;
_username = "";
_password = "";
}
///
/// metodo static per la gestione delle email
///
///
///
///
public gestEmail(string smtpCli, string user, string pwd)
{
lg.Info("[Modulo gestEmail]: avviato con parametro smtp {0} ed utente {1}", smtpCli, user);
_smtpCli = smtpCli;
_username = user;
_password = pwd;
}
///
/// metodo static per la gestione delle email
///
///
///
public gestEmail(string smtpCli, string logDir)
{
lg.Info("[Modulo gestEmail]: avviato con parametro smtp {0} e logdir {1}", smtpCli, logDir);
_smtpCli = smtpCli;
_username = "";
_password = "";
}
///
/// procedura invio email
///
/// email mittente
/// email destinatario
/// oggetto dell'email
/// corpo del messaggio
public bool mandaEmailNoLog(string _mailFrom, string _mailTo, string _oggetto, string _corpo)
{
//manda email...
MailMessage messaggio = new MailMessage(_mailFrom, _mailTo, _oggetto, _corpo);
messaggio.IsBodyHtml = true;
SmtpClient _smtpClient = new SmtpClient(_smtpCli);
// se ci sono credenziali utente...
if (_username != "")
{
_smtpClient.Credentials = new System.Net.NetworkCredential(_username, _password);
_smtpClient.EnableSsl = utils.obj.confReadBool("_enableSSL");
}
try
{
_smtpClient.Send(messaggio);
return true;
}
catch (SmtpException esmtp)
{
Console.WriteLine("{0}", esmtp.Message);
Console.WriteLine("Here is the full error message output");
Console.Write("{0}", esmtp.ToString());
lg.ErrorException(string.Format("{0}\r\n full error message\r\n", esmtp.Message), esmtp);
return false;
}
}
///
/// procedura invio email + scrittura in log!
///
/// email mittente
/// email destinatario
/// oggetto dell'email
/// corpo del messaggio
public bool mandaEmail(string _mailFrom, string _mailTo, string _oggetto, string _corpo)
{
bool fatto = false;
//manda email...
try
{
fatto = mandaEmailNoLog(_mailFrom, _mailTo, _oggetto, _corpo);
lg.Info("Email inviata: oggetto: {0}, corpo: {1}", _oggetto, _corpo);
}
catch (Exception exc)
{
lg.ErrorException(string.Format("ERRORE! Email NON INVIATA!oggetto: {0} corpo: {1} eccezione: ", _oggetto, _corpo), exc);
}
return fatto;
}
///
/// metodo singleton gestione email...
///
public static gestEmail ge = new gestEmail(utils.obj.confReadString("_smtpCli"));
///
/// metodo singleton gestione email CON AUTH utente...
///
public static gestEmail geAuth = new gestEmail(utils.obj.confReadString("_smtpCli"), utils.obj.confReadString("_emailUser"), utils.obj.confReadString("_emailPwd"));
}
#endregion
#region area user (wrapper su user_std)
///
/// WRAPPER utente correntemente connesso (Formato dominio\username)
///
public string currUserAD
{
get
{
return user_std.UtSn.currUserAD;
}
}
///
/// WRAPPER utente correntemente connesso per utilizzo FileSystem (Formato dominio.username)
///
public string currUser_FS
{
get
{
return user_std.UtSn.currUser_FS;
}
}
///
/// WRAPPER utente correntemente connesso (Formato Cognome nome)
///
public string currUserCognomeNome
{
get
{
return user_std.UtSn.currUserCognomeNome;
}
}
///
/// WRAPPER utente correntemente connesso (Formato Nome Cognome)
///
public string currUserNomeCognome
{
get
{
return user_std.UtSn.currUserNomeCognome;
}
}
///
/// WRAPPER EMAIL utente correntemente connesso
///
public string currUserEmail
{
get
{
return user_std.UtSn.currUserEmail;
}
}
///
/// WRAPPER UserId (AD) utente correntemente connesso
///
public string currUserId
{
get
{
return user_std.UtSn.currUserId;
}
}
///
/// WRAPPER calcola se l'utente abbia il diritto x la funzione indicata
///
/// username formato AD
/// codice modulo
/// codice funzione
///
public bool userHasRight(string utenteAD, string codModulo, string codFunzione)
{
return user_std.UtSn.userHasRight(utenteAD, codModulo, codFunzione);
}
#endregion
#region area Session
///
/// 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)
{
if (HttpContext.Current.Session[nomeVar] != null)
{
return HttpContext.Current.Session[nomeVar].ToString();
}
else
{
return "";
}
}
///
/// carica dalla sessione un dato di tipo long
///
///
///
public long LongSessionObj(string nomeVar)
{
if (HttpContext.Current.Session[nomeVar] != null)
{
return (long)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 (int)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;
}
///
/// 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 di fare cast a stringa...
try
{
stringAnsw = (string)HttpContext.Current.Session[nomeVar].ToString() != "";
}
catch
{ }
// infine condizione doppia...
try
{
answ = (HttpContext.Current.Session[nomeVar] != null && stringAnsw);
}
catch
{ }
return answ;
}
#endregion
//#region cache
/////
///// carica dalla Cache un dato di tipo object generico
/////
/////
/////
//public object objCacheObj(string nomeVar)
//{
// if (HttpContext.Current.Cache[nomeVar] != null)
// {
// return HttpContext.Current.Cache[nomeVar];
// }
// else
// {
// return "";
// }
//}
/////
///// carica dalla Cachee un dato di tipo boolean (se vuoto false)
/////
/////
/////
//public bool BoolCacheObj(string nomeVar)
//{
// if (HttpContext.Current.Cache[nomeVar] != null)
// {
// return (bool)HttpContext.Current.Cache[nomeVar];
// }
// else
// {
// return false;
// }
//}
/////
///// carica dalla Cachee un dato di tipo string
/////
/////
/////
//public string StringCacheObj(string nomeVar)
//{
// if (HttpContext.Current.Cache[nomeVar] != null)
// {
// return HttpContext.Current.Cache[nomeVar].ToString();
// }
// else
// {
// return "";
// }
//}
/////
///// inserisce in Cache un valore
/////
///// nome della variabile
///// valore
//public bool setCacheVal(string nome, object valore)
//{
// bool _done = false;
// try
// {
// HttpContext.Current.Cache[nome] = 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 nome)
//{
// bool _done = false;
// try
// {
// HttpContext.Current.Cache.Remove(nome);
// _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;
// // cerco di fare cast a stringa...
// try
// {
// stringAnsw = (string)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)
// {
// HttpContext.Current.Cache.Remove(kvp.Value);
// }
// HttpContext.Current.Cache.Remove("tabelleInCache");
//}
//#endregion
//#region gestione valori in RedisCache
/////
///// Connessione lazy a redis...
/////
//private static Lazy lazyConnection = new Lazy(() =>
//{
// return ConnectionMultiplexer.Connect("127.0.0.1,abortConnect=false,ssl=false");
//});
/////
///// Oggetto statico connessione redis
/////
//public static ConnectionMultiplexer connRedis
//{
// get
// {
// return lazyConnection.Value;
// }
//}
/////
///// 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;
//}
/////
///// 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;
//}
/////
///// 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;
//}
/////
///// Salvataggio di una hash di 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;
//}
/////
///// 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;
//}
/////
///// 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
#region gestione file config
///
/// 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;
}
///
/// legge dalla config un valore string
///
///
///
public string confReadString(string nomeParam)
{
string answ = "";
try
{
answ = (string)configAppSetReader.GetValue(nomeParam, typeof(string));
}
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;
}
#endregion
#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 area varie
///
/// ripulisce la stringa da eventuali caratteri non ammessi quali
/// [ .,;\/]
/// e OPZIONALMENTE toglie " " (spazi) sostituendoli con "_" (underscore)
///
/// stringa originale
/// definisce se mantenere (true) o togliere (false) gli spazi (eventualmente sostituendo con underscore "_")
///
public static string cleanPathName(string originalName, bool keepSpaces)
{
string answ = originalName.Trim().Replace("&", "e").Replace(".", "").Replace(",", "").Replace(";", "").Replace(":", "").Replace("/", "-").Replace(@"\", "-").Replace(@"'", "_").Replace("\"", "_").Replace("#", "_").Replace("?", "_").Replace("*", "_").Replace(" ", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_"); ;
if (keepSpaces)
{
answ = originalName.Trim().Replace("&", "e").Replace(".", "").Replace(",", "").Replace(";", "").Replace(":", "").Replace("/", "-").Replace(@"\", "-").Replace(@"'", "_").Replace("\"", "_").Replace("#", "_").Replace("?", "_").Replace("*", "_").Replace(" ", " ").Replace(" ", " ").Replace(" ", " ").Replace(" ", " ").Replace("__", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_");
}
return answ;
}
///
/// ripulisce la stringa da eventuali caratteri non ammessi quali
/// [ .,;\/]
/// e toglie " " (spazi) sostituendoli con "_" (underscore)
///
/// stringa originale
///
public static string cleanPathName(string originalName)
{
return cleanPathName(originalName, false);
}
///
/// restituisce, in caso di null o stringa vuota, il carattere "*"
///
///
///
public static string emptyToStar(string original)
{
string answ = original;
if ((original == null) || (original == ""))
{
answ = "*";
}
return answ;
}
///
/// Effettua shring di una stringa ricudendola in lunghezza (tiene inizio/fine + eventuale ".." centrale se lungh superiore a indicata)
///
/// stringa originale
/// lungh max desiderata
///
public static string shrinkString(string originalString, int maxLenght)
{
string answ = originalString;
if (answ.Length > maxLenght)
{
string sep = utils.obj.confReadString("separatoreTrim");
int numChar = (maxLenght - sep.Length) / 2;
answ = string.Format("{0}{1}{2}", answ.Substring(0, numChar), sep, answ.Substring(answ.Length - (maxLenght - 3 - numChar)));
}
return answ;
}
///
/// trimma una stringa per il num max di caratteri richiesti togliendo dal centro (tiene inizio/fine...)
///
///
///
/// num caratteri da ignorare a dx
///
public static string shrinkString(string stringaIn, int maxNum, int ignoreRight)
{
// elimino caratteri a dx.. se posso
string answ = stringaIn;
if (ignoreRight < stringaIn.Length)
{
answ = answ.Substring(0, stringaIn.Length - ignoreRight);
}
// effetuo shrink!
answ = shrinkString(answ, maxNum);
return answ;
}
///
/// trimma una stringa per il num max di caratteri richiesti
///
///
///
public static string trimChar(object stringaIn, object maxChar)
{
string answ = "";
int maxNum = 0;
try
{
answ = stringaIn.ToString();
maxNum = Convert.ToInt32(maxChar);
}
catch
{ }
if (maxNum < answ.Length)
{
answ = answ.Substring(0, maxNum) + "...";
}
return answ;
}
public static int pageSizeConf
{
get
{
return obj.confReadInt("pageSize");
}
}
///
/// dim pagina desiderata
///
public static int pageSize
{
get
{
int answ = 0;
try
{
answ = utils.obj.IntSessionObj("pageSize");
}
catch
{ }
if (answ <= 0)
{
answ = 20;
}
return answ;
}
set
{
utils.obj.setSessionVal("pageSize", value);
}
}
#endregion
#region gestione ruoli utente...
///
/// risponde alla domanda se l'utente sia PowerUser
///
///
public bool isPowerUser
{
get
{
return user_std.UtSn.userHasRight("PowerUser");
}
}
///
/// risponde alla domanda se l'utente sia PowerReader
///
///
public bool isPowerReader
{
get
{
return user_std.UtSn.userHasRight("PowerReader");
}
}
///
/// risponde alla domanda se l'utente sia ProjectManager
///
///
public bool isPM
{
get
{
return user_std.UtSn.userHasRight("PM");
}
}
///
/// risponde alla domanda se l'utente sia CapoCommessa
///
///
public bool isCC
{
get
{
return user_std.UtSn.userHasRight("CC");
}
}
///
/// risponde alla domanda se l'utente sia User
///
///
public bool isUser
{
get
{
return user_std.UtSn.userHasRight("User");
}
}
///
/// risponde alla domanda se l'utente sia CC della commessa indicata dalla fase
///
///
///
public bool isCurrentCC(int idxFase)
{
bool answ = false;
string CapoCommessa = "";
try
{
CapoCommessa = DataProxy_ProjEts.DP.taDC.GetData(idxFase)[0].CapoCommessa;
}
catch
{ }
if (user_std.UtSn.NomeCognome == CapoCommessa || user_std.UtSn.CognomeNome == CapoCommessa)
{
answ = true;
}
return answ;
}
#endregion
}
///
/// definisce un intervalo di 2 date
///
public struct intervalloDate
{
///
/// data inizio
///
public DateTime inizio;
///
/// data fine
///
public DateTime fine;
///
/// indica se sia valido il dato, ovvero inizio e fine > 0 e FINE >= INIZIO
///
public bool isValid
{
get
{
bool cond1 = false;
bool cond2 = false;
bool cond3 = false;
try
{
cond1 = inizio > Convert.ToDateTime("01/01/0001");
}
catch
{ }
try
{
cond2 = fine > Convert.ToDateTime("01/01/0001");
}
catch
{ }
try
{
cond3 = (fine.Subtract(inizio).TotalHours > 0);
}
catch
{ }
return (cond1 && cond2 && cond3);
}
}
}
public class oreWeek
{
///
/// inizializzazione empty
///
public oreWeek()
{
}
///
/// effettua una somma di ore dallo schema ore LMMGV facendo somma giorno per giorno
///
/// string LMMGV (se <> 5 char errore)
/// string LMMGV (se <> 5 char errore)
/// Restituisce:
/// - somma giornaliera LMMGV
/// - "X" se nel singolo giorno > maxOre
/// - "?????" se secondo addendo nn di 5 char
/// - "#" se non può convertire un singolo char
public static string addOre(string addendo1, string addendo2, int MaxOre)
{
string answ = "";
int summa = 0;
// procedo SOLO se le 2 stringhe sono 5 char
if (addendo1.Length != 5 || addendo2.Length != 5)
{
answ = "?????";
}
else
{
// faccio somma 1 char alla volta e controllo lungh max
for (int i = 0; i < 5; i++)
{
try
{
// se già ho carattere "X" confermo "X"...
if (addendo1.Substring(i, 1) == "X" || addendo1.Substring(i, 1) == "X")
{
answ += "X";
}
else
{
summa = Convert.ToInt16(addendo1.Substring(i, 1)) + Convert.ToInt16(addendo2.Substring(i, 1));
if (summa > MaxOre)
{
answ += "X";
}
else
{
answ += summa.ToString();
}
}
}
catch (Exception exc)
{
answ += "X";
}
}
}
return answ;
}
}
///
/// classe di funzioni inerenti le date
///
public class datario
{
///
/// inizializzazione empty
///
public datario()
{
}
///
/// costruisce un oggetto intervallo date
///
///
///
///
public intervalloDate setIntervallo(DateTime inizio, DateTime fine)
{
intervalloDate periodo = new intervalloDate();
periodo.inizio = inizio;
periodo.fine = fine;
return periodo;
}
///
/// effettua l'operazione di intersezione tra 2 intervali di date restituendo ulteriore intervallo: NB se sono intervali disgiunti restituisce 9/9/9999 x inizio e fine
///
///
///
///
public intervalloDate intersecaIntervalli(intervalloDate interv1, intervalloDate interv2)
{
intervalloDate interv3;
// verifico non siano disgiunti...
if (interv1.fine < interv2.inizio || interv2.fine < interv1.inizio)
{
interv3.inizio = Convert.ToDateTime("9/9/9999");
interv3.fine = Convert.ToDateTime("9/9/9999");
}
else
{
interv3 = interv1;
if (interv2.inizio > interv1.inizio)
{
interv3.inizio = interv2.inizio;
}
if (interv2.fine < interv1.fine)
{
interv3.fine = interv2.fine;
}
}
return interv3;
}
///
/// oggetto mese precedente alla dataLilmite
///
///
public intervalloDate mesePrecedente(DateTime dataLimite)
{
intervalloDate interv = new intervalloDate();
interv.inizio = dataLimite.AddMonths(-1).AddDays(-(dataLimite.Day - 1)).Subtract(dataLimite.TimeOfDay);
interv.fine = dataLimite.AddDays(-(dataLimite.Day - 1)).Subtract(dataLimite.TimeOfDay);
return interv;
}
///
/// oggetto mese corrente fino alla dataLilmite
///
///
public intervalloDate meseCorrente(DateTime dataLimite)
{
intervalloDate interv = new intervalloDate();
interv.inizio = dataLimite.AddDays(-(dataLimite.Day - 1)).Subtract(dataLimite.TimeOfDay);
interv.fine = dataLimite.Subtract(dataLimite.TimeOfDay);
return interv;
}
///
/// confronta le date e restituisce true se le date sono nello stesso mese
///
///
///
///
public bool stessoMese(DateTime data1, DateTime data2)
{
bool stessoMese = false;
if ((data1.Year == data2.Year) && (data1.Month == data2.Month))
{
stessoMese = true;
}
return stessoMese;
}
///
/// restituisce l'intervallo del giorno completo che comprende la data indicata
///
///
///
public intervalloDate giornata(DateTime data)
{
intervalloDate interv = new intervalloDate();
interv.inizio = data.Subtract(data.TimeOfDay);
interv.fine = interv.inizio.AddDays(1);
return interv;
}
///
/// restituisce l'intervallo di N giorni fino alla data indicata
///
///
///
///
public intervalloDate ultimiGiorni(DateTime data, int numGiorniPrima)
{
intervalloDate interv = new intervalloDate();
interv.fine = data.Subtract(data.TimeOfDay).AddDays(1);
interv.inizio = interv.fine.AddDays(-numGiorniPrima);
return interv;
}
///
/// restituisce l'intervallo della settimana corrente per la data indicata
///
///
///
public intervalloDate questaSett(DateTime data)
{
intervalloDate interv = new intervalloDate();
interv.fine = data.Subtract(data.TimeOfDay).AddDays(1);
DayOfWeek giorno = data.DayOfWeek;
int numGG = 0;
switch (giorno)
{
case DayOfWeek.Monday:
numGG = 1;
break;
case DayOfWeek.Tuesday:
numGG = 2;
break;
case DayOfWeek.Wednesday:
numGG = 3;
break;
case DayOfWeek.Thursday:
numGG = 4;
break;
case DayOfWeek.Friday:
numGG = 5;
break;
case DayOfWeek.Saturday:
numGG = 6;
break;
case DayOfWeek.Sunday:
numGG = 7;
break;
default:
break;
}
interv.inizio = interv.fine.AddDays(-numGG);
return interv;
}
///
/// restituisce l'intervallo del mese corrente per la data indicata (dal giorno 1 all'indomani delal data indicata)
///
///
///
public intervalloDate questoMese(DateTime data)
{
intervalloDate interv = new intervalloDate();
interv.fine = data.Subtract(data.TimeOfDay).AddDays(1);
interv.inizio = interv.fine.AddDays(-data.Day);
return interv;
}
///
/// restituisce l'intervallo del mese che comprende la data indicata (dal primo all'ultimo giorno)
///
///
///
public intervalloDate estremiMese(DateTime data)
{
intervalloDate interv = new intervalloDate();
interv.inizio = data.AddDays(-(data.Day - 1)).Subtract(data.TimeOfDay);
interv.fine = interv.inizio.AddMonths(1);
return interv;
}
///
/// restituisce l'intervallo dell'anno corrente per la data indicata
///
///
///
public intervalloDate estremiAnno(DateTime data)
{
intervalloDate interv = new intervalloDate();
interv.inizio = data.AddDays(-(data.Day - 1)).AddMonths(-(data.Month - 1)).Subtract(data.TimeOfDay);
interv.fine = interv.inizio.AddMonths(12);
return interv;
}
///
/// oggetto singleton
///
public static datario mngr = new datario();
///
/// calcola week number secondo ISO 8601
///
///
///
public static int WeekOfYearISO8601(DateTime date)
{
var day = (int)CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(date);
return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date.AddDays(4 - (day == 0 ? 7 : day)), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
///
/// restituisce la prima data della settimana richiesta
///
///
///
///
public static DateTime FirstDateOfWeekISO8601(int year, int weekOfYear)
{
DateTime jan1 = new DateTime(year, 1, 1);
int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek;
DateTime firstThursday = jan1.AddDays(daysOffset);
var cal = CultureInfo.CurrentCulture.Calendar;
int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
var weekNum = weekOfYear;
if (firstWeek <= 1)
{
weekNum -= 1;
}
var result = firstThursday.AddDays(weekNum * 7);
return result.AddDays(-3);
}
}
}