using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; namespace SteamWare { #region gestione date /// /// struttura che definisce i parametri di un turno di lavoro /// public struct turnoLavoro { /// /// Gets or sets the cod turno. /// /// /// The cod turno. /// public string codTurno { get; set; } /// /// Gets or sets the inizio. /// /// /// The inizio. /// public DateTime inizio { get; set; } /// /// Gets or sets the fine. /// /// /// The fine. /// public DateTime fine { get; set; } /// /// Gets or sets the periodo. /// /// /// The periodo. /// public intervalloDate periodo { get; set; } /// /// Gets or sets the durata minuti. /// /// /// The durata minuti. /// public int durataMinuti { get; set; } /// /// Gets or sets the t number. /// /// /// The t number. /// public int TNum { get; set; } } /// /// definisce un intervalo di 2 date /// [Serializable] 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); } } } /// /// struttura orario ordinarie/strordinarie /// public struct orarioSvolto { /// /// ore ordinarie /// public double ordinarie; /// /// ore straordinarie /// public double straordinarie; } /// /// classe di funzioni inerenti le date /// public class datario { /// /// inizializzazione empty /// public datario() { } /// /// calcola il turno di riferimento data una data di riferimento /// /// The data ora rif. /// The shift turno. /// The durata turno. /// public turnoLavoro getTurnoByDateTime(DateTime dataOraRif, int shiftTurno, int durataTurno) { // inizio con shift alla data-ora corrente.. dataOraRif = dataOraRif.AddHours(-shiftTurno); // continuo calcolo TimeSpan oraRif = dataOraRif.TimeOfDay; DateTime dataRif = dataOraRif.Add(-oraRif); // calcolo! turnoLavoro answ = new turnoLavoro(); answ.durataMinuti = 60 * durataTurno; answ.TNum = Convert.ToInt32(Math.Floor(Convert.ToDouble(dataOraRif.Hour) / durataTurno)) + 1; answ.inizio = dataRif.AddHours(shiftTurno + (answ.TNum - 1) * durataTurno); answ.fine = answ.inizio.AddHours(durataTurno); intervalloDate periodo = setIntervallo(answ.inizio, answ.fine); answ.periodo = periodo; return answ; } /// /// 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 di N MESI fino alla data indicata /// /// /// /// public intervalloDate ultimiMesi(DateTime data, int numMesiPrima) { intervalloDate interv = new intervalloDate(); interv.fine = data.Subtract(data.TimeOfDay).AddDays(1); interv.inizio = interv.fine.AddMonths(-numMesiPrima); return interv; } /// /// restituisce l'intervallo di N giorni dalla data indicata in avanti /// /// /// /// public intervalloDate prossimiGiorni(DateTime data, int numGiorniSucc) { intervalloDate interv = new intervalloDate(); interv.inizio = data.Subtract(data.TimeOfDay); interv.fine = interv.inizio.AddDays(numGiorniSucc); 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 della 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 dell'anno corrente per la data indicata (dal giorno 1 all'indomani della data indicata) /// /// /// public intervalloDate questoAnno(DateTime data) { intervalloDate interv = new intervalloDate(); interv.fine = data.Subtract(data.TimeOfDay).AddDays(1); interv.inizio = data.AddDays(-(data.Day - 1)).AddMonths(-(data.Month - 1)).Subtract(data.TimeOfDay); 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(); /// /// converte in datetime un valore formattato con una culture generica ed un formato generico /// /// /// /// /// /// public static DateTime convDate(string dataOra, string formato, string culture, bool doLog) { DateTime answ = DateTime.Now; CultureInfo cInfo = new CultureInfo(culture); if (doLog) logger.lg.scriviLog(string.Format("Valore txt:{1}", Environment.NewLine, dataOra), tipoLog.INFO); bool fatto = false; fatto = DateTime.TryParseExact(dataOra, formato, cInfo, DateTimeStyles.None, out answ); if (doLog) logger.lg.scriviLog(string.Format("{0}Valore txt:{1}{0}Valore conv:{2}", Environment.NewLine, dataOra, answ), tipoLog.INFO); if (!fatto) { answ = Convert.ToDateTime(dataOra); } if (doLog) logger.lg.scriviLog(string.Format("{0}Valore txt:{1}{0}Valore conv BIS:{2}", Environment.NewLine, dataOra, answ), tipoLog.INFO); return answ; } /// /// converte in datetime un valore formattato con una culture generica ed un formato generico /// /// /// /// /// public static DateTime convDate(string dataOra, string formato, string culture) { return convDate(dataOra, formato, culture, false); } /// /// Tipo di periodo selezione date /// public enum periodo { /// /// non definito /// nd, /// /// Solo periodo passato (+ presente) /// past, /// /// Solo periodo futuro (+ presente) /// future, /// /// tutto /// all } } /// /// Helper methods e funzioni x gestione conversione dataset tipizzati e non /// /// A strongly type DataTable. /// A DataTable of type T will be returned from the DataSet. /// public static class DataSetAdapter where T : DataTable, new() { /// /// Convert the first DataTable from a DataSet to a /// strongly-typed data table. /// public static T convert(DataSet dataSet) { if (dataSet == null) return null; if (dataSet.Tables.Count == 0) return null; DataTable dataTable = dataSet.Tables[0]; return convert(dataTable); } /// /// Convert an ordinary DataTable to a strongly-typed /// data table. /// public static T convert(DataTable dataTable) { if (dataTable == null) return null; T stronglyTyped = new T(); // add data from the regular DataTable to the // strongly typed DataTable. stronglyTyped.Merge(dataTable, true, MissingSchemaAction.Ignore); return stronglyTyped; } } #endregion #region gestione email & log... /// /// classe di gestione delle email /// public class gestEmail { /// /// 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) { logger.lg.scriviLog(string.Format("[Modulo gestEmail]: avviato con parametro smtp {0} - SENZA USER/PWD", smtpCli), tipoLog.STARTUP); _smtpCli = smtpCli; _username = ""; _password = ""; } /// /// metodo static per la gestione delle email /// /// /// /// public gestEmail(string smtpCli, string user, string pwd) { logger.lg.scriviLog(string.Format("[Modulo gestEmail]: avviato con parametro smtp {0} ed utente {1}", smtpCli, user), tipoLog.STARTUP); _smtpCli = smtpCli; _username = user; _password = pwd; } /// /// metodo static per la gestione delle email /// /// /// public gestEmail(string smtpCli, string logDir) { logger.lg.scriviLog(string.Format("[Modulo gestEmail]: avviato con parametro smtp {0} e logdir", smtpCli), tipoLog.STARTUP); _smtpCli = smtpCli; _username = ""; _password = ""; } /// /// procedura invio email /// /// email mittente /// email destinatario /// oggetto dell'email /// corpo del messaggio /// allegati del messaggio public bool mandaEmailNoLog(string _mailFrom, string _mailTo, string _oggetto, string _corpo, AlternateView[] _allegati) { // sostituisco eventuali a capo nel corpo messaggio... _corpo = _corpo.Replace("\r", "
"); _corpo = _corpo.Replace("\n", "
"); //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.UseDefaultCredentials = false; //_smtpClient.Port = 587; //_smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; _smtpClient.Credentials = new System.Net.NetworkCredential(_username, _password); _smtpClient.EnableSsl = memLayer.ML.confReadBool("_enableSSL"); // verifico se sia porta non standard... if (memLayer.ML.CRS("_PortSSL") != "") { _smtpClient.Port = memLayer.ML.CRI("_PortSSL"); } } // eventualmente aggiungo allegati... foreach (AlternateView allegato in _allegati) { messaggio.AlternateViews.Add(allegato); } 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()); logger.lg.scriviLog(string.Format("{0}\r\n full error message\r\n {1}", esmtp.Message, esmtp.ToString()), tipoLog.EXCEPTION); return false; } } /// /// procedura invio email /// /// email mittente /// email destinatario /// oggetto dell'email /// corpo del messaggio public bool mandaEmailNoLog(string _mailFrom, string _mailTo, string _oggetto, string _corpo) { // sostituisco eventuali a capo nel corpo messaggio... _corpo = _corpo.Replace("\r", "
"); _corpo = _corpo.Replace("\n", "
"); //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.UseDefaultCredentials = false; //_smtpClient.Port = 587; //_smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; _smtpClient.Credentials = new NetworkCredential(_username, _password); _smtpClient.EnableSsl = memLayer.ML.CRB("_enableSSL"); // verifico se sia porta non standard... if (memLayer.ML.CRS("_PortSSL") != "") { _smtpClient.Port = memLayer.ML.CRI("_PortSSL"); } } 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()); logger.lg.scriviLog(string.Format("{0}\r\n full error message\r\n {1}", esmtp.Message, esmtp.ToString()), tipoLog.EXCEPTION); 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); logger.lg.scriviLog(string.Format("Email inviata, destinatario: {2}{1}oggetto: {0}{1}------------------------------------{1}{2}{1}------------------------------------", _oggetto, Environment.NewLine, _corpo, _mailTo), tipoLog.INFO); } catch (Exception e) { logger.lg.scriviLog(string.Format("ERRORE! Email NON INVIATA!oggetto: {0} corpo: {1} eccezione:{2}{3}", _oggetto, _corpo, Environment.NewLine, e), tipoLog.EXCEPTION); } return fatto; } /// /// procedura invio email + scrittura in log! /// /// email mittente /// email destinatario /// oggetto dell'email /// corpo del messaggio /// allegati del messaggio public bool mandaEmail(string _mailFrom, string _mailTo, string _oggetto, string _corpo, AlternateView[] _allegati) { bool fatto = false; //manda email... try { fatto = mandaEmailNoLog(_mailFrom, _mailTo, _oggetto, _corpo, _allegati); logger.lg.scriviLog(string.Format("Email inviata: oggetto: {0}, corpo:{1}{1}{2}", _oggetto, Environment.NewLine, _corpo), tipoLog.INFO); } catch (Exception e) { logger.lg.scriviLog(string.Format("ERRORE! Email NON INVIATA!oggetto: {0} corpo: {1} eccezione:{2}{3}", _oggetto, _corpo, Environment.NewLine, e), tipoLog.EXCEPTION); } return fatto; } /// /// metodo singleton gestione email... /// public static gestEmail ge = new gestEmail(memLayer.ML.confReadString("_smtpCli")); /// /// metodo singleton gestione email CON AUTH utente... /// public static gestEmail geAuth = new gestEmail(memLayer.ML.confReadString("_smtpCli"), memLayer.ML.confReadString("_emailUser"), memLayer.ML.confReadString("_emailPwd")); } #endregion #region gestione stringhe namespace StringSplitter { /// /// Tipo di comparazione, Binary == CaseSensitive, Text = insensitive /// public enum ComparisonMethod { /// /// tipo controllo : binario /// Binary = 0, /// /// tipo controllo : text /// Text = 1 } /// /// Funzione di splitting compatibile con multi-character e multi-line /// public class CSplitter { /// /// stringa da splittare /// private static string m_Expression; /// /// Delimiter con cui splittare /// private static string m_Delimiter; /// /// Costruttore dello Splitter /// public CSplitter() { // non fa nulla all'inizializzazione } /// /// comparatore case sensitive /// /// /// /// private static bool isValidDelimiterBinary(int StringIndex, int DelimiterIndex) { if (DelimiterIndex == m_Delimiter.Length) return true; if (StringIndex == m_Expression.Length) return false; //If the current character of the expression matches //the current character of the Delimiter, //then go to next character if (m_Expression[StringIndex] == m_Delimiter[DelimiterIndex]) return isValidDelimiterBinary(StringIndex + 1, DelimiterIndex + 1); else return false; } /// /// comparatore case insensitive /// /// /// /// private static bool isValidDelimiterText(int StringIndex, int DelimiterIndex) { if (DelimiterIndex == m_Delimiter.Length) return true; if (StringIndex == m_Expression.Length) return false; //If the current character of the expression //matches the current character of the Delimiter, //then go to next character if (Char.ToLower(m_Expression[StringIndex]) == Char.ToLower(m_Delimiter[DelimiterIndex])) return isValidDelimiterText(StringIndex + 1, DelimiterIndex + 1); else return false; } /// /// parte principale dello splitter /// /// stringa da splittare /// delimitatore ricercato /// true=il delimiter � un blocco unico, false=qualsiasi oggetto del delimiter fa split (come split base) /// /// 0 -> Binary=CaseSensitive, 1 -> Text=case insensitive /// public static string[] Split(string Expression, string Delimiter, bool SingleSeparator, int Count, ComparisonMethod Compare) { //Update Private Members m_Expression = Expression; m_Delimiter = Delimiter; //Array to hold Splitted Tokens System.Collections.ArrayList Tokens = new System.Collections.ArrayList(); //If not using single separator, //then use the regular split function if (!SingleSeparator) if (Count >= 0) return Expression.Split(Delimiter.ToCharArray(), Count); else return Expression.Split(Delimiter.ToCharArray()); //Check if count = 0 then return an empty array if (Count == 0) return new string[0]; else //Check if Count = 1 then return the whole expression if (Count == 1) return new string[] { Expression }; else Count--; // Indexer to loop over the string with int i; //The Start index of the current //token in the expression int iStart = 0; if (Compare == ComparisonMethod.Binary) { for (i = 0; i < Expression.Length; i++) { if (isValidDelimiterBinary(i, 0)) { //Assign New Token Tokens.Add(Expression.Substring(iStart, i - iStart)); //Update Index i += Delimiter.Length - 1; //Update Current Token Start index iStart = i + 1; //If we reached the tokens limit , then exit For if (Tokens.Count == Count && Count >= 0) break; } } } else { for (i = 0; i < Expression.Length; i++) { if (isValidDelimiterText(i, 0)) { //Assign New Token Tokens.Add(Expression.Substring(iStart, i - iStart)); //Update Index i += Delimiter.Length - 1; //Update Current Token Start index iStart = i + 1; //If we reached the tokens limit , then exit For if (Tokens.Count == Count && Count >= 0) break; } } } string LastToken = ""; //If there is still data & have not been added if (iStart < Expression.Length) { LastToken = Expression.Substring(iStart, Expression.Length - iStart); if (LastToken == Delimiter) Tokens.Add(null); else Tokens.Add(LastToken); } else //If there is no elements in the tokens array, //then pass the whole string as the one element if (Tokens.Count == 0) Tokens.Add(Expression); //Return Splitted Tokens return (string[]) Tokens.ToArray(Type.GetType("System.String")); } /// /// elimina dal nome file il tipo (desinenza) /// /// /// public string nomeFileNoExt(string nomeCompleto) { string[] valori = Split(nomeCompleto, ".", true, 0, ComparisonMethod.Text); return valori[valori.Length - 2]; } } } #endregion /// /// Classe di metodi che estendono quelli base applicati alle string /// public class SteamwareStrings { /// /// Trasforma in MAIUSCOLo il primo carattere della stringa /// /// stringa da processare /// stringa processata public static string firstToUpper(string _stringaIN) { string _stringaOUT = _stringaIN; if (_stringaIN.Length > 1) { _stringaOUT = _stringaIN.Substring(0, 1).ToUpper() + _stringaIN.Substring(1, _stringaIN.Length - 1).ToLower(); } return _stringaOUT; } /// /// restituisce la stringa completa e corretta del filepath del server (anche con vDir) /// /// path relativo alla cartella iis dell'applicativo /// path fisico tradotto public static string getFilePath(string pathRel) { return System.Web.HttpContext.Current.Server.MapPath(pathRel); } /// /// effettua escape di stringhe di ricerca di tipo filtro per apici e altri caratteri non ammessi /// /// /// public static string EscapeSqlLike(string s_) { StringBuilder sb = new StringBuilder(s_.Length); for (int i = 0; i < s_.Length; i++) { char c = s_[i]; switch (c) { case ']': case '[': case '%': case '*': sb.Append("[").Append(c).Append("]"); break; case '\'': sb.Append("''"); break; default: sb.Append(c); break; } } return sb.ToString(); } /// /// restituisce una stringa uguale all'originale + terminazione newline /// /// /// public static string addLine(object s) { return string.Format("{0}{1}", s, Environment.NewLine); } /// /// formatta un titolo /// /// Titolo da scrivere /// carattere x padding titolo /// larghezza caratteri (x pad) /// public static string charTitle(object title, char padChar, int repNum) { string answ = ""; answ += addLine(new string(padChar, repNum)); answ += addLine(string.Format("{0} {1}", padChar, title)); answ += addLine(new string(padChar, repNum)); return answ; } /// /// formatta una riga di caratteri /// /// carattere da utilizzare /// larghezza caratteri (x pad) /// public static string charLine(char padChar, int repNum) { string answ = ""; answ += addLine(new string(padChar, repNum)); return answ; } /// /// genera stringhe pseudo-casuali /// /// /// public static string pseudoRandomString(int Lenght) { string answ = ""; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new Random(); answ = new string( Enumerable.Repeat(chars, Lenght) .Select(s => s[random.Next(s.Length)]) .ToArray()); return answ; } /// /// limita una stringa al numero max di caratteri imposto /// /// /// /// public static string limitString(string original, int maxChar) { string outString = original; if (outString.Length > maxChar) { outString = string.Format("{0}...", original.Substring(0, maxChar - 3)); } return outString; } /// /// limita una stringa al numero max di caratteri imposto prendendo ANCHE ultimi /// /// /// /// /// public static string limitString(string original, int maxChar, int lastNumChar) { string outString = original; if (outString.Length > maxChar) { outString = string.Format("{0}...{1}", original.Substring(0, maxChar - 3 - lastNumChar), original.Substring(outString.Length - lastNumChar)); } return outString; } } /// /// fornisce dati di base per l'utente /// public class anagrData { /// /// fornisce cognome e nome utente formattati a partire dall'username e dalla tabella UTENTE /// /// /// public string datiUtenteDaUsername(string username) { string answ = ""; DataLayer_AnagGenTableAdapters.UTENTETableAdapter taUtente = new SteamWare.DataLayer_AnagGenTableAdapters.UTENTETableAdapter(); try { DataLayer_AnagGen.UTENTERow _rigaUt = taUtente.GetData().FindByUSER_NAME(username); answ = String.Format("{0} {1}", _rigaUt.COGNOME, _rigaUt.NOME); } catch { } return answ; } /// /// restituisce la riga completa dall'username richiesto /// /// /// public DataLayer_AnagGen.UTENTERow rigaUtenteDaUsername(string username) { DataLayer_AnagGenTableAdapters.UTENTETableAdapter taUtente = new SteamWare.DataLayer_AnagGenTableAdapters.UTENTETableAdapter(); try { return taUtente.GetData().FindByUSER_NAME(username); } catch { return null; } } } /// /// utility x dns e naming /// public class dnsUtils { /// /// calcola il nome del computer dato l'IP /// /// /// public static string DetermineCompName(string IP) { IPAddress myIP = IPAddress.Parse(IP); IPHostEntry GetIPHost = Dns.GetHostEntry(myIP); List compName = GetIPHost.HostName.ToString().Split('.').ToList(); return compName.First(); } /// /// Metodo x restituire nome dato IP tramite Reverse Lookup /// /// /// public static string ReverseLookup(string ip) { if (string.IsNullOrEmpty(ip)) return ip; try { return Dns.GetHostEntry(ip).HostName; //.Select(entry => entry.HostName).FirstOrDefault() ?? ip; } catch (SocketException) { return ip; } } /// /// scarica una pagina da URL e fornisce testo string /// /// Indirizzo pagina (completo) /// username (se necessario) /// password (se necessaria) /// public static string wgetPage(string URL, string user, string passwd) { string page = ""; try { using (var client = new WebClient()) { client.Credentials = new NetworkCredential(user, passwd); page = client.DownloadString(URL); } } catch { } return page; } /// /// manda pacchetto ARP /// /// /// /// /// /// [DllImport("iphlpapi.dll", ExactSpelling = true)] public static extern int SendARP(int DestIP, int SrcIP, [Out] byte[] pMacAddr, ref int PhyAddrLen); /// /// fornisce mac address dato nome/IP /// /// /// public static string GetMacAddress(string sName) { string s = string.Empty; System.Net.IPHostEntry Tempaddr = null; Tempaddr = (System.Net.IPHostEntry)Dns.GetHostEntry(sName); System.Net.IPAddress[] TempAd = Tempaddr.AddressList; string[] Ipaddr = new string[3]; foreach (IPAddress TempA in TempAd) { Ipaddr[1] = TempA.ToString(); byte[] ab = new byte[6]; int len = ab.Length; int r = SendARP((int)BitConverter.ToInt32(TempA.GetAddressBytes(), 0), 0, ab, ref len); string sMAC = BitConverter.ToString(ab, 0, 6); Ipaddr[2] = sMAC; s = sMAC; } return s; } } /// /// Helper per gestione jscripts vari /// public class jsUtils { /// /// restituisce la stringa di codice javascript x conferma client comprensiva di messaggio tradotto specifico /// /// /// public static string getCBE(object lemma) { return string.Format("return confirm('{0}'); ", user_std.UtSn.Traduci(lemma.ToString())); } /// /// restituisce la stringa di codice javascript x conferma client comprensiva di messaggio tradotto specifico /// /// /// /// public static string getCBE(object lemma, object doTranslate) { string answ = ""; // verifico se richiesta traduzione... if (Convert.ToBoolean(doTranslate)) { answ = getCBE(lemma); } else { answ = string.Format("return confirm('{0}')", lemma); } return answ; } } /// /// classi helper gestione URL /// public class urlUtils { /// /// chiama un URL e restituisce (se richiesto) il risultato ricevuto /// /// url da chiamare /// se si vuole in risposta il contenuto della risposta alla chiamata /// public static string callUrl(string url, bool returnAnsw) { string answ = ""; try { WebRequest request = HttpWebRequest.Create(url); WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); if (returnAnsw) { answ = reader.ReadToEnd(); } } catch { } return answ; } } /// /// utils x cifrature e Crypto /// public class SteamCrypto { /// /// cifra un messaggio con una password /// /// /// /// public static string EncryptString(string Message, string Passphrase) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); // Step 1. We hash the passphrase using MD5 // We use the MD5 hash generator as the result is a 128 bit byte array // which is a valid length for the TripleDES encoder we use below MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase)); // Step 2. Create a new TripleDESCryptoServiceProvider object TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); // Step 3. Setup the encoder TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; // Step 4. Convert the input string to a byte[] byte[] DataToEncrypt = UTF8.GetBytes(Message); // Step 5. Attempt to encrypt the string try { ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor(); Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information TDESAlgorithm.Clear(); HashProvider.Clear(); } // Step 6. Return the encrypted string as a base64 encoded string return Convert.ToBase64String(Results); } /// /// decifra un messaggio con una password /// /// /// /// public static string DecryptString(string Message, string Passphrase) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); // Step 1. We hash the passphrase using MD5 // We use the MD5 hash generator as the result is a 128 bit byte array // which is a valid length for the TripleDES encoder we use below MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase)); // Step 2. Create a new TripleDESCryptoServiceProvider object TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); // Step 3. Setup the decoder TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; // Step 4. Convert the input string to a byte[] byte[] DataToDecrypt = Convert.FromBase64String(Message); // Step 5. Attempt to decrypt the string try { ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information TDESAlgorithm.Clear(); HashProvider.Clear(); } // Step 6. Return the decrypted string in UTF8 format return UTF8.GetString(Results); } /// /// genera hash di una stringa in MD5 (es x hash gravatar) /// /// /// public static string getHashStringMD5(string Message) { string hash = ""; using (MD5 md5Hash = MD5.Create()) { hash = GetMd5Hash(md5Hash, Message); } return hash; } /// /// Crea un hash MD5 /// /// /// /// public static string GetMd5Hash(MD5 md5Hash, string input) { // Convert the input string to a byte array and compute the hash. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); } /// /// Verify a hash against a string. /// /// /// /// /// public static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash) { // Hash the input. string hashOfInput = GetMd5Hash(md5Hash, input); // Create a StringComparer an compare the hashes. StringComparer comparer = StringComparer.OrdinalIgnoreCase; if (0 == comparer.Compare(hashOfInput, hash)) { return true; } else { return false; } } } /// /// classe gestione valori percentuali per semplificare edit utente (moltiplicati x 100 appunto) /// public class percentuali { /// /// converte da percentuale a numero (es 5,3% --> 0.053) /// /// /// public static decimal perc2num(string originalVal) { decimal answ = 0; // se contiene "%" lo tolgo... originalVal = originalVal.Replace("%", ""); // ora controllo se c'� valore > 1... try { // inizio convertendo .. answ = Convert.ToDecimal(originalVal); answ = answ / 100; } catch { } return answ; } /// /// converte da numero a percentuale (es 0.053 --> 5,3%) /// /// /// public static decimal num2perc(string originalVal) { decimal answ = 0; // ora controllo se c'� valore > 1... try { // inizio convertendo .. answ = Convert.ToDecimal(originalVal); answ = answ * 100; } catch { } return answ; } } /// /// gestione helper tempi ciclo /// public class TempiCiclo { /// /// formatta in minuti/sec partendo da min.cent /// /// /// public static string minSec(object minCent) { string answ = ""; try { answ = string.Format("{0:mm}:{0:ss}", minCent2Sec(Convert.ToDecimal(minCent.ToString().Replace(".", ",")))); } catch { } return answ; } /// /// conversione da tempo minuti centesimali a minuti/secondi /// /// /// public static TimeSpan minCent2Sec(decimal valore) { TimeSpan answ = new TimeSpan(0, 0, 1); try { answ = new TimeSpan(0, Convert.ToInt32(valore), Convert.ToInt32((valore - Convert.ToInt32(valore)) * 60)); } catch { } return answ; } } /// /// Classe gestione divisioni /// public class ratio { /// /// Effettua il calcolo del rapporto numeratore/denominatore come DECIMAL con gestione denominatore != 0 /// /// numeratore /// denominatore /// public static decimal getDecimal(object numVal, object denVal) { decimal answ = 0; decimal num = 0; decimal den = 1; decimal.TryParse(numVal.ToString(), out num); decimal.TryParse(denVal.ToString(), out den); // se il denominatore � 0 --> 1 den = (den == 0) ? 1 : den; answ = num / den; return answ; } } /// /// eventi associati a UserCOntrol SteamWare standard /// public class ucEvent : EventArgs { /// /// tipo di evento segnalato /// public ucEvType tipoEvento { get; set; } /// /// inizializzazione oggetto EventArg specifico /// /// public ucEvent(ucEvType evento) { tipoEvento = evento; } } }