using AegisImplicitMail;
using System;
using System.Collections.Generic;
using System.ComponentModel;
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
{
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
{
#region Private Fields
///
/// Delimiter con cui splittare
///
private static string m_Delimiter;
///
/// stringa da splittare
///
private static string m_Expression;
#endregion Private Fields
#region Public Constructors
///
/// Costruttore dello Splitter
///
public CSplitter()
{
// non fa nulla all'inizializzazione
}
#endregion Public Constructors
#region Private Methods
///
/// 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;
}
}
#endregion Private Methods
#region Public Methods
///
/// 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 Public Methods
}
}
///
/// definisce un intervalo di 2 date
///
[Serializable]
public struct intervalloDate
{
#region Public Fields
///
/// data fine
///
public DateTime fine;
///
/// data inizio
///
public DateTime inizio;
#endregion Public Fields
#region Public Properties
///
/// 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);
}
}
#endregion Public Properties
}
///
/// struttura orario ordinarie/strordinarie
///
public struct orarioSvolto
{
#region Public Fields
///
/// ore ordinarie
///
public double ordinarie;
///
/// ore straordinarie
///
public double straordinarie;
#endregion Public Fields
}
///
/// struttura che definisce i parametri di un turno di lavoro
///
public struct turnoLavoro
{
#region Public Properties
///
/// Gets or sets the cod turno.
///
///
/// The cod turno.
///
public string codTurno { get; set; }
///
/// Gets or sets the durata minuti.
///
///
/// The durata minuti.
///
public int durataMinuti { get; set; }
///
/// Gets or sets the fine.
///
///
/// The fine.
///
public DateTime fine { get; set; }
///
/// Gets or sets the inizio.
///
///
/// The inizio.
///
public DateTime inizio { get; set; }
///
/// Gets or sets the periodo.
///
///
/// The periodo.
///
public intervalloDate periodo { get; set; }
///
/// Gets or sets the t number.
///
///
/// The t number.
///
public int TNum { get; set; }
#endregion Public Properties
}
///
/// 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()
{
#region Public Methods
///
/// 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 Public Methods
}
///
/// fornisce dati di base per l'utente
///
public class anagrData
{
#region Public Methods
///
/// 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;
}
}
#endregion Public Methods
}
///
/// classe di funzioni inerenti le date
///
public class datario
{
#region Public Fields
///
/// oggetto singleton
///
public static datario mngr = new datario();
#endregion Public Fields
#region Public Constructors
///
/// inizializzazione empty
///
public datario()
{
}
#endregion Public Constructors
#region Public Enums
///
/// Tipo di periodo selezione date
///
public enum periodo
{
///
/// non definito
///
nd,
///
/// Solo periodo passato (+ presente)
///
past,
///
/// Solo periodo futuro (+ presente)
///
future,
///
/// tutto
///
all
}
#endregion Public Enums
#region Public Methods
///
/// 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);
}
///
/// 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;
}
///
/// 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;
}
///
/// 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;
}
///
/// 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;
}
///
/// 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 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;
}
///
/// 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;
}
///
/// 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 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 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;
}
///
/// costruisce un oggetto intervallo date
///
///
///
///
public intervalloDate setIntervallo(DateTime inizio, DateTime fine)
{
intervalloDate periodo = new intervalloDate();
periodo.inizio = inizio;
periodo.fine = fine;
return periodo;
}
///
/// 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 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;
}
#endregion Public Methods
}
///
/// utility x dns e naming
///
public class dnsUtils
{
#region Public Methods
///
/// 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();
}
///
/// fornisce mac address dato nome/IP
///
///
///
public static string GetMacAddress(string sName)
{
string s = string.Empty;
System.Net.IPHostEntry Tempaddr = null;
Tempaddr = 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(BitConverter.ToInt32(TempA.GetAddressBytes(), 0), 0, ab, ref len);
string sMAC = BitConverter.ToString(ab, 0, 6);
Ipaddr[2] = sMAC;
s = sMAC;
}
return s;
}
///
/// 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; }
}
///
/// manda pacchetto ARP
///
///
///
///
///
///
[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(int DestIP, int SrcIP, [Out] byte[] pMacAddr, ref int PhyAddrLen);
///
/// 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;
}
#endregion Public Methods
}
///
/// classe di gestione delle email
///
public class gestEmail
{
#region Protected Fields
///
/// stringa pwd x server SMTP
///
protected string _password;
///
/// stringa del nome DNS o dell'ip del server SMTP
///
protected string _smtpCli;
///
/// stringa username x server SMTP
///
protected string _username;
#endregion Protected Fields
#region Public Fields
///
/// metodo singleton gestione email...
///
public static gestEmail ge = new gestEmail(memLayer.ML.CRS("_smtpCli"));
///
/// metodo singleton gestione email CON AUTH utente...
///
public static gestEmail geAuth = new gestEmail(memLayer.ML.CRS("_smtpCli"), memLayer.ML.CRS("_emailUser"), memLayer.ML.CRS("_emailPwd"));
#endregion Public Fields
#region Public Constructors
///
/// 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 = "";
}
#endregion Public Constructors
#region Private Methods
///
/// CallBack chiusura invio
///
///
///
private void compEvent(object sender, AsyncCompletedEventArgs e)
{
if (e.UserState != null)
{
logger.lg.scriviLog(e.UserState.ToString());
}
if (e.Cancelled)
{
logger.lg.scriviLog("Invio cancellato");
}
Console.Out.WriteLine("is it canceled? " + e.Cancelled);
if (e.Error != null)
{
logger.lg.scriviLog("Invio con errori: " + e.Error.Message);
}
}
// A simple call back function:
private void OnMailSent(object sender, AsyncCompletedEventArgs e)
{
if (e.UserState != null)
{
logger.lg.scriviLog(e.UserState.ToString());
}
if (e.Cancelled)
{
logger.lg.scriviLog("Invio cancellato");
}
Console.Out.WriteLine("is it canceled? " + e.Cancelled);
if (e.Error != null)
{
logger.lg.scriviLog("Invio con errori: " + e.Error.Message);
}
}
///
/// Invia con metodo del client AIM x compatilbiiltà SSL implicito and co
/// https://sourceforge.net/projects/netimplicitssl/
///
/// email mittente
/// email destinatario
/// oggetto dell'email
/// corpo del messaggio
/// allegati del messaggio
///
private bool sendWithAIMClient(string _mailFrom, string _mailTo, string _oggetto, string _corpo, AlternateView[] _allegati)
{
// Generate Message
var mymessage = new MimeMailMessage();
mymessage.From = new MimeMailAddress(_mailFrom);
mymessage.To.Add(_mailTo);
mymessage.Subject = _oggetto;
mymessage.Body = _corpo;
if (_allegati != null)
{
#if false
// eventualmente aggiungo allegati...
foreach (AlternateView allegato in _allegati)
{
mymessage.Attachments.Add((MimeAttachment)allegato);
}
#endif
}
// Create Smtp Client
int port = 465;
if (!string.IsNullOrEmpty(memLayer.ML.CRS("_PortSSL")))
{
port = memLayer.ML.CRI("_PortSSL");
}
var emailer = new SmtpSocketClient();
emailer.Host = _smtpCli;
emailer.Port = port;
emailer.SslType = SslMode.Ssl;
emailer.User = (_username);
emailer.Password = _password;
emailer.AuthenticationMode = AuthenticationType.Base64;
emailer.Timeout = 5000;
// The authentication types depends on your server, it can be plain, base 64 or none.
//if you do not need user name and password means you are using default credentials
// In this case, your authentication type is none
emailer.MailMessage = mymessage;
emailer.SendCompleted += OnMailSent;
emailer.SendMailAsync();
return true;
}
///
/// Invia con metodo del client Net standard
///
/// email mittente
/// email destinatario
/// oggetto dell'email
/// corpo del messaggio
/// allegati del messaggio
///
private bool sendWithNetClient(string _mailFrom, string _mailTo, string _oggetto, string _corpo, AlternateView[] _allegati)
{
// compone messaggio
MailMessage messaggio = new MailMessage(_mailFrom, _mailTo, _oggetto, _corpo);
messaggio.IsBodyHtml = true;
//manda email...
SmtpClient _smtpClient = new SmtpClient(_smtpCli);
// se ci sono credenziali utente...
if (!string.IsNullOrEmpty(_username))
{
//_smtpClient.UseDefaultCredentials = false;
//_smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
_smtpClient.Credentials = new System.Net.NetworkCredential(_username, _password);
_smtpClient.EnableSsl = memLayer.ML.CRB("_enableSSL");
// verifico se ci sia timeout...
if (memLayer.ML.CRI("_smtpTimeout") > 0)
{
_smtpClient.Timeout = memLayer.ML.CRI("_smtpTimeout");
}
// verifico se ci sia priority...
if (!string.IsNullOrEmpty(memLayer.ML.CRS("_msgPriority")))
{
switch (memLayer.ML.CRS("_msgPriority").ToUpper())
{
case "HIGH":
messaggio.Priority = MailPriority.High;
break;
case "LOW":
messaggio.Priority = MailPriority.Low;
break;
case "NORM":
default:
messaggio.Priority = MailPriority.Normal;
break;
}
}
// verifico se sia porta non standard...
if (!string.IsNullOrEmpty(memLayer.ML.CRS("_PortSSL")))
{
_smtpClient.Port = memLayer.ML.CRI("_PortSSL");
}
}
// eventualmente aggiungo allegati...
if (_allegati != null)
{
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;
}
}
#endregion Private Methods
#region Public Methods
///
/// Decode in Base64
///
///
///
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
///
/// Encode in Base64
///
///
///
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
///
/// 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" +
"{0}------------------------------------{0}" +
"destinatario: {1}{0}" +
"oggetto: {2}{0}" +
"------------------------------------------------------------------------{0}" +
"{3}" +
"{0}------------------------------------------------------------------------{0}{0}", Environment.NewLine, _mailTo, _oggetto, _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;
}
///
/// 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;
}
///
/// 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)
{
bool answ = false;
// sostituisco eventuali a capo nel corpo messaggio...
_corpo = _corpo.Replace("\r", "
");
_corpo = _corpo.Replace("\n", "
");
//_useAIMSmtp
if (memLayer.ML.CRB("_useAIMSmtp"))
{
answ = sendWithAIMClient(_mailFrom, _mailTo, _oggetto, _corpo, _allegati);
}
else
{
answ = sendWithNetClient(_mailFrom, _mailTo, _oggetto, _corpo, _allegati);
}
return answ;
}
///
/// procedura invio email
///
/// email mittente
/// email destinatario
/// oggetto dell'email
/// corpo del messaggio
public bool mandaEmailNoLog(string _mailFrom, string _mailTo, string _oggetto, string _corpo)
{
// chiamo procedura con alelgati nulli...
return mandaEmailNoLog(_mailFrom, _mailTo, _oggetto, _corpo, null);
}
#endregion Public Methods
}
///
/// Helper per gestione jscripts vari
///
public class jsUtils
{
#region Public Methods
///
/// 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;
}
#endregion Public Methods
}
///
/// classe gestione valori percentuali per semplificare edit utente (moltiplicati x 100 appunto)
///
public class percentuali
{
#region Public Methods
///
/// 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;
}
///
/// 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;
}
#endregion Public Methods
}
///
/// Classe gestione divisioni
///
public class ratio
{
#region Public Methods
///
/// 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;
}
#endregion Public Methods
}
///
/// utils x cifrature e Crypto
///
public class SteamCrypto
{
#region Public Methods
///
/// decifra un messaggio con una password
///
///
///
///
public static string DecryptString(string Message, string Passphrase)
{
string answ = Message;
byte[] Results = null;
UTF8Encoding UTF8 = new 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 = null;
try
{
DataToDecrypt = Convert.FromBase64String(Message);
}
catch
{ }
if (DataToDecrypt != null)
{
// 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
answ = UTF8.GetString(Results);
}
return answ;
}
///
/// cifra un messaggio con una password
///
///
///
///
public static string EncryptString(string Message, string Passphrase)
{
byte[] Results;
UTF8Encoding UTF8 = new 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);
}
///
/// 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;
}
}
#endregion Public Methods
}
///
/// gestione helper tempi ciclo
///
public class TempiCiclo
{
#region Public Methods
///
/// 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;
}
///
/// 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;
}
#endregion Public Methods
}
///
/// eventi associati a UserCOntrol SteamWare standard
///
public class ucEvent : EventArgs
{
#region Public Constructors
///
/// inizializzazione oggetto EventArg specifico
///
///
public ucEvent(ucEvType evento)
{
tipoEvento = evento;
}
#endregion Public Constructors
#region Public Properties
///
/// tipo di evento segnalato
///
public ucEvType tipoEvento { get; set; }
#endregion Public Properties
}
///
/// classi helper gestione URL
///
public class urlUtils
{
#region Public Methods
///
/// 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;
}
#endregion Public Methods
}
}