diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..f8109e7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,10 @@ +[*.cs] + +# CA1031: Do not catch general exception types +dotnet_diagnostic.CA1031.severity = none + +# IDE0059: Assegnazione non necessaria di un valore +csharp_style_unused_value_assignment_preference = discard_variable:silent + +# CS0168: La variabile è dichiarata, ma non viene mai usata +dotnet_diagnostic.CS0168.severity = none diff --git a/Jenkinsfile b/Jenkinsfile index 192e7a2..c1182d3 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -7,7 +7,7 @@ pipeline { steps { /* calcolo numero versione... diverso x branch MASTER/DEVELOP */ script { - withEnv(['NEXT_BUILD_NUMBER=736']) { + withEnv(['NEXT_BUILD_NUMBER=737']) { // env.versionNumber = VersionNumber(versionNumberString : '4.1.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true) env.versionNumber = VersionNumber(versionNumberString : '4.1.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}') env.versionNumberBeta = VersionNumber(versionNumberString : '4.1.${BUILD_DATE_FORMATTED, "yyMM"}-beta.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}') diff --git a/SteamWare.IO/Properties/Settings.Designer.cs b/SteamWare.IO/Properties/Settings.Designer.cs index 1f4e35e..74a60b4 100644 --- a/SteamWare.IO/Properties/Settings.Designer.cs +++ b/SteamWare.IO/Properties/Settings.Designer.cs @@ -12,7 +12,7 @@ namespace SteamWare.IO.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.4.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.7.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); diff --git a/SteamWare.IO/SteamWare.IO.csproj b/SteamWare.IO/SteamWare.IO.csproj index 46fe6e4..99eb3dc 100644 --- a/SteamWare.IO/SteamWare.IO.csproj +++ b/SteamWare.IO/SteamWare.IO.csproj @@ -9,11 +9,12 @@ Properties SteamWare.IO SteamWare.IO - v4.6.2 + v4.6.2 512 true + true @@ -36,20 +37,23 @@ ..\packages\Crc32C.NET.1.0.5.0\lib\net20\Crc32C.NET.dll - - ..\packages\DnsClient.1.2.0\lib\net45\DnsClient.dll + + ..\packages\DnsClient.1.3.2\lib\net45\DnsClient.dll ..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\packages\MongoDB.Bson.2.10.2\lib\net452\MongoDB.Bson.dll + + ..\packages\Microsoft.Bcl.AsyncInterfaces.1.1.1\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll - - ..\packages\MongoDB.Driver.2.10.2\lib\net452\MongoDB.Driver.dll + + ..\packages\MongoDB.Bson.2.11.1\lib\net452\MongoDB.Bson.dll - - ..\packages\MongoDB.Driver.Core.2.10.2\lib\net452\MongoDB.Driver.Core.dll + + ..\packages\MongoDB.Driver.2.11.1\lib\net452\MongoDB.Driver.dll + + + ..\packages\MongoDB.Driver.Core.2.11.1\lib\net452\MongoDB.Driver.Core.dll ..\packages\MongoDB.Libmongocrypt.1.0.0\lib\net452\MongoDB.Libmongocrypt.dll @@ -58,58 +62,83 @@ ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll - ..\packages\NLog.4.6.8\lib\net45\NLog.dll + ..\packages\NLog.4.7.4\lib\net45\NLog.dll - ..\packages\Pipelines.Sockets.Unofficial.2.1.1\lib\net461\Pipelines.Sockets.Unofficial.dll + ..\packages\Pipelines.Sockets.Unofficial.2.1.16\lib\net461\Pipelines.Sockets.Unofficial.dll - - ..\packages\SharpCompress.0.24.0\lib\net45\SharpCompress.dll + + ..\packages\SharpCompress.0.26.0\lib\net46\SharpCompress.dll ..\packages\Snappy.NET.1.1.1.8\lib\net45\Snappy.NET.dll - ..\packages\StackExchange.Redis.2.0.601\lib\net461\StackExchange.Redis.dll + ..\packages\StackExchange.Redis.2.1.58\lib\net461\StackExchange.Redis.dll - - ..\packages\SteamWare.Logger.4.0.2002.727\lib\net462\SteamWare.Logger.dll + + ..\packages\SteamWare.Logger.4.1.2008.736\lib\net462\SteamWare.Logger.dll - ..\packages\System.Buffers.4.5.0\lib\netstandard2.0\System.Buffers.dll + ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll ..\packages\System.Diagnostics.PerformanceCounter.4.7.0\lib\net461\System.Diagnostics.PerformanceCounter.dll - - - ..\packages\System.IO.Pipelines.4.7.0\lib\netstandard2.0\System.IO.Pipelines.dll + + + ..\packages\System.IO.Pipelines.4.7.2\lib\net461\System.IO.Pipelines.dll - ..\packages\System.Memory.4.5.3\lib\netstandard2.0\System.Memory.dll + ..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + True + True ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll - ..\packages\System.Runtime.CompilerServices.Unsafe.4.7.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll + ..\packages\System.Runtime.CompilerServices.Unsafe.4.7.1\lib\net461\System.Runtime.CompilerServices.Unsafe.dll - + + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.1\lib\net461\System.Security.Cryptography.Algorithms.dll + True + True + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + True + True + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + True + True + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.2\lib\net461\System.Security.Cryptography.X509Certificates.dll True True - - ..\packages\System.Threading.Channels.4.7.0\lib\netstandard2.0\System.Threading.Channels.dll + ..\packages\System.Threading.Channels.4.7.1\lib\net461\System.Threading.Channels.dll - ..\packages\System.Threading.Tasks.Extensions.4.5.3\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll @@ -117,7 +146,6 @@ - @@ -147,6 +175,9 @@ + + .editorconfig + DataLayer_generic.xsd @@ -179,6 +210,9 @@ + + + @@ -187,5 +221,7 @@ Questo progetto fa riferimento a uno o più pacchetti NuGet che non sono presenti in questo computer. Usare lo strumento di ripristino dei pacchetti NuGet per scaricarli. Per altre informazioni, vedere http://go.microsoft.com/fwlink/?LinkID=322105. Il file mancante è {0}. + + \ No newline at end of file diff --git a/SteamWare.IO/app.config b/SteamWare.IO/app.config index 2f00522..b2b295d 100644 --- a/SteamWare.IO/app.config +++ b/SteamWare.IO/app.config @@ -1,53 +1,61 @@ - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + + + + + + + + + + + + + - \ No newline at end of file + diff --git a/SteamWare.IO/packages.config b/SteamWare.IO/packages.config index 13f38fe..dda52ed 100644 --- a/SteamWare.IO/packages.config +++ b/SteamWare.IO/packages.config @@ -1,26 +1,33 @@  - - - - + + + + + - - - + + + - - - + + + - - + + + + - + - - + + + + + + \ No newline at end of file diff --git a/SteamWare.Logger/SteamWare.Logger.csproj b/SteamWare.Logger/SteamWare.Logger.csproj index 6863627..26ba1a9 100644 --- a/SteamWare.Logger/SteamWare.Logger.csproj +++ b/SteamWare.Logger/SteamWare.Logger.csproj @@ -32,7 +32,7 @@ - ..\packages\NLog.4.6.8\lib\net45\NLog.dll + ..\packages\NLog.4.7.4\lib\net45\NLog.dll @@ -56,6 +56,9 @@ + + .editorconfig + Always diff --git a/SteamWare.Logger/packages.config b/SteamWare.Logger/packages.config index aa0bddf..32f10a9 100644 --- a/SteamWare.Logger/packages.config +++ b/SteamWare.Logger/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/SteamWare.Reports/SteamWare.Reports.csproj b/SteamWare.Reports/SteamWare.Reports.csproj index e124d25..18550b5 100644 --- a/SteamWare.Reports/SteamWare.Reports.csproj +++ b/SteamWare.Reports/SteamWare.Reports.csproj @@ -53,6 +53,10 @@ - + + + .editorconfig + + \ No newline at end of file diff --git a/SteamWare.sln b/SteamWare.sln index 9cfa1c7..76cac37 100644 --- a/SteamWare.sln +++ b/SteamWare.sln @@ -15,6 +15,11 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SteamWare.Logger", "SteamWa EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Steamware.Scheduler", "Steamware.Scheduler\Steamware.Scheduler.csproj", "{8901AFAC-987A-40C9-B730-D1FDE0E5170C}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D288348A-1636-463B-B803-0ED937EA54ED}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|.NET = Debug|.NET diff --git a/SteamWareLib/SteamWare.csproj b/SteamWareLib/SteamWare.csproj index d529e8f..157ba86 100644 --- a/SteamWareLib/SteamWare.csproj +++ b/SteamWareLib/SteamWare.csproj @@ -70,28 +70,31 @@ ..\packages\AIM.1.0.3\lib\AegisImplicitMail.dll - - ..\packages\AjaxControlToolkit.19.1.0\lib\net40\AjaxControlToolkit.dll + + ..\packages\AjaxControlToolkit.20.1.0\lib\net40\AjaxControlToolkit.dll ..\packages\Crc32C.NET.1.0.5.0\lib\net20\Crc32C.NET.dll - - ..\packages\DnsClient.1.2.0\lib\net45\DnsClient.dll + + ..\packages\DnsClient.1.3.2\lib\net45\DnsClient.dll ..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\packages\Microsoft.Bcl.AsyncInterfaces.1.1.1\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll + - - ..\packages\MongoDB.Bson.2.10.2\lib\net452\MongoDB.Bson.dll + + ..\packages\MongoDB.Bson.2.11.1\lib\net452\MongoDB.Bson.dll - - ..\packages\MongoDB.Driver.2.10.2\lib\net452\MongoDB.Driver.dll + + ..\packages\MongoDB.Driver.2.11.1\lib\net452\MongoDB.Driver.dll - - ..\packages\MongoDB.Driver.Core.2.10.2\lib\net452\MongoDB.Driver.Core.dll + + ..\packages\MongoDB.Driver.Core.2.11.1\lib\net452\MongoDB.Driver.Core.dll ..\packages\MongoDB.Libmongocrypt.1.0.0\lib\net452\MongoDB.Libmongocrypt.dll @@ -100,7 +103,7 @@ ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll - ..\packages\NLog.4.6.8\lib\net45\NLog.dll + ..\packages\NLog.4.7.4\lib\net45\NLog.dll ..\packages\PDFsharp.1.50.5147\lib\net20\PdfSharp.dll @@ -109,22 +112,22 @@ ..\packages\PDFsharp.1.50.5147\lib\net20\PdfSharp.Charting.dll - ..\packages\Pipelines.Sockets.Unofficial.2.1.1\lib\net461\Pipelines.Sockets.Unofficial.dll + ..\packages\Pipelines.Sockets.Unofficial.2.1.16\lib\net461\Pipelines.Sockets.Unofficial.dll - - ..\packages\SharpCompress.0.24.0\lib\net45\SharpCompress.dll + + ..\packages\SharpCompress.0.26.0\lib\net46\SharpCompress.dll ..\packages\Snappy.NET.1.1.1.8\lib\net45\Snappy.NET.dll - ..\packages\StackExchange.Redis.2.0.601\lib\net461\StackExchange.Redis.dll + ..\packages\StackExchange.Redis.2.1.58\lib\net461\StackExchange.Redis.dll c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.dll - ..\packages\System.Buffers.4.5.0\lib\netstandard2.0\System.Buffers.dll + ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll @@ -137,33 +140,58 @@ - - - ..\packages\System.IO.Pipelines.4.7.0\lib\netstandard2.0\System.IO.Pipelines.dll + + + ..\packages\System.IO.Pipelines.4.7.2\lib\net461\System.IO.Pipelines.dll - ..\packages\System.Memory.4.5.3\lib\netstandard2.0\System.Memory.dll + ..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + True + True ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll - ..\packages\System.Runtime.CompilerServices.Unsafe.4.7.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll + ..\packages\System.Runtime.CompilerServices.Unsafe.4.7.1\lib\net461\System.Runtime.CompilerServices.Unsafe.dll - + + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.1\lib\net461\System.Security.Cryptography.Algorithms.dll + True + True + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + True + True + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + True + True + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.2\lib\net461\System.Security.Cryptography.X509Certificates.dll True True - - ..\packages\System.Threading.Channels.4.7.0\lib\netstandard2.0\System.Threading.Channels.dll + ..\packages\System.Threading.Channels.4.7.1\lib\net461\System.Threading.Channels.dll - ..\packages\System.Threading.Tasks.Extensions.4.5.3\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll @@ -286,6 +314,9 @@ Designer + + .editorconfig + TextTemplatingFileGenerator SteamWare.cs @@ -421,6 +452,8 @@ + + \ No newline at end of file diff --git a/SteamWareLib/app.config b/SteamWareLib/app.config index e6352bc..4c2d8da 100644 --- a/SteamWareLib/app.config +++ b/SteamWareLib/app.config @@ -65,11 +65,11 @@ - + - + @@ -81,7 +81,7 @@ - + @@ -95,6 +95,18 @@ + + + + + + + + + + + + diff --git a/SteamWareLib/packages.config b/SteamWareLib/packages.config index 997772d..9d58927 100644 --- a/SteamWareLib/packages.config +++ b/SteamWareLib/packages.config @@ -1,30 +1,37 @@  - + - - - - - + + + + + + - + - - + + - - + + - - + + + + - + - - + + + + + + \ No newline at end of file diff --git a/SteamWareLib/utils.cs b/SteamWareLib/utils.cs index 4efe435..7da8c65 100644 --- a/SteamWareLib/utils.cs +++ b/SteamWareLib/utils.cs @@ -15,594 +15,594 @@ using System.Text; namespace SteamWare { - #region gestione date + #region gestione date - /// - /// struttura che definisce i parametri di un turno di lavoro - /// - public struct turnoLavoro - { /// - /// Gets or sets the cod turno. + /// struttura che definisce i parametri di un turno di lavoro /// - /// - /// 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 + public struct turnoLavoro { - get - { - bool cond1 = false; - bool cond2 = false; - bool cond3 = false; - try + /// + /// 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 { - cond1 = inizio > Convert.ToDateTime("01/01/0001"); + 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); + } } - catch - { } - try + } + /// + /// 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() { - cond2 = fine > Convert.ToDateTime("01/01/0001"); } - catch - { } - try + /// + /// 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) { - cond3 = (fine.Subtract(inizio).TotalHours > 0); + // 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; } - 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) + /// + /// costruisce un oggetto intervallo date + /// + /// + /// + /// + public intervalloDate setIntervallo(DateTime inizio, DateTime fine) { - interv3.inizio = interv2.inizio; + intervalloDate periodo = new intervalloDate(); + periodo.inizio = inizio; + periodo.fine = fine; + return periodo; } - if (interv2.fine < interv1.fine) + /// + /// 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) { - interv3.fine = interv2.fine; + 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; } - } - 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(); + /// + /// 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); - } + /// + /// 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); - } + 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); - } + 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; + 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 + } } /// - /// converte in datetime un valore formattato con una culture generica ed un formato generico + /// Helper methods e funzioni x gestione conversione dataset tipizzati e non /// - /// - /// - /// - /// - public static DateTime convDate(string dataOra, string formato, string culture) + /// A strongly type DataTable. + /// A DataTable of type T will be returned from the DataSet. + /// + public static class DataSetAdapter + where T : DataTable, new() { - 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; - } + /// + /// 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; - } + 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; - } + 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; + T stronglyTyped = new T(); + // add data from the regular DataTable to the + // strongly typed DataTable. + stronglyTyped.Merge(dataTable, true, MissingSchemaAction.Ignore); + return stronglyTyped; + } } - } - #endregion + #endregion - #region gestione email & log... - /// - /// classe di gestione delle email - /// - public class gestEmail - { + #region gestione email & log... /// - /// stringa del nome DNS o dell'ip del server SMTP + /// classe di gestione delle email /// - 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) + public class gestEmail { - 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) - { - 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); - } + /// + /// 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) + { + 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; - } - /// - /// 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) - { + return answ; + } + /// + /// 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) @@ -610,989 +610,989 @@ namespace SteamWare mymessage.Attachments.Add((MimeAttachment)allegato); } #endif - } - - // Create Smtp Client - int port = 465; - if (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; - } - /// - /// Encode in Base64 - /// - /// - /// - public static string Base64Encode(string plainText) - { - var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); - return System.Convert.ToBase64String(plainTextBytes); - } - /// - /// Decode in Base64 - /// - /// - /// - public static string Base64Decode(string base64EncodedData) - { - var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); - return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); - } - - // 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); - } - } - - /// - /// 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); - } - } - - - /// - /// 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 (_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 (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 (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; - } - } - - /// - /// 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); - } - /// - /// 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; - } - /// - /// 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 - - #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)) + + // Create Smtp Client + int port = 465; + if (!string.IsNullOrEmpty(memLayer.ML.CRS("_PortSSL"))) { - //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; - } + 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; } - string LastToken = ""; - //If there is still data & have not been added - if (iStart < Expression.Length) + /// + /// Encode in Base64 + /// + /// + /// + public static string Base64Encode(string plainText) { - LastToken = Expression.Substring(iStart, - Expression.Length - iStart); - if (LastToken == Delimiter) - { - Tokens.Add(null); - } - else - { - Tokens.Add(LastToken); - } + var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); + return System.Convert.ToBase64String(plainTextBytes); } - else - //If there is no elements in the tokens array, - //then pass the whole string as the one element - if (Tokens.Count == 0) + /// + /// Decode in Base64 + /// + /// + /// + public static string Base64Decode(string base64EncodedData) { - Tokens.Add(Expression); + var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); + return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); } - //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 - - /// - /// 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()) + // A simple call back function: + private void OnMailSent(object sender, AsyncCompletedEventArgs e) { - client.Credentials = new NetworkCredential(user, passwd); - page = client.DownloadString(URL); + 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); + } } - } - 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 = 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; - } - - } - - /// - /// 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) + /// + /// CallBack chiusura invio + /// + /// + /// + private void compEvent(object sender, AsyncCompletedEventArgs e) { - answ = reader.ReadToEnd(); + 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); + } } - } - 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; - 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); - } - /// - /// 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 + /// + /// 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) { - ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); - Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); + // 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; + } } - finally + + /// + /// procedura invio email + /// + /// email mittente + /// email destinatario + /// oggetto dell'email + /// corpo del messaggio + public bool mandaEmailNoLog(string _mailFrom, string _mailTo, string _oggetto, string _corpo) { - // Clear the TripleDes and Hashprovider services of any sensitive information - TDESAlgorithm.Clear(); - HashProvider.Clear(); + // chiamo procedura con alelgati nulli... + return mandaEmailNoLog(_mailFrom, _mailTo, _oggetto, _corpo, null); } - // Step 6. Return the decrypted string in UTF8 format - answ = UTF8.GetString(Results); - } - return answ; + /// + /// 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; + } + /// + /// 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")); } - /// - /// genera hash di una stringa in MD5 (es x hash gravatar) - /// - /// - /// - public static string getHashStringMD5(string Message) + #endregion + + #region gestione stringhe + + namespace StringSplitter { - string hash = ""; - using (MD5 md5Hash = MD5.Create()) - { - hash = GetMd5Hash(md5Hash, Message); + /// + /// Tipo di comparazione, Binary == CaseSensitive, Text = insensitive + /// + public enum ComparisonMethod + { + /// + /// tipo controllo : binario + /// + Binary = 0, + /// + /// tipo controllo : text + /// + Text = 1 + } - } - return hash; + /// + /// 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 + /// - /// Crea un hash MD5 + /// fornisce dati di base per l'utente /// - /// - /// - /// - public static string GetMd5Hash(MD5 md5Hash, string input) + public class anagrData { - - // 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(); + /// + /// 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; + } + } } + /// - /// Verify a hash against a string. + /// utility x dns e naming /// - /// - /// - /// - /// - public static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash) + public class dnsUtils { - // Hash the input. - string hashOfInput = GetMd5Hash(md5Hash, input); + /// + /// 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; + } - // Create a StringComparer an compare the hashes. - StringComparer comparer = StringComparer.OrdinalIgnoreCase; + 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 = 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; + } - 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) + /// Helper per gestione jscripts vari /// - /// - /// - public static decimal perc2num(string originalVal) + public class jsUtils { - 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; - } - } + /// + /// restituisce la stringa di codice javascript x conferma client comprensiva di messaggio tradotto specifico + /// + /// + /// + public static string getCBE(object lemma) + { - /// - /// 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; + 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; + 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); + } + /// + /// 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; + } + + /// + /// 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; + } } - } } diff --git a/Steamware.Scheduler/Steamware.Scheduler.csproj b/Steamware.Scheduler/Steamware.Scheduler.csproj index 70dc0a2..02f3154 100644 --- a/Steamware.Scheduler/Steamware.Scheduler.csproj +++ b/Steamware.Scheduler/Steamware.Scheduler.csproj @@ -48,5 +48,10 @@
+ + + .editorconfig + + \ No newline at end of file diff --git a/TestBench/App.config b/TestBench/App.config index 48a24fd..c05352e 100644 --- a/TestBench/App.config +++ b/TestBench/App.config @@ -20,7 +20,7 @@ - + @@ -32,7 +32,7 @@ - + @@ -46,6 +46,10 @@ + + + + \ No newline at end of file