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 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 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 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 } /// /// 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); } } }