From 8103f2bf7fffd40232c91eb68df9d5c537185b3b Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Wed, 13 Sep 2023 10:04:20 +0200 Subject: [PATCH 1/6] Fix log x DataWrap --- SteamWare/DataWrap.cs | 58 +++++++++++++++++++++++++------------------ 1 file changed, 34 insertions(+), 24 deletions(-) diff --git a/SteamWare/DataWrap.cs b/SteamWare/DataWrap.cs index 1107a51..7df1ab9 100644 --- a/SteamWare/DataWrap.cs +++ b/SteamWare/DataWrap.cs @@ -1,4 +1,5 @@ using Newtonsoft.Json; +using NLog; using System.Collections.Generic; namespace SteamWare @@ -159,6 +160,32 @@ namespace SteamWare #endregion Public Properties + #region Public Methods + + /// + /// crea nel db corrente il lemma richiesto e lo valorizza come "--{0}--" + /// + /// + /// + public void creaNuovoLemmaVoc(string lemma) + { + foreach (DataLayer_generic.LingueRow rigaLingua in taLingue.GetData()) + { + taVocabolario.Insert(rigaLingua.Lingua, lemma, string.Format("--{0}--", lemma)); + } + } + + /// + /// resetta il vocabolario rileggendo i dati... + /// + public void resetVocabolario() + { + memLayer.ML.emptyCacheVal("dictVocabolario"); + setupVocabolario(); + } + + #endregion Public Methods + #region Protected Methods /// @@ -251,15 +278,18 @@ namespace SteamWare /// protected void setupVocabolario() { + string source = "DB"; if (memLayer.ML.isInCacheObject("dictVocabolario")) { if (memLayer.ML.cacheOnRedis) { dictVocabolario = JsonConvert.DeserializeObject>(memLayer.ML.objCacheObj("dictVocabolario").ToString()); + source = "REDIS"; } else { dictVocabolario = (Dictionary)memLayer.ML.objCacheObj("dictVocabolario"); + source = "CACHE"; } } else @@ -276,35 +306,15 @@ namespace SteamWare } } // scrivo quanti lemmi ha caricato! - logger.lg.scriviLog(string.Format("Caricati {0} lemmi!", dictVocabolario.Count)); + Log.Info($"setupVocabolario | {source} | Caricati {dictVocabolario.Count} lemmi"); } #endregion Protected Methods - #region Public Methods + #region Private Fields - /// - /// crea nel db corrente il lemma richiesto e lo valorizza come "--{0}--" - /// - /// - /// - public void creaNuovoLemmaVoc(string lemma) - { - foreach (DataLayer_generic.LingueRow rigaLingua in taLingue.GetData()) - { - taVocabolario.Insert(rigaLingua.Lingua, lemma, string.Format("--{0}--", lemma)); - } - } + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); - /// - /// resetta il vocabolario rileggendo i dati... - /// - public void resetVocabolario() - { - memLayer.ML.emptyCacheVal("dictVocabolario"); - setupVocabolario(); - } - - #endregion Public Methods + #endregion Private Fields } } \ No newline at end of file From 5d403348e51c00d3e6b5911c1e3178a7ebfdf1a7 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Wed, 13 Sep 2023 10:24:58 +0200 Subject: [PATCH 2/6] ancora possibile fix dataWrap --- SteamWare/DataWrap.cs | 43 ++++++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/SteamWare/DataWrap.cs b/SteamWare/DataWrap.cs index 7df1ab9..26b579f 100644 --- a/SteamWare/DataWrap.cs +++ b/SteamWare/DataWrap.cs @@ -1,5 +1,6 @@ using Newtonsoft.Json; using NLog; +using System; using System.Collections.Generic; namespace SteamWare @@ -279,31 +280,39 @@ namespace SteamWare protected void setupVocabolario() { string source = "DB"; - if (memLayer.ML.isInCacheObject("dictVocabolario")) + try { - if (memLayer.ML.cacheOnRedis) + if (memLayer.ML.isInCacheObject("dictVocabolario")) { - dictVocabolario = JsonConvert.DeserializeObject>(memLayer.ML.objCacheObj("dictVocabolario").ToString()); - source = "REDIS"; + if (memLayer.ML.cacheOnRedis) + { + dictVocabolario = JsonConvert.DeserializeObject>(memLayer.ML.objCacheObj("dictVocabolario").ToString()); + source = "REDIS"; + } + else + { + dictVocabolario = (Dictionary)memLayer.ML.objCacheObj("dictVocabolario"); + source = "CACHE"; + } } else { - dictVocabolario = (Dictionary)memLayer.ML.objCacheObj("dictVocabolario"); - source = "CACHE"; + dictVocabolario = ricaricaDictVocabolario(); + if (memLayer.ML.cacheOnRedis) + { + string serVal = JsonConvert.SerializeObject(dictVocabolario); + memLayer.ML.setCacheVal("dictVocabolario", serVal, true); + } + else + { + memLayer.ML.setCacheVal("dictVocabolario", dictVocabolario, true); + } } } - else + catch(Exception exc) { - dictVocabolario = ricaricaDictVocabolario(); - if (memLayer.ML.cacheOnRedis) - { - string serVal = JsonConvert.SerializeObject(dictVocabolario); - memLayer.ML.setCacheVal("dictVocabolario", serVal, true); - } - else - { - memLayer.ML.setCacheVal("dictVocabolario", dictVocabolario, true); - } + Log.Error($"Eccezione 01 durante setupVocabolario:{Environment.NewLine}{exc}"); + dictVocabolario = new Dictionary(); } // scrivo quanti lemmi ha caricato! Log.Info($"setupVocabolario | {source} | Caricati {dictVocabolario.Count} lemmi"); From 11209fcaa7d594cc6895711da6ce04d9a546001d Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Wed, 13 Sep 2023 11:11:45 +0200 Subject: [PATCH 3/6] ulteriori fix x logger --- SteamWare.IO/SteamWare.IO.csproj | 6 +- SteamWare.IO/packages.config | 4 +- SteamWare.Logger/SteamWare.Logger.csproj | 4 +- SteamWare.Logger/packages.config | 2 +- SteamWare/DataWrap.cs | 35 ++++++-- SteamWare/SteamWare.csproj | 10 +-- SteamWare/app.config | 4 + SteamWare/packages.config | 6 +- TestBench/App.config | 9 +- TestBench/MainFOrm.Designer.cs | 103 ++++++++++++++++++----- TestBench/MainFOrm.cs | 23 +++++ TestBench/NLog.config | 31 +++++++ TestBench/TestBench.csproj | 8 ++ TestBench/packages.config | 1 + 14 files changed, 201 insertions(+), 45 deletions(-) create mode 100644 TestBench/NLog.config diff --git a/SteamWare.IO/SteamWare.IO.csproj b/SteamWare.IO/SteamWare.IO.csproj index dd1379a..5a3b084 100644 --- a/SteamWare.IO/SteamWare.IO.csproj +++ b/SteamWare.IO/SteamWare.IO.csproj @@ -56,10 +56,10 @@ ..\packages\MongoDB.Libmongocrypt.1.3.0\lib\netstandard2.0\MongoDB.Libmongocrypt.dll - ..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll - - ..\packages\NLog.4.7.15\lib\net45\NLog.dll + + ..\packages\NLog.5.2.4\lib\net46\NLog.dll ..\packages\Pipelines.Sockets.Unofficial.2.2.2\lib\net461\Pipelines.Sockets.Unofficial.dll diff --git a/SteamWare.IO/packages.config b/SteamWare.IO/packages.config index 73ce0ad..291d4ab 100644 --- a/SteamWare.IO/packages.config +++ b/SteamWare.IO/packages.config @@ -6,8 +6,8 @@ - - + + diff --git a/SteamWare.Logger/SteamWare.Logger.csproj b/SteamWare.Logger/SteamWare.Logger.csproj index a70aa53..60dccea 100644 --- a/SteamWare.Logger/SteamWare.Logger.csproj +++ b/SteamWare.Logger/SteamWare.Logger.csproj @@ -31,8 +31,8 @@ 4 - - ..\packages\NLog.4.7.15\lib\net45\NLog.dll + + ..\packages\NLog.5.2.4\lib\net46\NLog.dll diff --git a/SteamWare.Logger/packages.config b/SteamWare.Logger/packages.config index 5a5410a..dbdab5c 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/DataWrap.cs b/SteamWare/DataWrap.cs index 26b579f..8c244bf 100644 --- a/SteamWare/DataWrap.cs +++ b/SteamWare/DataWrap.cs @@ -96,6 +96,11 @@ namespace SteamWare /// public DataWrap() { + // fix log + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } // inizializzo i table adapters avvioTableAdaptersBase(); setupConnectionStringBase(); @@ -224,19 +229,18 @@ namespace SteamWare { // continuo Dictionary answ = new Dictionary(); + DataLayer_generic.VocabolarioDataTable vocData = new DataLayer_generic.VocabolarioDataTable(); if (taVocabolario == null) { - foreach (DataLayer_generic.VocabolarioRow riga in DW.taVocabolario.GetData()) - { - answ.Add(riga.Lingua.ToUpper() + "#" + riga.Lemma.ToUpper(), riga.Traduzione); - } + vocData = DW.taVocabolario.GetData(); } else { - foreach (DataLayer_generic.VocabolarioRow riga in taVocabolario.GetData()) - { - answ.Add(riga.Lingua.ToUpper() + "#" + riga.Lemma.ToUpper(), riga.Traduzione); - } + vocData = taVocabolario.GetData(); + } + foreach (DataLayer_generic.VocabolarioRow riga in vocData) + { + answ.Add(riga.Lingua.ToUpper() + "#" + riga.Lemma.ToUpper(), riga.Traduzione); } return answ; } @@ -247,6 +251,10 @@ namespace SteamWare protected virtual void setupConnectionStringBase() { string connStr = memLayer.ML.confReadString("VocabolarioConnectionString"); + if (string.IsNullOrEmpty(connStr)) + { + Log.Error($"ERRORE | DataWrap.setupConnectionStringBase | VocabolarioConnectionString EMPTY"); + } // connections del db vocabolario taLingue.Connection.ConnectionString = connStr; taVocabolario.Connection.ConnectionString = connStr; @@ -259,7 +267,15 @@ namespace SteamWare protected virtual void setupConnectionStringSpec() { string connStrUt = memLayer.ML.confReadString("UtenteCdcConnectionString"); + if (string.IsNullOrEmpty(connStrUt)) + { + Log.Error($"ERRORE | DataWrap.setupConnectionStringSpec | UtenteCdcConnectionString EMPTY"); + } string connStrPerm = memLayer.ML.confReadString("PermessiConnectionString"); + if (string.IsNullOrEmpty(connStrPerm)) + { + Log.Error($"ERRORE | DataWrap.setupConnectionStringSpec | PermessiConnectionString EMPTY"); + } // cambio le connString - db anagrafica principale taCdc.Connection.ConnectionString = connStrUt; taDiritti.Connection.ConnectionString = connStrUt; @@ -309,12 +325,13 @@ namespace SteamWare } } } - catch(Exception exc) + catch (Exception exc) { Log.Error($"Eccezione 01 durante setupVocabolario:{Environment.NewLine}{exc}"); dictVocabolario = new Dictionary(); } // scrivo quanti lemmi ha caricato! + Log.Info($"setupVocabolario | {source} | Caricati {dictVocabolario.Count} lemmi"); } diff --git a/SteamWare/SteamWare.csproj b/SteamWare/SteamWare.csproj index 70e7f10..32bd825 100644 --- a/SteamWare/SteamWare.csproj +++ b/SteamWare/SteamWare.csproj @@ -98,10 +98,10 @@ ..\packages\MongoDB.Libmongocrypt.1.3.0\lib\netstandard2.0\MongoDB.Libmongocrypt.dll - ..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll - - ..\packages\NLog.4.7.15\lib\net45\NLog.dll + + ..\packages\NLog.5.2.4\lib\net46\NLog.dll ..\packages\PDFsharp.1.50.5147\lib\net20\PdfSharp.dll @@ -118,8 +118,8 @@ ..\packages\StackExchange.Redis.2.5.61\lib\net461\StackExchange.Redis.dll - - ..\packages\SteamWare.Logger.5.2.2204.2910\lib\net462\SteamWare.Logger.dll + + ..\packages\SteamWare.Logger.5.3.2309.1309\lib\net462\SteamWare.Logger.dll ..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.dll diff --git a/SteamWare/app.config b/SteamWare/app.config index 03aec91..0095cd1 100644 --- a/SteamWare/app.config +++ b/SteamWare/app.config @@ -97,6 +97,10 @@ + + + + \ No newline at end of file diff --git a/SteamWare/packages.config b/SteamWare/packages.config index 220f4d9..51150d1 100644 --- a/SteamWare/packages.config +++ b/SteamWare/packages.config @@ -10,14 +10,14 @@ - - + + - + diff --git a/TestBench/App.config b/TestBench/App.config index f4a8f4d..4fd688b 100644 --- a/TestBench/App.config +++ b/TestBench/App.config @@ -14,7 +14,10 @@ - + + + + @@ -62,6 +65,10 @@ + + + + \ No newline at end of file diff --git a/TestBench/MainFOrm.Designer.cs b/TestBench/MainFOrm.Designer.cs index ba04413..4cac685 100644 --- a/TestBench/MainFOrm.Designer.cs +++ b/TestBench/MainFOrm.Designer.cs @@ -91,6 +91,7 @@ this.txtUser = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.tabPage8 = new System.Windows.Forms.TabPage(); + this.lblChannelLog = new System.Windows.Forms.Label(); this.btnStartSub = new System.Windows.Forms.Button(); this.txtMessaggio = new System.Windows.Forms.TextBox(); this.btnSendMessage = new System.Windows.Forms.Button(); @@ -98,7 +99,11 @@ this.label12 = new System.Windows.Forms.Label(); this.clockTimer = new System.Windows.Forms.Timer(this.components); this.LogTimer = new System.Windows.Forms.Timer(this.components); - this.lblChannelLog = new System.Windows.Forms.Label(); + this.tabPage9 = new System.Windows.Forms.TabPage(); + this.txtMatr = new System.Windows.Forms.TextBox(); + this.label13 = new System.Windows.Forms.Label(); + this.btnTestUserLoad = new System.Windows.Forms.Button(); + this.lblOutTestMatr = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); @@ -113,6 +118,7 @@ this.groupBox2.SuspendLayout(); this.tabPage7.SuspendLayout(); this.tabPage8.SuspendLayout(); + this.tabPage9.SuspendLayout(); this.SuspendLayout(); // // groupBox1 @@ -287,6 +293,7 @@ this.tabControl1.Controls.Add(this.tabPage6); this.tabControl1.Controls.Add(this.tabPage7); this.tabControl1.Controls.Add(this.tabPage8); + this.tabControl1.Controls.Add(this.tabPage9); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; @@ -300,7 +307,7 @@ this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); - this.tabPage1.Size = new System.Drawing.Size(768, 353); + this.tabPage1.Size = new System.Drawing.Size(768, 366); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "File IO test"; this.tabPage1.UseVisualStyleBackColor = true; @@ -313,7 +320,7 @@ this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); - this.tabPage2.Size = new System.Drawing.Size(768, 353); + this.tabPage2.Size = new System.Drawing.Size(768, 366); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "PDF test"; this.tabPage2.UseVisualStyleBackColor = true; @@ -330,7 +337,7 @@ this.tabPage3.Controls.Add(this.button2); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; - this.tabPage3.Size = new System.Drawing.Size(768, 353); + this.tabPage3.Size = new System.Drawing.Size(768, 366); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Redis test"; this.tabPage3.UseVisualStyleBackColor = true; @@ -402,7 +409,7 @@ this.tabPage4.Controls.Add(this.lblHwSwData); this.tabPage4.Location = new System.Drawing.Point(4, 22); this.tabPage4.Name = "tabPage4"; - this.tabPage4.Size = new System.Drawing.Size(768, 353); + this.tabPage4.Size = new System.Drawing.Size(768, 366); this.tabPage4.TabIndex = 3; this.tabPage4.Text = "Hw Sw pages"; this.tabPage4.UseVisualStyleBackColor = true; @@ -424,7 +431,7 @@ this.tabPage5.Margin = new System.Windows.Forms.Padding(2); this.tabPage5.Name = "tabPage5"; this.tabPage5.Padding = new System.Windows.Forms.Padding(2); - this.tabPage5.Size = new System.Drawing.Size(768, 353); + this.tabPage5.Size = new System.Drawing.Size(768, 366); this.tabPage5.TabIndex = 4; this.tabPage5.Text = "Scheduler"; this.tabPage5.UseVisualStyleBackColor = true; @@ -546,7 +553,7 @@ this.tabPage6.Location = new System.Drawing.Point(4, 22); this.tabPage6.Margin = new System.Windows.Forms.Padding(2); this.tabPage6.Name = "tabPage6"; - this.tabPage6.Size = new System.Drawing.Size(768, 353); + this.tabPage6.Size = new System.Drawing.Size(768, 366); this.tabPage6.TabIndex = 5; this.tabPage6.Text = "MessageQueue"; this.tabPage6.UseVisualStyleBackColor = true; @@ -691,7 +698,7 @@ this.tabPage7.Location = new System.Drawing.Point(4, 22); this.tabPage7.Name = "tabPage7"; this.tabPage7.Padding = new System.Windows.Forms.Padding(3); - this.tabPage7.Size = new System.Drawing.Size(768, 353); + this.tabPage7.Size = new System.Drawing.Size(768, 366); this.tabPage7.TabIndex = 6; this.tabPage7.Text = "Update Man"; this.tabPage7.UseVisualStyleBackColor = true; @@ -792,6 +799,19 @@ this.tabPage8.Text = "PubSub (REDIS)"; this.tabPage8.UseVisualStyleBackColor = true; // + // lblChannelLog + // + this.lblChannelLog.AutoSize = true; + this.lblChannelLog.BackColor = System.Drawing.Color.Black; + this.lblChannelLog.ForeColor = System.Drawing.Color.Yellow; + this.lblChannelLog.Location = new System.Drawing.Point(378, 65); + this.lblChannelLog.MaximumSize = new System.Drawing.Size(400, 300); + this.lblChannelLog.MinimumSize = new System.Drawing.Size(400, 300); + this.lblChannelLog.Name = "lblChannelLog"; + this.lblChannelLog.Size = new System.Drawing.Size(400, 300); + this.lblChannelLog.TabIndex = 9; + this.lblChannelLog.Text = "log"; + // // btnStartSub // this.btnStartSub.Location = new System.Drawing.Point(619, 12); @@ -850,18 +870,56 @@ this.LogTimer.Interval = 10; this.LogTimer.Tick += new System.EventHandler(this.LogTimer_Tick); // - // lblChannelLog + // tabPage9 // - this.lblChannelLog.AutoSize = true; - this.lblChannelLog.BackColor = System.Drawing.Color.Black; - this.lblChannelLog.ForeColor = System.Drawing.Color.Yellow; - this.lblChannelLog.Location = new System.Drawing.Point(378, 65); - this.lblChannelLog.MaximumSize = new System.Drawing.Size(400, 300); - this.lblChannelLog.MinimumSize = new System.Drawing.Size(400, 300); - this.lblChannelLog.Name = "lblChannelLog"; - this.lblChannelLog.Size = new System.Drawing.Size(400, 300); - this.lblChannelLog.TabIndex = 9; - this.lblChannelLog.Text = "log"; + this.tabPage9.Controls.Add(this.lblOutTestMatr); + this.tabPage9.Controls.Add(this.btnTestUserLoad); + this.tabPage9.Controls.Add(this.label13); + this.tabPage9.Controls.Add(this.txtMatr); + this.tabPage9.Location = new System.Drawing.Point(4, 22); + this.tabPage9.Name = "tabPage9"; + this.tabPage9.Padding = new System.Windows.Forms.Padding(3); + this.tabPage9.Size = new System.Drawing.Size(768, 366); + this.tabPage9.TabIndex = 8; + this.tabPage9.Text = "Test Vari"; + this.tabPage9.UseVisualStyleBackColor = true; + // + // txtMatr + // + this.txtMatr.Location = new System.Drawing.Point(41, 11); + this.txtMatr.Name = "txtMatr"; + this.txtMatr.Size = new System.Drawing.Size(69, 20); + this.txtMatr.TabIndex = 0; + this.txtMatr.Text = "102"; + this.txtMatr.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + // + // label13 + // + this.label13.AutoSize = true; + this.label13.Location = new System.Drawing.Point(8, 14); + this.label13.Name = "label13"; + this.label13.Size = new System.Drawing.Size(27, 13); + this.label13.TabIndex = 1; + this.label13.Text = "matr"; + // + // btnTestUserLoad + // + this.btnTestUserLoad.Location = new System.Drawing.Point(126, 11); + this.btnTestUserLoad.Name = "btnTestUserLoad"; + this.btnTestUserLoad.Size = new System.Drawing.Size(75, 23); + this.btnTestUserLoad.TabIndex = 2; + this.btnTestUserLoad.Text = "load user"; + this.btnTestUserLoad.UseVisualStyleBackColor = true; + this.btnTestUserLoad.Click += new System.EventHandler(this.btnTestUserLoad_Click); + // + // lblOutTestMatr + // + this.lblOutTestMatr.AutoSize = true; + this.lblOutTestMatr.Location = new System.Drawing.Point(218, 14); + this.lblOutTestMatr.Name = "lblOutTestMatr"; + this.lblOutTestMatr.Size = new System.Drawing.Size(16, 13); + this.lblOutTestMatr.TabIndex = 3; + this.lblOutTestMatr.Text = "---"; // // MainForm // @@ -898,6 +956,8 @@ this.tabPage7.PerformLayout(); this.tabPage8.ResumeLayout(false); this.tabPage8.PerformLayout(); + this.tabPage9.ResumeLayout(false); + this.tabPage9.PerformLayout(); this.ResumeLayout(false); } @@ -974,6 +1034,11 @@ private System.Windows.Forms.TextBox txtChannelName; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label lblChannelLog; + private System.Windows.Forms.TabPage tabPage9; + private System.Windows.Forms.Label lblOutTestMatr; + private System.Windows.Forms.Button btnTestUserLoad; + private System.Windows.Forms.Label label13; + private System.Windows.Forms.TextBox txtMatr; } } diff --git a/TestBench/MainFOrm.cs b/TestBench/MainFOrm.cs index fc1b4cb..d426a5f 100644 --- a/TestBench/MainFOrm.cs +++ b/TestBench/MainFOrm.cs @@ -7,6 +7,7 @@ using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using NLog; namespace TestBench { @@ -399,5 +400,27 @@ namespace TestBench } } } + + private void btnTestUserLoad_Click(object sender, EventArgs e) + { + // test lettura dati utente + try + { + var rigaUt = user_std.UtSn.rigaUtenteDaMatricola(txtMatr.Text.Trim()); + if (rigaUt != null) + { + lblOutTestMatr.Text = $"Test user | CN: {rigaUt.COGNOME} {rigaUt.NOME} | email: {rigaUt.EMAIL}"; + } + else + { + lblOutTestMatr.Text = "Errore!"; + } + } + catch (Exception exc) + { + Log.Error($"Test user_std fallito{Environment.NewLine}{exc}"); + } + } + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); } } \ No newline at end of file diff --git a/TestBench/NLog.config b/TestBench/NLog.config new file mode 100644 index 0000000..3461e58 --- /dev/null +++ b/TestBench/NLog.config @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/TestBench/TestBench.csproj b/TestBench/TestBench.csproj index acfcc32..f097c22 100644 --- a/TestBench/TestBench.csproj +++ b/TestBench/TestBench.csproj @@ -36,6 +36,9 @@ ..\packages\Microsoft.Bcl.AsyncInterfaces.6.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll + + ..\packages\NLog.5.2.4\lib\net46\NLog.dll + ..\packages\Pipelines.Sockets.Unofficial.2.2.2\lib\net472\Pipelines.Sockets.Unofficial.dll @@ -46,6 +49,7 @@ ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + ..\packages\System.Diagnostics.PerformanceCounter.6.0.1\lib\net461\System.Diagnostics.PerformanceCounter.dll @@ -68,12 +72,15 @@ ..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + ..\packages\System.Threading.Channels.6.0.0\lib\net461\System.Threading.Channels.dll ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + @@ -109,6 +116,7 @@ Always + SettingsSingleFileGenerator diff --git a/TestBench/packages.config b/TestBench/packages.config index 12abd3e..e15d762 100644 --- a/TestBench/packages.config +++ b/TestBench/packages.config @@ -1,6 +1,7 @@  + From 7602d1beaf29885be1c09c9a1978bb41742b7391 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Wed, 13 Sep 2023 11:24:51 +0200 Subject: [PATCH 4/6] Update log x authProxy --- SteamWare/authProxy.cs | 250 ++++++++++++++++++++++++----------------- 1 file changed, 144 insertions(+), 106 deletions(-) diff --git a/SteamWare/authProxy.cs b/SteamWare/authProxy.cs index a297518..2df20f2 100644 --- a/SteamWare/authProxy.cs +++ b/SteamWare/authProxy.cs @@ -1,4 +1,5 @@ -using System; +using NLog; +using System; namespace SteamWare { @@ -7,100 +8,22 @@ namespace SteamWare /// public class authProxy { - #region area table adapters + #region Public Fields - /// - /// The ta anag dev - /// - public DS_devicesTableAdapters.AnagDevicesTableAdapter taAnagDev; - - /// - /// init dei table adapters - /// - protected void initTA() - { - taAnagDev = new DS_devicesTableAdapters.AnagDevicesTableAdapter(); - } - /// - /// effettua setup dei connection strings da web.config della singola applicazione - /// - protected virtual void setupConnectionStringBase() - { - // connections del db - string connString = memLayer.ML.confReadString("DevicesConnectionString"); - taAnagDev.Connection.ConnectionString = connString; - } - - - #endregion - - /// - /// Initializes a new instance of the class. - /// - protected authProxy() - { - initTA(); - setupConnectionStringBase(); - } /// /// Singleton accesso a authProxy /// public static authProxy AP = new authProxy(); /// - /// Tenta autologin con autoriconoscimento Dominio/username by cookie + /// The ta anag dev /// - /// - /// - public static bool tryAuthByCookie(string cookieName) - { - logger.lg.scriviLog(String.Format(string.Format("Richiesta login da cookie {0}", cookieName)), tipoLog.INFO); - string devSecret = memLayer.ML.getCookieVal(cookieName); - bool answ = false; - DS_devices.AnagDevicesRow device = null; - if (devSecret != "" && devSecret != null) - { - // cerco il device...ogni dipendente può averne + di 1 registrato a suo nome... - string Dominio = ""; - string UsrName = ""; - try - { - device = DataWrap.DW.taAnagDev.getByDeviceSecret(devSecret)[0]; - Dominio = device.Dominio; - UsrName = device.User_Name; - } - catch (Exception exc) - { - logger.lg.scriviLog(String.Format("Errore recupero dati da devSecret {0}:{1}{2}", devSecret, Environment.NewLine, exc), tipoLog.ERROR); - } - if (Dominio != "" && UsrName != "") - { - answ = true; - try - { - // avvio l'utente (in sessione) - user_std.UtSn.startUpUtente(Dominio, UsrName); - logger.lg.scriviLog(String.Format("Effettuata login da cookie per l'utente {0}/{1}", Dominio, UsrName), tipoLog.INFO); - } - catch - { } - } - } - return answ; - } - /// - /// formatta il secret code - /// - /// - /// - /// - /// - /// - /// - public static string getSecret(string Dominio, string UsrName, int matrOpr, string DeviceName, DateTime adesso) - { - return string.Format("{0}|{1}|{2}|{3}|{4}", Dominio, UsrName, DeviceName, matrOpr, adesso); - } + public DS_devicesTableAdapters.AnagDevicesTableAdapter taAnagDev; + + #endregion Public Fields + + #region Public Methods + /// /// crea un nuovo record device e salva un nuovo cookie su db x il dispositivo e l'utente richiesti /// @@ -126,33 +49,31 @@ namespace SteamWare DataWrap.DW.taAnagDev.insertQuery(devSecret, Dominio, UsrName, matrOpr, DeviceName, Description, adesso, IPv4); // salvo il cookie nel browser memLayer.ML.setCookieVal(cookieName, devSecret, expDate); - logger.lg.scriviLog(String.Format("Salvato login da cookie per l'utente {0}/{1} - matr {2}", Dominio, UsrName, matrOpr), tipoLog.INFO); + Log.Info($"Salvato login da cookie per l'utente {Dominio}/{UsrName} | matr {matrOpr}"); // indico come fatto answ = true; } catch (Exception exc) { - logger.lg.scriviLog(string.Format("Errore in salvataggio cookie su db/dispositivo:{0}dominio:{1} | userName:{2} | matr:{6} | deviceName:{3} | ip:{4}{0}{5}", Environment.NewLine, Dominio, UsrName, DeviceName, IPv4, exc, matrOpr)); + Log.Error($"Errore in salvataggio cookie su db/dispositivo:{Environment.NewLine}dom/usr: {Dominio}/{UsrName} | matr:{matrOpr} | deviceName:{DeviceName} | ip:{IPv4}{Environment.NewLine}{exc}"); } return answ; } + /// - /// rimuove device da DB e toglie il cookie + /// formatta il secret code /// - /// secret associata al device + /// + /// + /// + /// + /// /// - public static bool removeDeviceByDevSec(string DeviceSecret) + public static string getSecret(string Dominio, string UsrName, int matrOpr, string DeviceName, DateTime adesso) { - bool answ = false; - try - { - DataWrap.DW.taAnagDev.delByDeviceSecret(DeviceSecret); - answ = true; - } - catch - { } - return answ; + return $"{Dominio}|{UsrName}|{DeviceName}|{matrOpr}|{adesso}"; } + /// /// rimuove device da DB e toglie il cookie /// @@ -166,10 +87,33 @@ namespace SteamWare DataWrap.DW.taAnagDev.delByDeviceName(DeviceName); answ = true; } - catch - { } + catch (Exception exc) + { + Log.Error($"Errore in removeDeviceByDevName:{Environment.NewLine}{exc}"); + } return answ; } + + /// + /// rimuove device da DB e toglie il cookie + /// + /// secret associata al device + /// + public static bool removeDeviceByDevSec(string DeviceSecret) + { + bool answ = false; + try + { + DataWrap.DW.taAnagDev.delByDeviceSecret(DeviceSecret); + answ = true; + } + catch (Exception exc) + { + Log.Error($"Errore in removeDeviceByDevSec:{Environment.NewLine}{exc}"); + } + return answ; + } + /// /// imuove device da DB e toglie il cookie /// @@ -184,9 +128,103 @@ namespace SteamWare DataWrap.DW.taAnagDev.delByDominioUser(Dominio, UsrName); answ = true; } - catch - { } + catch (Exception exc) + { + Log.Error($"Errore in removeDeviceByUserDominio:{Environment.NewLine}{exc}"); + } return answ; } + + /// + /// Tenta autologin con autoriconoscimento Dominio/username by cookie + /// + /// + /// + public static bool tryAuthByCookie(string cookieName) + { + Log.Info($"Richiesta login da cookie {cookieName}"); + string devSecret = memLayer.ML.getCookieVal(cookieName); + bool answ = false; + DS_devices.AnagDevicesRow device = null; + if (devSecret != "" && devSecret != null) + { + // cerco il device...ogni dipendente può averne + di 1 registrato a suo nome... + string Dominio = ""; + string UsrName = ""; + try + { + device = DataWrap.DW.taAnagDev.getByDeviceSecret(devSecret)[0]; + Dominio = device.Dominio; + UsrName = device.User_Name; + } + catch (Exception exc) + { + Log.Error($"tryAuthByCookie | Errore recupero dati da devSecret {devSecret}:{Environment.NewLine}{exc}"); + } + if (Dominio != "" && UsrName != "") + { + answ = true; + try + { + // avvio l'utente (in sessione) + user_std.UtSn.startUpUtente(Dominio, UsrName); + Log.Info($"Effettuata login da cookie per l'utente {Dominio}/{UsrName}"); + } + catch (Exception exc) + { + Log.Error($"tryAuthByCookie | Errore check dominio {Environment.NewLine}{exc}"); + } + } + } + return answ; + } + + #endregion Public Methods + + #region Protected Constructors + + /// + /// Initializes a new instance of the class. + /// + protected authProxy() + { + // fix log + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } + initTA(); + setupConnectionStringBase(); + } + + #endregion Protected Constructors + + #region Protected Methods + + /// + /// init dei table adapters + /// + protected void initTA() + { + taAnagDev = new DS_devicesTableAdapters.AnagDevicesTableAdapter(); + } + + /// + /// effettua setup dei connection strings da web.config della singola applicazione + /// + protected virtual void setupConnectionStringBase() + { + // connections del db + string connString = memLayer.ML.confReadString("DevicesConnectionString"); + taAnagDev.Connection.ConnectionString = connString; + } + + #endregion Protected Methods + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields } -} +} \ No newline at end of file From 4322801521014b584dc50c027978a29caaaba6d0 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Wed, 13 Sep 2023 16:04:34 +0200 Subject: [PATCH 5/6] continuo fix logging su steamwarelibs --- SteamWare/ApplicationSimplePage.cs | 97 +++++++++++++++---------- SteamWare/ApplicationUserControl.cs | 108 ++++++++++++++++++---------- SteamWare/DataWrap.cs | 2 - 3 files changed, 128 insertions(+), 79 deletions(-) diff --git a/SteamWare/ApplicationSimplePage.cs b/SteamWare/ApplicationSimplePage.cs index 0cb758f..910bcf6 100644 --- a/SteamWare/ApplicationSimplePage.cs +++ b/SteamWare/ApplicationSimplePage.cs @@ -1,3 +1,6 @@ +using NLog; +using System; + namespace SteamWare { /// @@ -5,43 +8,22 @@ namespace SteamWare /// public class ApplicationSimplePage : System.Web.UI.Page { + #region Public Constructors + /// /// Iniziazlizzazione void (non fa nulla) /// - protected ApplicationSimplePage() - { } - - #region area public - - #endregion - - #region flusso creazione pagina =c= - - /// - /// Metodo MAIN: viene eseguita al caricamento ed effettua delle routines per il controllo utente e istanzia l'oggetto memLayer - /// - /// - /// - protected virtual void Page_Load(object sender, System.EventArgs e) + public ApplicationSimplePage() { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } } + #endregion Public Constructors - #endregion - - #region utility =c= - - /// - /// rimanda alla pagina di Work In Progress salvando in session un titolo ed una descrizione che al pagina wip poi mostrerà all'utente - /// - /// titolo da mostrare nella pagina WIP - /// descrizione da mostrare nella pagina WIP - protected void paginaWIP(string titoloWIP, string descrizioneWIP) - { - Session["titoloWIP"] = titoloWIP; - Session["descrizioneWIP"] = descrizioneWIP; - Response.Redirect("WIP.aspx"); - } + #region Public Methods /// /// wrapper per log con salvataggio dell'IP del chiamante @@ -56,11 +38,14 @@ namespace SteamWare { postazione_IP = string.Format(" | {0} | ", Request.UserHostName); } - catch - { } - logger.lg.scriviLog(postazione_IP + _testoPre); + catch (Exception exc) + { + Log.Error($"Eccezione in httpLog01{Environment.NewLine}{exc}"); + } + Log.Info(postazione_IP + _testoPre); return answ; } + /// /// wrapper per log con salvataggio dell'IP del chiamante /// @@ -75,13 +60,47 @@ namespace SteamWare { postazione_IP = string.Format(" | {0} | ", Request.UserHostName); } - catch - { } - logger.lg.scriviLog(postazione_IP + testoLog, tipo); + catch (Exception exc) + { + Log.Error($"Eccezione in httpLog02{Environment.NewLine}{exc}"); + } + Log.Info(postazione_IP + testoLog, tipo); return answ; } - - #endregion + #endregion Public Methods + + #region Protected Methods + + /// + /// Metodo MAIN: viene eseguita al caricamento ed effettua delle routines per il controllo + /// utente e istanzia l'oggetto memLayer + /// + /// + /// + protected virtual void Page_Load(object sender, System.EventArgs e) + { + } + + /// + /// rimanda alla pagina di Work In Progress salvando in session un titolo ed una descrizione + /// che al pagina wip poi mostrerà all'utente + /// + /// titolo da mostrare nella pagina WIP + /// descrizione da mostrare nella pagina WIP + protected void paginaWIP(string titoloWIP, string descrizioneWIP) + { + Session["titoloWIP"] = titoloWIP; + Session["descrizioneWIP"] = descrizioneWIP; + Response.Redirect("WIP.aspx"); + } + + #endregion Protected Methods + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields } -} +} \ No newline at end of file diff --git a/SteamWare/ApplicationUserControl.cs b/SteamWare/ApplicationUserControl.cs index 94ebb32..05ea608 100644 --- a/SteamWare/ApplicationUserControl.cs +++ b/SteamWare/ApplicationUserControl.cs @@ -1,3 +1,4 @@ +using NLog; using System; using System.Collections.Generic; using System.Data; @@ -8,16 +9,17 @@ namespace SteamWare /// /// Base class for every user control in the application, containing some common behaviour and /// utility methods. It is not meant to be be used directly. - /// * Definizioni generali: - /// * SteamWare: codice scritto manualmente da SteamWare - /// * webForm: codice autogenerato da VisualStudio - /// * =c= : codice costante(non serve modifica) - /// * >c> : codice variabile(va modificato x ogni controllo / pagina) - /// - /// * Notazione - /// * _ : se posto all'inizio del nome indica una variabile/oggetto caricato in memoria da input pagina e/o session - /// * MAIUS : le procedure / metodi con prima lettera in MAIUSCOLO indicano codice COSTANTE - /// * minus : le procedure / metodi con prima lettera in minuscolo indicano codice variabile da verificare////modificare + /// * Definizioni generali: + /// * SteamWare: codice scritto manualmente da SteamWare + /// * webForm: codice autogenerato da VisualStudio + /// * =c= : codice costante(non serve modifica) + /// * >c> : codice variabile(va modificato x ogni controllo / pagina) + /// + /// * Notazione + /// * _ : se posto all'inizio del nome indica una variabile/oggetto caricato in memoria da input + /// pagina e/o session + /// * MAIUS : le procedure / metodi con prima lettera in MAIUSCOLO indicano codice COSTANTE + /// * minus : le procedure / metodi con prima lettera in minuscolo indicano codice variabile da verificare////modificare /// public class ApplicationUserControl : System.Web.UI.UserControl { @@ -41,7 +43,12 @@ namespace SteamWare /// tipo id controllo con classi di base comune da cui derivare gli *.asmx /// public ApplicationUserControl() - { } + { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } + } #endregion Public Constructors @@ -170,8 +177,10 @@ namespace SteamWare answ = righe.Length; } } - catch - { } + catch (Exception exc) + { + Log.Error($"Errore in setLogValueToSession:{Environment.NewLine}{exc}"); + } return answ; } @@ -203,8 +212,10 @@ namespace SteamWare string[] righe = confrontoValori.obj.valNew.Split('<'); answ = righe.Length; } - catch - { } + catch (Exception exc) + { + Log.Error($"Errore in setLogValueToSession4del:{Environment.NewLine}{exc}"); + } return answ; } @@ -241,8 +252,9 @@ namespace SteamWare string data = val.ToString(); dataFormattata = data.Substring(0, 4) + "-" + data.Substring(4, 2) + "-" + data.Substring(6, 2); } - catch + catch (Exception exc) { + Log.Error($"Errore in data2IsoString:{Environment.NewLine}{exc}"); } return dataFormattata; } @@ -260,8 +272,9 @@ namespace SteamWare string data = val.ToString(); dataFormattata = data.Substring(6, 2) + "/" + data.Substring(4, 2) + "/" + data.Substring(0, 4); } - catch + catch (Exception exc) { + Log.Error($"Errore in data2string:{Environment.NewLine}{exc}"); } return dataFormattata; } @@ -307,8 +320,10 @@ namespace SteamWare { label = (DataWrap.DW.taCdc.getByCdc(val.ToString())[0]).DESCRIZIONE; } - catch - { } + catch (Exception exc) + { + Log.Error($"Errore in descrCdcDaId:{Environment.NewLine}{exc}"); + } return label; } @@ -325,9 +340,11 @@ namespace SteamWare { postazione_IP = string.Format(" | {0} | ", Request.UserHostName); } - catch - { } - logger.lg.scriviLog(postazione_IP + _testoPre); + catch (Exception exc) + { + Log.Error($"Errore in httpLog01:{Environment.NewLine}{exc}"); + } + Log.Info(postazione_IP + _testoPre); return answ; } @@ -345,9 +362,11 @@ namespace SteamWare { postazione_IP = string.Format(" | {0} | ", Request.UserHostName); } - catch - { } - logger.lg.scriviLog(postazione_IP + testoLog, tipo); + catch (Exception exc) + { + Log.Error($"Errore in httpLog02:{Environment.NewLine}{exc}"); + } + Log.Info(postazione_IP + testoLog, tipo); return answ; } @@ -576,7 +595,7 @@ namespace SteamWare } /// - /// calcola come percentuale la radio dividendo/divisore + /// calcola come percentuale la ratio dividendo/divisore /// /// /// @@ -588,10 +607,12 @@ namespace SteamWare double _divisore = Convert.ToDouble(divisore); try { - answ = string.Format("{0:p}", _dividendo / _divisore); + answ = $"{_dividendo / _divisore:p}"; + } + catch (Exception exc) + { + Log.Error($"Errore in percentuale:{Environment.NewLine}{exc}"); } - catch - { } return answ; } @@ -645,8 +666,10 @@ namespace SteamWare DataLayer_AnagGen.UTENTERow riga = DataWrap.DW.taUtente.getByUserName(utenteWin)[0]; sigla = riga.SIGLA; } - catch - { } + catch (Exception exc) + { + Log.Error($"Errore in siglaDaUserWin:{Environment.NewLine}{exc}"); + } return sigla; } @@ -819,7 +842,7 @@ namespace SteamWare int filtLenght = filtroCompleto.Length; int currLenght = 0; // workaround: separo la ricerca in + tranches, andando a prendere solo (circa) 2000 - // char alla volta... + // char alla volta... if (filtroCompleto.Length < 2000) { // uso il filtro completo... @@ -1040,9 +1063,10 @@ namespace SteamWare _dataFrom = "01/01/1900"; } } - catch + catch (Exception exc) { _dataFrom = "01/01/1900"; + Log.Error($"Errore in dataFilter / conv _dataFrom:{Environment.NewLine}{exc}"); } try { @@ -1052,9 +1076,10 @@ namespace SteamWare _dataTo = "01/01/2200"; } } - catch + catch (Exception exc) { _dataTo = "01/01/2200"; + Log.Error($"Errore in dataFilter / conv _dataTo:{Environment.NewLine}{exc}"); } switch (_tipoPeriodo) { @@ -1096,9 +1121,10 @@ namespace SteamWare _data = "01/01/1900"; } } - catch + catch (Exception exc) { _data = "01/01/1900"; + Log.Error($"Errore in dataFilter / conv _data:{Environment.NewLine}{exc}"); } switch (_tipoPeriodo) { @@ -1153,7 +1179,7 @@ namespace SteamWare DataLayer_AnagGen.CDCDataTable tblCdc = DataWrap.DW.taCdc.GetTopCdC(user_std.UtSn.utente, user_std.UtSn.dominio, user_std.UtSn.modulo); if (tblCdc.Rows.Count == 0 && _safePages.IndexOf(_paginaCorrente) == -1) { - logger.lg.scriviLog(string.Format("Errore in filtroPosizioneCdC: utente {0} non autorizzato per la pagina {1}", user_std.UtSn.utente, _paginaCorrente), tipoLog.STARTUP); + Log.Info(string.Format("Errore in filtroPosizioneCdC: utente {0} non autorizzato per la pagina {1}", user_std.UtSn.utente, _paginaCorrente), tipoLog.STARTUP); Response.Redirect("~/unauthorized.aspx"); } foreach (DataLayer_AnagGen.CDCRow riga in tblCdc) @@ -1347,7 +1373,7 @@ namespace SteamWare /// /// MAIN: esecuzione al caricamento del modulo delle routines di controllo utente e - /// creazione pagina + /// creazione pagina /// /// /// @@ -1427,7 +1453,7 @@ namespace SteamWare // una common page... if (!user_std.UtSn.isPageEnabled(_paginaCorrente) && _commonPages.IndexOf(_paginaCorrente) == -1) { - logger.lg.scriviLog(string.Format("Errore in SetUpByUserRight: utente {0} non autorizzato per la pagina {1}", user_std.UtSn.utente, _paginaCorrente), tipoLog.STARTUP); + Log.Info(string.Format("Errore in SetUpByUserRight: utente {0} non autorizzato per la pagina {1}", user_std.UtSn.utente, _paginaCorrente), tipoLog.STARTUP); Response.Redirect("~/unauthorized.aspx"); } } @@ -1467,6 +1493,12 @@ namespace SteamWare #endregion Protected Methods + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields + #region Private Methods /// diff --git a/SteamWare/DataWrap.cs b/SteamWare/DataWrap.cs index 8c244bf..03e6fb9 100644 --- a/SteamWare/DataWrap.cs +++ b/SteamWare/DataWrap.cs @@ -96,7 +96,6 @@ namespace SteamWare /// public DataWrap() { - // fix log if (Log == null) { Log = LogManager.GetCurrentClassLogger(); @@ -331,7 +330,6 @@ namespace SteamWare dictVocabolario = new Dictionary(); } // scrivo quanti lemmi ha caricato! - Log.Info($"setupVocabolario | {source} | Caricati {dictVocabolario.Count} lemmi"); } From 4cc7af22c2c8731e29e0ce4fe521c7d6f9eb8650 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Wed, 13 Sep 2023 16:53:47 +0200 Subject: [PATCH 6/6] Completo rimozione dipendenze logging x steamwarelib --- SteamWare.IO/Redis.cs | 1885 ++++++------ SteamWare.IO/fileMover.cs | 2536 +++++++++-------- SteamWare.IO/memLayer.cs | 71 +- SteamWare/App_Readme/README_SteamWare.txt | 12 - .../SteamWare_demo/example-favicon.ico | Bin 31702 -> 0 bytes SteamWare/HwSwInfo.cs | 114 +- SteamWare/SteamWare.csproj | 5 - SteamWare/UpdateMan.cs | 71 +- SteamWare/UserControl.cs | 759 ++--- SteamWare/dbUpdateManager.cs | 125 +- SteamWare/devicesAuthProxy.cs | 2224 ++++++++------- SteamWare/fileMover.cs | 1912 +++++++------ SteamWare/licenseMan.cs | 188 +- SteamWare/packages.config | 1 - SteamWare/utils.cs | 618 ++-- 15 files changed, 5437 insertions(+), 5084 deletions(-) delete mode 100644 SteamWare/App_Readme/README_SteamWare.txt delete mode 100644 SteamWare/App_Readme/SteamWare_demo/example-favicon.ico diff --git a/SteamWare.IO/Redis.cs b/SteamWare.IO/Redis.cs index c18b6d5..9b70774 100644 --- a/SteamWare.IO/Redis.cs +++ b/SteamWare.IO/Redis.cs @@ -1,4 +1,6 @@ using Newtonsoft.Json; +using NLog; +using NLog.Fluent; using StackExchange.Redis; using SteamWare.Logger; using System; @@ -9,983 +11,1008 @@ using System.Threading.Tasks; namespace SteamWare.IO { - public class Redis - { - #region base objects - - /// - /// Oggetto currentDb locale - /// - private IDatabase _currDB { get; set; } - - /// - /// Oggetto DB REDIS corrente - /// - public IDatabase cache + public class Redis { - get - { - IDatabase answ; - // se già valorizzato uso oggetto private... - if (_currDB != null) + #region Public Constructors + + public Redis() { - answ = _currDB; + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } } - else + + #endregion Public Constructors + + #region Public Enums + + /// + /// Tipologia di ordinamento x liste KVP + /// + public enum kvpOrderBy { - // init DB (sullo 0) - answ = connRedis.GetDatabase(); - // gestione override... - if (memLayer.ML.confReadInt("redisDb") >= 0) - { - // in questo caso uso il DB configurato in app.config... - answ = connRedis.GetDatabase(memLayer.ML.confReadInt("redisDb")); - } - _currDB = answ; + /// + /// Ordinamento ASCending per KEY + /// + KeyAsc, + + /// + /// Ordinamento DESCending per KEY + /// + KeyDesc, + + /// + /// Ordinamento ASCending per VAL + /// + ValAsc, + + /// + /// Ordinamento DESCending per VAL + /// + ValDesc } - // restituisco oggetto DB - return answ; - } - } - /// - /// Oggetto per sottoscrizione Pub/Sub Redis - /// - public ISubscriber RedPubSub - { - get - { - return connRedis.GetSubscriber(); - } - } + #endregion Public Enums - /// - /// Connessione lazy a redis... - /// - private Lazy lazyConnection = new Lazy(() => - { - string RedisConn = memLayer.ML.confReadString("RedisConn"); - if (string.IsNullOrEmpty(RedisConn)) - { - RedisConn = "localhost,abortConnect=false,ssl=false"; - } + #region Public Properties - return ConnectionMultiplexer.Connect(RedisConn); - }); - - /// - /// Connessione lazy a redis... - /// - private Lazy lazyConnectionAdmin = new Lazy(() => - { - string RedisConnAdmin = memLayer.ML.confReadString("RedisConnAdmin"); - if (string.IsNullOrEmpty(RedisConnAdmin)) - { - RedisConnAdmin = "localhost,abortConnect=false,ssl=false,allowAdmin=true"; - } - - return ConnectionMultiplexer.Connect(RedisConnAdmin); - }); - - /// - /// Oggetto statico connessione redis - /// - public ConnectionMultiplexer connRedis - { - get - { - return lazyConnection.Value; - } - } - - /// - /// Oggetto statico connessione redis - /// - public ConnectionMultiplexer connRedisAdmin - { - get - { - return lazyConnectionAdmin.Value; - } - } - - #endregion base objects - - #region Helpers - - /// - /// Nome della variabile HASH da utilizzare (dato CodModulo / Server / DB impiegato da funzionalita' DbConfig) + keyName richiesto... - /// - public string redHash(string keyName) - { - string answ = keyName; - try - { - answ = string.Format("{0}:{1}:{2}:{3}", memLayer.ML.confReadString("CodModulo"), memLayer.ML.taConfig.Connection.DataSource, memLayer.ML.taConfig.Connection.Database, keyName).Replace("\\", "_"); - } - catch - { } - return answ; - } - - /// - /// Serializzazione di un oggetto generico - /// - /// - /// - public string serializeVal(object origVal) - { - string answ = ""; - try - { - answ = JsonConvert.SerializeObject(origVal); - } - catch { } - return answ; - } - - /// - /// Deserializzazione di un valore string in oggetto generico - /// - /// - /// - public object deserializeVal(string serVal) - { - object answ = ""; - try - { - answ = JsonConvert.DeserializeObject(serVal); - } - catch { } - return answ; - } - - /// - /// Restituisce un pò di info sul server redis connesso - /// - /// - public string getRedisInfoData() - { - string answ = ""; - StringBuilder sb = new StringBuilder(); - try - { - sb.AppendLine($"Configuration: {connRedis.Configuration}"); - sb.AppendLine($"Connected: {connRedis.IsConnected}"); - sb.AppendLine($"ClientName: {connRedis.ClientName}"); - sb.AppendLine($"Total Ops: {connRedis.OperationCount}"); - sb.AppendLine($"Status: {connRedis.GetStatus()}"); - answ = sb.ToString(); - } - catch - { } - return answ; - } - - /// - /// Restituisce info dei server connessi... - /// - /// - public IServer[] redServInfo() - { - IServer[] answ = new IServer[1]; - try - { - answ = new IServer[connRedisAdmin.GetEndPoints().Length]; - int i = 0; - foreach (var ep in connRedisAdmin.GetEndPoints()) + /// + /// Oggetto DB REDIS corrente + /// + public IDatabase cache { - var server = connRedisAdmin.GetServer(ep); - answ[i] = server; - i++; + get + { + IDatabase answ; + // se già valorizzato uso oggetto private... + if (_currDB != null) + { + answ = _currDB; + } + else + { + // init DB (sullo 0) + answ = connRedis.GetDatabase(); + // gestione override... + if (memLayer.ML.confReadInt("redisDb") >= 0) + { + // in questo caso uso il DB configurato in app.config... + answ = connRedis.GetDatabase(memLayer.ML.confReadInt("redisDb")); + } + _currDB = answ; + } + // restituisco oggetto DB + return answ; + } } - } - catch (Exception exc) - { - Logging.Instance.Error($"redServInfo:{Environment.NewLine}{exc}"); - } - return answ; - } - #endregion Helpers - - #region gestione valori in RedisCache - - /// - /// Restituisce una chiave salvata in RedisCache - /// - /// - /// - public string getRSV(string chiave) - { - string answ = ""; - try - { - answ = cache.StringGet(chiave); - } - catch (Exception exc) - { - //logger.lg.scriviLog(string.Format("Errore in getRSV:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - - /// - /// Salva una chiave in RedisCache - /// - /// - /// - /// - public bool setRSV(string chiave, string valore) - { - bool answ = false; - try - { - cache.StringSet(chiave, valore); - answ = true; - } - catch (Exception exc) - { - Logging.Instance.Error(string.Format("Eccezzione in setRSV:{0}{1}", Environment.NewLine, exc)); - } - return answ; - } - - /// - /// Salva una chiave in RedisCache - /// - /// - /// - /// in secondi - /// - public bool setRSV(string chiave, string valore, int TTL_sec) - { - bool answ = false; - try - { - TimeSpan expT = new TimeSpan(0, 0, TTL_sec); - // salvo con expyry... - cache.StringSet(chiave, valore, expT); - answ = true; - } - catch (Exception exc) - { - Logging.Instance.Error(string.Format("Eccezzione in setRSV:{0}{1}", Environment.NewLine, exc)); - } - return answ; - } - - /// - /// Incrementa un contatore in Redis - /// - /// - /// - public long setRCntI(string chiave) - { - long answ = 0; - try - { - answ = cache.StringIncrement(chiave, 1); - } - catch (Exception exc) - { - Logging.Instance.Error(string.Format("Eccezzione in setRCI:{0}{1}", Environment.NewLine, exc)); - } - return answ; - } - - /// - /// Decrementa un contatore in Redis - /// - /// - /// - public long setRCntD(string chiave) - { - long answ = 0; - try - { - answ = cache.StringDecrement(chiave, 1); - } - catch (Exception exc) - { - Logging.Instance.Error(string.Format("Eccezzione in setRCD:{0}{1}", Environment.NewLine, exc)); - } - return answ; - } - - /// - /// Restituisce una chiave COUNTER in RedisCache - /// - /// - /// - public int getRCnt(string chiave) - { - int answInt = 0; - string answ = ""; - try - { - answ = cache.StringGet(chiave); - answInt = Convert.ToInt32(answ); - } - catch (Exception exc) - { - Logging.Instance.Error(string.Format("Eccezione in getRSV:{0}{1}", Environment.NewLine, exc)); - } - return answInt; - } - - /// - /// Resetta (elimina) un contatore in Redis - /// - /// - /// - public bool resetRCnt(string chiave) - { - bool answ = false; - try - { - answ = cache.KeyDelete(chiave); - } - catch (Exception exc) - { - Logging.Instance.Error(string.Format("Eccezione in resetRCnt:{0}{1}", Environment.NewLine, exc)); - } - return answ; - } - - /// - /// Restituisce un set KVP (Key Value Pair) salvati in RedisCache - /// - /// - /// - public RedisValue[] getRKeys(RedisKey[] chiavi) - { - RedisValue[] answ = null; - try - { - answ = cache.StringGet(chiavi); - } - catch (Exception exc) - { - Logging.Instance.Error(string.Format("Eccezione in getRKeys:{0}{1}", Environment.NewLine, exc)); - } - return answ; - } - - /// - /// Salva un set KVP (Key Value Pair) in RedisCache - /// - /// Set KVP chiave-valore da salvare - /// - public bool setRKeys(KeyValuePair[] valori) - { - bool answ = false; - try - { - cache.StringSet(valori); - answ = true; - } - catch (Exception exc) - { - Logging.Instance.Error(string.Format("Eccezione in setRKeys:{0}{1}", Environment.NewLine, exc)); - } - return answ; - } - - /// - /// Verifica se ci siano valori nella KEY indicata... - /// - /// - /// - public bool redKeyPresent(RedisKey key) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - answ = cache.KeyExists(key); - } - catch (Exception exc) - { - Logging.Instance.Error(string.Format("Eccezione in redKeyPresent per la key {2}:{0}{1}", Environment.NewLine, exc, key)); - } - return answ; - } - - /// - /// Verifica se ci siano valori nella KEY indicata (string) - /// - /// - /// - public bool redKeyPresentSz(string key) - { - bool answ = false; - try - { - RedisKey chiave = key; - answ = redKeyPresent(chiave); - } - catch - { } - return answ; - } - - /// - /// Verifica se ci siano valori nella hash indicata... - /// - /// - /// - public bool redHashPresent(RedisKey key) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - answ = cache.HashGetAll(key).Length > 0; - } - catch (Exception exc) - { - Logging.Instance.Error(string.Format("Eccezione in redHashPresent per la key {2}{0}{1}", Environment.NewLine, exc, key)); - } - return answ; - } - - /// - /// Verifica se ci siano valori nella hash indicata (string) - /// - /// - /// - public bool redHashPresentSz(string key) - { - bool answ = false; - try - { - RedisKey chiave = key; - answ = redHashPresent(chiave); - } - catch - { } - return answ; - } - - /// - /// Recupera tutti i valori dalla hash - /// - /// - /// - public KeyValuePair[] redGetHash(string hashKey) - { - KeyValuePair[] answ = new KeyValuePair[1]; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - HashEntry[] valori = cache.HashGetAll(chiave); - answ = new KeyValuePair[valori.Length]; - int i = 0; - foreach (HashEntry item in valori) + /// + /// Oggetto statico connessione redis + /// + public ConnectionMultiplexer connRedis { - answ[i] = new KeyValuePair(item.Name, item.Value); - i++; + get + { + return lazyConnection.Value; + } } - } - catch - { } - return answ; - } - /// - /// Recupera tutti i valori dalla hash in formato Dictionary - /// - /// - /// - public Dictionary redGetHashDict(string hashKey) - { - Dictionary answ = new Dictionary(); - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - HashEntry[] valori = cache.HashGetAll(chiave); - foreach (HashEntry item in valori) + /// + /// Oggetto statico connessione redis + /// + public ConnectionMultiplexer connRedisAdmin { - answ.Add(item.Name, item.Value); + get + { + return lazyConnectionAdmin.Value; + } } - } - catch - { } - return answ; - } - /// - /// Recupera UN SINGOLO VALORE dalla hash per un dato field - /// - /// - /// - /// - public string redGetHashField(string hashKey, string hashField) - { - string answ = ""; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - RedisValue campo = hashField; - RedisValue valOut = cache.HashGet(chiave, campo); - answ = valOut.ToString(); - } - catch - { } - return answ; - } - - /// - /// Salvataggio di una hash di valori - /// - /// chiave - /// valori - /// - public bool redSaveHash(string hashKey, KeyValuePair[] hashFields) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - HashEntry[] valori = new HashEntry[hashFields.Length]; - int i = 0; - foreach (KeyValuePair kvp in hashFields) + /// + /// Restituisce numero record in Redis DB + /// + public long numRecRedis { - valori[i] = new HashEntry(kvp.Key, kvp.Value); - i++; + get + { + long answ = 0; + try + { + foreach (var ep in connRedis.GetEndPoints()) + { + var server = connRedis.GetServer(ep); + answ += server.DatabaseSize(); + } + } + catch + { } + return answ; + } } - cache.HashSet(chiave, valori); - answ = true; - } - catch - { } - return answ; - } - /// - /// Salvataggio di una hash di valori in formato Dictionary - /// - /// chiave - /// valori - /// - public bool redSaveHashDict(string hashKey, Dictionary hashFields) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - HashEntry[] valori = new HashEntry[hashFields.Count]; - int i = 0; - foreach (KeyValuePair kvp in hashFields) + /// + /// Oggetto per sottoscrizione Pub/Sub Redis + /// + public ISubscriber RedPubSub { - valori[i] = new HashEntry(kvp.Key, kvp.Value); - i++; + get + { + return connRedis.GetSubscriber(); + } } - cache.HashSet(chiave, valori); - answ = true; - } - catch - { } - return answ; - } - /// - /// Salvataggio di una hash di valori - /// - /// chiave - /// valori come lista KVP - /// - public bool redSaveHashList(string hashKey, List> hashListKVP) - { - bool answ = false; - if (connRedis.IsConnected) - { - // cerco se ci sia valore in redis... - IDatabase cache = connRedis.GetDatabase(); - try + #endregion Public Properties + + #region Public Methods + + /// + /// Effettua comaprazione x VALORE in KVP ASC + /// + /// + /// + /// + public int CompareVal(KeyValuePair x, KeyValuePair y) { - RedisKey chiave = hashKey; - HashEntry[] valori = new HashEntry[hashListKVP.Count]; - int i = 0; - foreach (KeyValuePair kvp in hashListKVP) - { - valori[i] = new HashEntry(kvp.Key, kvp.Value); - i++; - } - cache.HashSet(chiave, valori); - answ = true; + return x.Value.CompareTo(y.Value); } - catch - { } - } - return answ; - } - /// - /// Salvataggio di una hash di valori - /// - /// chiave - /// valori - /// scadenza preimpostata hash (secondi) | defaoult = -1 (non scade) - /// - public bool redSaveHash(string hashKey, KeyValuePair[] hashFields, double expireSeconds = -1) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - answ = redSaveHash(hashKey, hashFields); - if (expireSeconds > 0) + /// + /// Effettua comaprazione x VALORE in KVP DESC + /// + /// + /// + /// + public int CompareValDesc(KeyValuePair x, KeyValuePair y) { - cache.KeyExpire(chiave, DateTime.Now.AddSeconds(expireSeconds)); + return y.Value.CompareTo(x.Value); } - //answ = true; - } - catch - { } - return answ; - } - /// - /// Salvataggio di una hash di valori in formato Dictionary - /// - /// chiave - /// valori - /// scadenza preimpostata hash (secondi) | defaoult = -1 (non scade) - /// - public bool redSaveHashDict(string hashKey, Dictionary hashFields, double expireSeconds = -1) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = hashKey; - answ = redSaveHashDict(hashKey, hashFields); - if (expireSeconds > 0) + /// + /// Deserializzazione di un valore string in oggetto generico + /// + /// + /// + public object deserializeVal(string serVal) { - cache.KeyExpire(chiave, DateTime.Now.AddSeconds(expireSeconds)); + object answ = ""; + try + { + answ = JsonConvert.DeserializeObject(serVal); + } + catch { } + return answ; } - //answ = true; - } - catch - { } - return answ; - } - /// - /// Elimina una key (hash, string) - /// - /// - /// - public bool redDelKey(string key) - { - bool answ = false; - // cerco se ci sia valore in redis... - try - { - RedisKey chiave = key; - cache.KeyDelete(chiave); - answ = true; - } - catch - { } - return answ; - } - - /// - /// Flush completo cache redis - /// - /// ** = tutti - /// - public bool redFlushKey(string keyPattern) - { - bool answ = false; - // cerco se ci sia valore in redis... - // se vuoto = ALL... - keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; - try - { - foreach (var ep in connRedis.GetEndPoints()) + /// + /// Restituisce una chiave COUNTER in RedisCache + /// + /// + /// + public int getRCnt(string chiave) { - var server = connRedis.GetServer(ep); - var keys = server.Keys(database: memLayer.ML.confReadInt("redisDb"), pattern: $"{keyPattern}*"); - foreach (var key in keys) - { - cache.KeyDelete(key); - } + int answInt = 0; + string answ = ""; + try + { + answ = cache.StringGet(chiave); + answInt = Convert.ToInt32(answ); + } + catch (Exception exc) + { + Log.Error(string.Format("Eccezione in getRSV:{0}{1}", Environment.NewLine, exc)); + } + return answInt; } - answ = true; - } - catch (Exception exc) - { - Logging.Instance.Error($"Eccezione in redFlushKey{Environment.NewLine}{exc}"); - } - return answ; - } - /// - /// Conta num oggetti cache redis che rispondono a pattern - /// - /// ** = tutti - /// - public int redCountKey(string keyPattern) - { - int answ = 0; - // cerco se ci sia valore in redis... - // se vuoto = ALL... - keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; - try - { - foreach (var ep in connRedis.GetEndPoints()) + /// + /// Restituisce un pò di info sul server redis connesso + /// + /// + public string getRedisInfoData() { - var server = connRedis.GetServer(ep); - foreach (var key in server.Keys(pattern: keyPattern)) - { - answ++; - } + string answ = ""; + StringBuilder sb = new StringBuilder(); + try + { + sb.AppendLine($"Configuration: {connRedis.Configuration}"); + sb.AppendLine($"Connected: {connRedis.IsConnected}"); + sb.AppendLine($"ClientName: {connRedis.ClientName}"); + sb.AppendLine($"Total Ops: {connRedis.OperationCount}"); + sb.AppendLine($"Status: {connRedis.GetStatus()}"); + answ = sb.ToString(); + } + catch + { } + return answ; } - } - catch (Exception exc) - { - Logging.Instance.Error($"Eccezione in redCountKey:{Environment.NewLine}{exc}"); - } - return answ; - } - /// - /// Restituisce numero record in Redis DB - /// - public long numRecRedis - { - get - { - long answ = 0; - try + /// + /// Restituisce un set KVP (Key Value Pair) salvati in RedisCache + /// + /// + /// + public RedisValue[] getRKeys(RedisKey[] chiavi) { - foreach (var ep in connRedis.GetEndPoints()) - { - var server = connRedis.GetServer(ep); - answ += server.DatabaseSize(); - } + RedisValue[] answ = null; + try + { + answ = cache.StringGet(chiavi); + } + catch (Exception exc) + { + Log.Error(string.Format("Eccezione in getRKeys:{0}{1}", Environment.NewLine, exc)); + } + return answ; } - catch - { } - return answ; - } - } - /// - /// Restituisce oggetti cache redis che rispondono a pattern - /// - /// ** = tutti - /// Tipo di ordinamento per kvp - /// - public List> redGetCounterByKey(string keyPattern, kvpOrderBy orderBy) - { - int numAnsw = redCountKey(keyPattern); - RedisKey[] chiavi = new RedisKey[numAnsw]; - List> answ = new List>(); - // se vuoto = ALL... - keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; - - // recupero in primis elenco chiavi - try - { - int i = 0; - foreach (var ep in connRedis.GetEndPoints()) + /// + /// Restituisce una chiave salvata in RedisCache + /// + /// + /// + public string getRSV(string chiave) { - var server = connRedis.GetServer(ep); - foreach (var key in server.Keys(pattern: keyPattern)) - { - chiavi[i] = key; - i++; - } + string answ = ""; + try + { + answ = cache.StringGet(chiave); + } + catch (Exception exc) + { + Log.Error($"Eccezione getRSV{Environment.NewLine}{exc}"); + } + return answ; } - } - catch (Exception exc) - { - Logging.Instance.Error($"Eccezione in redGetCounterByKey{Environment.NewLine}{exc}"); - } - // ora recupero valori! - var valori = getRKeys(chiavi); - int currVal = 0; - // popolo rispsota - try - { - for (int i = 0; i < numAnsw; i++) + + /// + /// Lunghezza List + /// + /// + /// + public long ListLen(string queueName) { - Int32.TryParse(valori[i], out currVal); - answ.Add(new KeyValuePair(chiavi[i], currVal)); + return connRedis.GetDatabase().ListLength((RedisKey)queueName); } - } - catch - { } - // se richiesto riordino... - switch (orderBy) - { - case kvpOrderBy.KeyAsc: - answ.Sort(CompareKey); - break; - case kvpOrderBy.KeyDesc: - answ.Sort(CompareKeyDesc); - break; + /// + /// Recupera valore da List (F.I.F.O.) + /// + /// + /// + public string ListPop(string queueName) + { + return connRedis.GetDatabase().ListLeftPop((RedisKey)queueName).ToString(); + } - case kvpOrderBy.ValAsc: - answ.Sort(CompareVal); - break; + /// + /// Mette un valore in List (F.I.F.O.) + /// + /// + /// + public void ListPush(string queueName, string value) + { + connRedis.GetDatabase().ListRightPush((RedisKey)queueName, (RedisValue)value); + } - case kvpOrderBy.ValDesc: - answ.Sort(CompareValDesc); - break; + /// + /// Conta num oggetti cache redis che rispondono a pattern + /// + /// ** = tutti + /// + public int redCountKey(string keyPattern) + { + int answ = 0; + // cerco se ci sia valore in redis... se vuoto = ALL... + keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; + try + { + foreach (var ep in connRedis.GetEndPoints()) + { + var server = connRedis.GetServer(ep); + foreach (var key in server.Keys(pattern: keyPattern)) + { + answ++; + } + } + } + catch (Exception exc) + { + Log.Error($"Eccezione in redCountKey:{Environment.NewLine}{exc}"); + } + return answ; + } - default: - break; - } - return answ; + /// + /// Elimina una key (hash, string) + /// + /// + /// + public bool redDelKey(string key) + { + bool answ = false; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = key; + cache.KeyDelete(chiave); + answ = true; + } + catch + { } + return answ; + } + + /// + /// Flush completo cache redis + /// + /// ** = tutti + /// + public bool redFlushKey(string keyPattern) + { + bool answ = false; + // cerco se ci sia valore in redis... se vuoto = ALL... + keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; + try + { + foreach (var ep in connRedis.GetEndPoints()) + { + var server = connRedis.GetServer(ep); + var keys = server.Keys(database: memLayer.ML.confReadInt("redisDb"), pattern: $"{keyPattern}*"); + foreach (var key in keys) + { + cache.KeyDelete(key); + } + } + answ = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione in redFlushKey{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// Restituisce oggetti cache redis che rispondono a pattern + /// + /// ** = tutti + /// Tipo di ordinamento per kvp + /// + public List> redGetCounterByKey(string keyPattern, kvpOrderBy orderBy) + { + int numAnsw = redCountKey(keyPattern); + RedisKey[] chiavi = new RedisKey[numAnsw]; + List> answ = new List>(); + // se vuoto = ALL... + keyPattern = string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern; + + // recupero in primis elenco chiavi + try + { + int i = 0; + foreach (var ep in connRedis.GetEndPoints()) + { + var server = connRedis.GetServer(ep); + foreach (var key in server.Keys(pattern: keyPattern)) + { + chiavi[i] = key; + i++; + } + } + } + catch (Exception exc) + { + Log.Error($"Eccezione in redGetCounterByKey{Environment.NewLine}{exc}"); + } + // ora recupero valori! + var valori = getRKeys(chiavi); + int currVal = 0; + // popolo rispsota + try + { + for (int i = 0; i < numAnsw; i++) + { + Int32.TryParse(valori[i], out currVal); + answ.Add(new KeyValuePair(chiavi[i], currVal)); + } + } + catch + { } + // se richiesto riordino... + switch (orderBy) + { + case kvpOrderBy.KeyAsc: + answ.Sort(CompareKey); + break; + + case kvpOrderBy.KeyDesc: + answ.Sort(CompareKeyDesc); + break; + + case kvpOrderBy.ValAsc: + answ.Sort(CompareVal); + break; + + case kvpOrderBy.ValDesc: + answ.Sort(CompareValDesc); + break; + + default: + break; + } + return answ; + } + + /// + /// Recupera tutti i valori dalla hash + /// + /// + /// + public KeyValuePair[] redGetHash(string hashKey) + { + KeyValuePair[] answ = new KeyValuePair[1]; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + HashEntry[] valori = cache.HashGetAll(chiave); + answ = new KeyValuePair[valori.Length]; + int i = 0; + foreach (HashEntry item in valori) + { + answ[i] = new KeyValuePair(item.Name, item.Value); + i++; + } + } + catch + { } + return answ; + } + + /// + /// Recupera tutti i valori dalla hash in formato Dictionary + /// + /// + /// + public Dictionary redGetHashDict(string hashKey) + { + Dictionary answ = new Dictionary(); + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + HashEntry[] valori = cache.HashGetAll(chiave); + foreach (HashEntry item in valori) + { + answ.Add(item.Name, item.Value); + } + } + catch + { } + return answ; + } + + /// + /// Recupera UN SINGOLO VALORE dalla hash per un dato field + /// + /// + /// + /// + public string redGetHashField(string hashKey, string hashField) + { + string answ = ""; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + RedisValue campo = hashField; + RedisValue valOut = cache.HashGet(chiave, campo); + answ = valOut.ToString(); + } + catch + { } + return answ; + } + + /// + /// Nome della variabile HASH da utilizzare (dato CodModulo / Server / DB impiegato da + /// funzionalita' DbConfig) + keyName richiesto... + /// + public string redHash(string keyName) + { + string answ = keyName; + try + { + answ = string.Format("{0}:{1}:{2}:{3}", memLayer.ML.confReadString("CodModulo"), memLayer.ML.taConfig.Connection.DataSource, memLayer.ML.taConfig.Connection.Database, keyName).Replace("\\", "_"); + } + catch + { } + return answ; + } + + /// + /// Verifica se ci siano valori nella hash indicata... + /// + /// + /// + public bool redHashPresent(RedisKey key) + { + bool answ = false; + // cerco se ci sia valore in redis... + try + { + answ = cache.HashGetAll(key).Length > 0; + } + catch (Exception exc) + { + Log.Error(string.Format("Eccezione in redHashPresent per la key {2}{0}{1}", Environment.NewLine, exc, key)); + } + return answ; + } + + /// + /// Verifica se ci siano valori nella hash indicata (string) + /// + /// + /// + public bool redHashPresentSz(string key) + { + bool answ = false; + try + { + RedisKey chiave = key; + answ = redHashPresent(chiave); + } + catch + { } + return answ; + } + + /// + /// Verifica se ci siano valori nella KEY indicata... + /// + /// + /// + public bool redKeyPresent(RedisKey key) + { + bool answ = false; + // cerco se ci sia valore in redis... + try + { + answ = cache.KeyExists(key); + } + catch (Exception exc) + { + Log.Error(string.Format("Eccezione in redKeyPresent per la key {2}:{0}{1}", Environment.NewLine, exc, key)); + } + return answ; + } + + /// + /// Verifica se ci siano valori nella KEY indicata (string) + /// + /// + /// + public bool redKeyPresentSz(string key) + { + bool answ = false; + try + { + RedisKey chiave = key; + answ = redKeyPresent(chiave); + } + catch + { } + return answ; + } + + /// + /// Salvataggio di una hash di valori + /// + /// chiave + /// valori + /// + public bool redSaveHash(string hashKey, KeyValuePair[] hashFields) + { + bool answ = false; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + HashEntry[] valori = new HashEntry[hashFields.Length]; + int i = 0; + foreach (KeyValuePair kvp in hashFields) + { + valori[i] = new HashEntry(kvp.Key, kvp.Value); + i++; + } + cache.HashSet(chiave, valori); + answ = true; + } + catch + { } + return answ; + } + + /// + /// Salvataggio di una hash di valori + /// + /// chiave + /// valori + /// + /// scadenza preimpostata hash (secondi) | defaoult = -1 (non scade) + /// + /// + public bool redSaveHash(string hashKey, KeyValuePair[] hashFields, double expireSeconds = -1) + { + bool answ = false; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + answ = redSaveHash(hashKey, hashFields); + if (expireSeconds > 0) + { + cache.KeyExpire(chiave, DateTime.Now.AddSeconds(expireSeconds)); + } + //answ = true; + } + catch + { } + return answ; + } + + /// + /// Salvataggio di una hash di valori in formato Dictionary + /// + /// chiave + /// valori + /// + public bool redSaveHashDict(string hashKey, Dictionary hashFields) + { + bool answ = false; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + HashEntry[] valori = new HashEntry[hashFields.Count]; + int i = 0; + foreach (KeyValuePair kvp in hashFields) + { + valori[i] = new HashEntry(kvp.Key, kvp.Value); + i++; + } + cache.HashSet(chiave, valori); + answ = true; + } + catch + { } + return answ; + } + + /// + /// Salvataggio di una hash di valori in formato Dictionary + /// + /// chiave + /// valori + /// + /// scadenza preimpostata hash (secondi) | defaoult = -1 (non scade) + /// + /// + public bool redSaveHashDict(string hashKey, Dictionary hashFields, double expireSeconds = -1) + { + bool answ = false; + // cerco se ci sia valore in redis... + try + { + RedisKey chiave = hashKey; + answ = redSaveHashDict(hashKey, hashFields); + if (expireSeconds > 0) + { + cache.KeyExpire(chiave, DateTime.Now.AddSeconds(expireSeconds)); + } + //answ = true; + } + catch + { } + return answ; + } + + /// + /// Salvataggio di una hash di valori + /// + /// chiave + /// valori come lista KVP + /// + public bool redSaveHashList(string hashKey, List> hashListKVP) + { + bool answ = false; + if (connRedis.IsConnected) + { + // cerco se ci sia valore in redis... + IDatabase cache = connRedis.GetDatabase(); + try + { + RedisKey chiave = hashKey; + HashEntry[] valori = new HashEntry[hashListKVP.Count]; + int i = 0; + foreach (KeyValuePair kvp in hashListKVP) + { + valori[i] = new HashEntry(kvp.Key, kvp.Value); + i++; + } + cache.HashSet(chiave, valori); + answ = true; + } + catch + { } + } + return answ; + } + + /// + /// Restituisce info dei server connessi... + /// + /// + public IServer[] redServInfo() + { + IServer[] answ = new IServer[1]; + try + { + answ = new IServer[connRedisAdmin.GetEndPoints().Length]; + int i = 0; + foreach (var ep in connRedisAdmin.GetEndPoints()) + { + var server = connRedisAdmin.GetServer(ep); + answ[i] = server; + i++; + } + } + catch (Exception exc) + { + Log.Error($"redServInfo:{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// Resetta (elimina) un contatore in Redis + /// + /// + /// + public bool resetRCnt(string chiave) + { + bool answ = false; + try + { + answ = cache.KeyDelete(chiave); + } + catch (Exception exc) + { + Log.Error(string.Format("Eccezione in resetRCnt:{0}{1}", Environment.NewLine, exc)); + } + return answ; + } + + /// + /// Serializzazione di un oggetto generico + /// + /// + /// + public string serializeVal(object origVal) + { + string answ = ""; + try + { + answ = JsonConvert.SerializeObject(origVal); + } + catch { } + return answ; + } + + /// + /// Decrementa un contatore in Redis + /// + /// + /// + public long setRCntD(string chiave) + { + long answ = 0; + try + { + answ = cache.StringDecrement(chiave, 1); + } + catch (Exception exc) + { + Log.Error(string.Format("Eccezzione in setRCD:{0}{1}", Environment.NewLine, exc)); + } + return answ; + } + + /// + /// Incrementa un contatore in Redis + /// + /// + /// + public long setRCntI(string chiave) + { + long answ = 0; + try + { + answ = cache.StringIncrement(chiave, 1); + } + catch (Exception exc) + { + Log.Error(string.Format("Eccezzione in setRCI:{0}{1}", Environment.NewLine, exc)); + } + return answ; + } + + /// + /// Salva un set KVP (Key Value Pair) in RedisCache + /// + /// Set KVP chiave-valore da salvare + /// + public bool setRKeys(KeyValuePair[] valori) + { + bool answ = false; + try + { + cache.StringSet(valori); + answ = true; + } + catch (Exception exc) + { + Log.Error(string.Format("Eccezione in setRKeys:{0}{1}", Environment.NewLine, exc)); + } + return answ; + } + + /// + /// Salva una chiave in RedisCache + /// + /// + /// + /// + public bool setRSV(string chiave, string valore) + { + bool answ = false; + try + { + cache.StringSet(chiave, valore); + answ = true; + } + catch (Exception exc) + { + Log.Error(string.Format("Eccezzione in setRSV:{0}{1}", Environment.NewLine, exc)); + } + return answ; + } + + /// + /// Salva una chiave in RedisCache + /// + /// + /// + /// in secondi + /// + public bool setRSV(string chiave, string valore, int TTL_sec) + { + bool answ = false; + try + { + TimeSpan expT = new TimeSpan(0, 0, TTL_sec); + // salvo con expyry... + cache.StringSet(chiave, valore, expT); + answ = true; + } + catch (Exception exc) + { + Log.Error(string.Format("Eccezzione in setRSV:{0}{1}", Environment.NewLine, exc)); + } + return answ; + } + + /// + /// Lunghezza Stack + /// + /// + /// + public long StackLen(string stackName) + { + return connRedis.GetDatabase().ListLength((RedisKey)stackName); + } + + /// + /// Recupera valore da Stack (F.I.L.O.) + /// + /// + /// + public string StackPop(string stackName) + { + return connRedis.GetDatabase().ListRightPop((RedisKey)stackName).ToString(); + } + + /// + /// Mette in Stack un valore (F.I.L.O.) + /// + /// + /// + public void StackPush(string stackName, string value) + { + connRedis.GetDatabase().ListRightPush((RedisKey)stackName, (RedisValue)value); + } + + #endregion Public Methods + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + /// + /// Connessione lazy a redis... + /// + private Lazy lazyConnection = new Lazy(() => + { + string RedisConn = memLayer.ML.confReadString("RedisConn"); + if (string.IsNullOrEmpty(RedisConn)) + { + RedisConn = "localhost,abortConnect=false,ssl=false"; + } + + return ConnectionMultiplexer.Connect(RedisConn); + }); + + /// + /// Connessione lazy a redis... + /// + private Lazy lazyConnectionAdmin = new Lazy(() => + { + string RedisConnAdmin = memLayer.ML.confReadString("RedisConnAdmin"); + if (string.IsNullOrEmpty(RedisConnAdmin)) + { + RedisConnAdmin = "localhost,abortConnect=false,ssl=false,allowAdmin=true"; + } + + return ConnectionMultiplexer.Connect(RedisConnAdmin); + }); + + #endregion Private Fields + + #region Private Properties + + /// + /// Oggetto currentDb locale + /// + private IDatabase _currDB { get; set; } + + #endregion Private Properties + + #region Private Methods + + /// + /// Effettua comaprazione x CHIAVE in KVP ASC + /// + /// + /// + /// + private int CompareKey(KeyValuePair x, KeyValuePair y) + { + return x.Key.CompareTo(y.Key); + } + + /// + /// Effettua comaprazione x CHIAVE in KVP DESC + /// + /// + /// + /// + private int CompareKeyDesc(KeyValuePair x, KeyValuePair y) + { + return y.Key.CompareTo(x.Key); + } + + #endregion Private Methods } - - /// - /// Effettua comaprazione x CHIAVE in KVP ASC - /// - /// - /// - /// - private int CompareKey(KeyValuePair x, KeyValuePair y) - { - return x.Key.CompareTo(y.Key); - } - - /// - /// Effettua comaprazione x VALORE in KVP ASC - /// - /// - /// - /// - public int CompareVal(KeyValuePair x, KeyValuePair y) - { - return x.Value.CompareTo(y.Value); - } - - /// - /// Effettua comaprazione x CHIAVE in KVP DESC - /// - /// - /// - /// - private int CompareKeyDesc(KeyValuePair x, KeyValuePair y) - { - return y.Key.CompareTo(x.Key); - } - - /// - /// Effettua comaprazione x VALORE in KVP DESC - /// - /// - /// - /// - public int CompareValDesc(KeyValuePair x, KeyValuePair y) - { - return y.Value.CompareTo(x.Value); - } - - /// - /// Tipologia di ordinamento x liste KVP - /// - public enum kvpOrderBy - { - /// - /// Ordinamento ASCending per KEY - /// - KeyAsc, - - /// - /// Ordinamento DESCending per KEY - /// - KeyDesc, - - /// - /// Ordinamento ASCending per VAL - /// - ValAsc, - - /// - /// Ordinamento DESCending per VAL - /// - ValDesc - } - - #endregion gestione valori in RedisCache - - #region gestione Stack / List - - /// - /// Lunghezza Stack - /// - /// - /// - public long StackLen(string stackName) - { - return connRedis.GetDatabase().ListLength((RedisKey)stackName); - } - - /// - /// Mette in Stack un valore (F.I.L.O.) - /// - /// - /// - public void StackPush(string stackName, string value) - { - connRedis.GetDatabase().ListRightPush((RedisKey)stackName, (RedisValue)value); - } - - /// - /// Recupera valore da Stack (F.I.L.O.) - /// - /// - /// - public string StackPop(string stackName) - { - return connRedis.GetDatabase().ListRightPop((RedisKey)stackName).ToString(); - } - - /// - /// Lunghezza List - /// - /// - /// - public long ListLen(string queueName) - { - return connRedis.GetDatabase().ListLength((RedisKey)queueName); - } - - /// - /// Mette un valore in List (F.I.F.O.) - /// - /// - /// - public void ListPush(string queueName, string value) - { - connRedis.GetDatabase().ListRightPush((RedisKey)queueName, (RedisValue)value); - } - - /// - /// Recupera valore da List (F.I.F.O.) - /// - /// - /// - public string ListPop(string queueName) - { - return connRedis.GetDatabase().ListLeftPop((RedisKey)queueName).ToString(); - } - - #endregion gestione Stack / List - } } \ No newline at end of file diff --git a/SteamWare.IO/fileMover.cs b/SteamWare.IO/fileMover.cs index 48af3d4..f263b0e 100644 --- a/SteamWare.IO/fileMover.cs +++ b/SteamWare.IO/fileMover.cs @@ -1,5 +1,5 @@ using ICSharpCode.SharpZipLib.Zip; -using SteamWare.Logger; +using NLog; using System; using System.Diagnostics; using System.IO; @@ -7,1280 +7,1322 @@ using System.Net; namespace SteamWare.IO { - /// - /// Accesso in lettura e scrittura al filesystem per gestione files upload e download - /// - public class fileMover - { - - #region oggetti private - /// - /// path di lavoro dei metodi leggi/scrivi + /// Accesso in lettura e scrittura al filesystem per gestione files upload e download /// - protected string _workPath; - /// - /// verifica esistenza directory ed eventualmente crea restituendo nome completo di "/" finale - /// - /// - /// - protected string verDir(string _path) + public class fileMover { - DirectoryInfo di = getDirectoryInfo(_path, true); - if (!di.Exists) - { - di.Create(); - } - if (!_path.EndsWith("/") && !_path.EndsWith(@"\")) - { - _path += "/"; - } - return _path; - } - /// - /// restituisce una tab di files dato l'elenco dei files - /// - /// - /// - private static DataLayer_generic.filesDataTable tabellaFiles(FileInfo[] _files) - { - DataLayer_generic.filesDataTable _dsEF = new DataLayer_generic.filesDataTable(); - DataLayer_generic.filesRow _riga; - foreach (FileInfo _fi in _files) - { - _riga = _dsEF.NewfilesRow(); - _riga.dataCreaz = _fi.CreationTime; - _riga.dataMod = _fi.LastWriteTime; - _riga.Nome = _fi.Name; - _riga.size = _fi.Length / 1000; - _dsEF.AddfilesRow(_riga); - } - return _dsEF; - } - /// - /// setta le directory - /// - /// - private void setDirs(string _path) - { - _workPath = _path; - } - /// - /// oggetto WebClient - /// - public WebClient WebCli; + #region Public Fields - #endregion + /// + /// versione statica (singleton) del'oggetto fileMover + /// + public static fileMover obj = new fileMover(); - #region inizializzazione + /// + /// oggetto WebClient + /// + public WebClient WebCli; - /// - /// inizializza il metodo alla cartella indicata - /// - /// - /// non serve +... x retrocompatibilità... - public fileMover(string _path, string _log) - { - setDirs(_path); - WebCli = new WebClient(); - } - /// - /// metodo di avvio empty - /// - public fileMover() - { - WebCli = new WebClient(); - } + #endregion Public Fields + #region Public Constructors - #endregion - - /// - /// Recupera path correttamente (se fisico o virtuale - /// - /// - /// - protected string GetPath(string path) - { - if (Path.IsPathRooted(path)) - { - return path; - } - // altrimenti MapPath! - return System.Web.HttpContext.Current.Server.MapPath(path); - } - - /// - /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile - /// - /// - /// - private FileInfo getFileInfoByName(string _nomeFile) - { - FileInfo _fi; - try - { - _fi = new FileInfo(GetPath(_workPath + "\\" + _nomeFile)); - } - catch (Exception exc) - { - Logging.Instance.Error($"Errore in recupero info file: {_nomeFile}{Environment.NewLine}{exc}"); - _fi = new FileInfo(_workPath + "\\" + _nomeFile); - } -#if false - // se nomefile contiene "/" --> faccio mappath altrimenti è percorso fisico... - if (_nomeFile.IndexOf("/") < 0) - { - try + /// + /// inizializza il metodo alla cartella indicata + /// + /// + /// non serve +... x retrocompatibilità... + public fileMover(string _path, string _log) { - _fi = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(_workPath + "\\" + _nomeFile)); + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } + setDirs(_path); + WebCli = new WebClient(); } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in recupero info file{_nomeFile}:{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - _fi = new FileInfo(_workPath + "\\" + _nomeFile); - } - } - else - { - try - { - _fi = new FileInfo(_nomeFile); - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in recupero info file{_nomeFile}:{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - _fi = new FileInfo(_workPath + "\\" + _nomeFile); - } - } -#endif - return _fi; - } - /// - /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile - /// - /// The _path. - /// The _nome file. - /// - private FileInfo getFileInfoByName(string _path, string _nomeFile) - { - FileInfo _fi; - try - { - _fi = new FileInfo(GetPath(_path + _nomeFile)); - } - catch (Exception exc) - { - Logging.Instance.Error($"Errore in recupero info path: {_path} | file: {_nomeFile}{Environment.NewLine}{exc}"); - _fi = new FileInfo(_path + "\\" + _nomeFile); - } + /// + /// metodo di avvio empty + /// + public fileMover() + { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } + WebCli = new WebClient(); + } + + #endregion Public Constructors + + #region Public Methods + + /// + /// Effettua copia files da locale a rete con auth (Local 2 Network)... + /// + /// + /// + /// + /// + /// + /// + /// + public static bool copiaFileL2N(string pathSource, string pathDest, NetworkCredential credentialsDest, string fileSource, string fileDest) + { + bool fatto = false; + Log.Info($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}"); + try + { + using (new NetworkConnection(pathDest, credentialsDest)) + { + File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); + fatto = true; + } + } + catch (Exception exc) + { + Log.Error($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}"); + } + return fatto; + } + + /// + /// Effettua copia files via rete con auth (Net 2 Net)... + /// + /// + /// + /// + /// + /// + /// + /// + public static bool copiaFileN2N(string pathSource, string pathDest, NetworkCredential credentialsSource, NetworkCredential credentialsDest, string fileSource, string fileDest) + { + bool fatto = false; + Log.Info($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}"); + try + { + using (new NetworkConnection(pathSource, credentialsSource)) + using (new NetworkConnection(pathDest, credentialsDest)) + { + File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); + fatto = true; + } + } + catch (Exception exc) + { + Log.Error($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}"); + } + return fatto; + } + + /// + /// elimina la folder indicata + /// + /// Path della fodler da eliminare + /// Indica se cancellare in modo ricorsivo + /// + public static bool deleteDir(string PathOfDir2Delete, bool recursive = true) + { + bool ret = true; + try + { + if (Directory.Exists(PathOfDir2Delete)) + { + Directory.Delete(PathOfDir2Delete, recursive); + } + } + catch (Exception ex) + { + ret = false; + Log.Error($"Non sono riuscito ad eliminare la directory {PathOfDir2Delete} richiesta: eccezione {ex}"); + } + return ret; + } + + /// + /// elimina il file indicato + /// + /// + /// + public static bool deleteFile(string PathOfFile2Delete) + { + bool ret = true; + try + { + if (File.Exists(PathOfFile2Delete)) + { + File.Delete(PathOfFile2Delete); + } + } + catch (Exception ex) + { + ret = false; + Log.Error(string.Format("Non sono riuscito ad eliminare file: eccezione {0}", ex)); + } + return ret; + } + + /// + /// Copia il contenuto directory da From a To (opzionalmente in modo ricorsivo)... + /// + /// Nome dir sorgente + /// Nome dir destinazione + /// Indica se copiare ricorsivamente + /// Indica se sovrascrivere i dati (default = true) + /// + public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, bool overwrite = true) + { + // Get the subdirectories for the specified directory. + DirectoryInfo dir = new DirectoryInfo(sourceDirName); + + if (!dir.Exists) + { + throw new DirectoryNotFoundException( + "Source directory does not exist or could not be found: " + + sourceDirName); + } + + DirectoryInfo[] dirs = dir.GetDirectories(); + // If the destination directory doesn't exist, create it. + if (!Directory.Exists(destDirName)) + { + Directory.CreateDirectory(destDirName); + } + + // Get the files in the directory and copy them to the new location. + FileInfo[] files = dir.GetFiles(); + foreach (FileInfo file in files) + { + string temppath = Path.Combine(destDirName, file.Name); + file.CopyTo(temppath, overwrite); + } + + // If copying subdirectories, copy them and their contents to new location. + if (copySubDirs) + { + foreach (DirectoryInfo subdir in dirs) + { + string temppath = Path.Combine(destDirName, subdir.Name); + DirectoryCopy(subdir.FullName, temppath, copySubDirs); + } + } + } + + /// + /// esegue un comando in shell + /// + /// + /// + /// + /// + public static int ExecuteCommand(string workDir, string Command, int Timeout) + { + int ExitCode; + ProcessStartInfo ProcessInfo; + Process Process; + + ProcessInfo = new ProcessStartInfo(Command); + ProcessInfo.CreateNoWindow = false; + ProcessInfo.UseShellExecute = true; + ProcessInfo.WorkingDirectory = workDir; + //ProcessInfo.RedirectStandardError = true; + //ProcessInfo.RedirectStandardInput = true; + //ProcessInfo.RedirectStandardOutput = true; + Process = Process.Start(ProcessInfo); + Process.WaitForExit(Timeout); + ExitCode = Process.ExitCode; + Process.Close(); + + return ExitCode; + } + + /// + /// restituisce la stringa completa e corretta del filepath del server (anche con vDir) + /// + /// path relativo alla cartella iis dell'applicativo + /// path fisico tradotto + public static string getFilePath(string pathRel) + { + return System.Web.HttpContext.Current.Server.MapPath(pathRel); + } + + /// + /// esegue un comando in shell + /// + /// + /// + /// + /// + public static void LaunchCommand(string workDir, string Command, int Timeout) + { + //int ExitCode; + ProcessStartInfo ProcessInfo; + Process Process; + + ProcessInfo = new ProcessStartInfo(Command); + ProcessInfo.CreateNoWindow = false; + ProcessInfo.UseShellExecute = true; + ProcessInfo.WorkingDirectory = workDir; + //ProcessInfo.RedirectStandardError = true; + //ProcessInfo.RedirectStandardInput = true; + //ProcessInfo.RedirectStandardOutput = true; + Process = Process.Start(ProcessInfo); + //Process.WaitForExit(Timeout); + //ExitCode = Process.ExitCode; + //Process.Close(); + } + + /// + /// Legge i dati da uno stream fino a quando arriva alla fine. I dati sono restituiti come + /// un byte[] array. un eccezione IOException è sollevata se una delle chiamate IO + /// sottostanti fallisce. + /// + /// Lo stream da cui leggere + /// Lunghezza buffer iniziale (-1 = default 32k) + public static byte[] ReadFully(Stream stream, int initialLength) + { + // If we've been passed an unhelpful initial length, just use 32K. + if (initialLength < 1) + { + initialLength = 32768; + } + + byte[] buffer = new byte[initialLength]; + int read = 0; + + int chunk; + while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0) + { + read += chunk; + + // If we've reached the end of our buffer, check to see if there's any more information + if (read == buffer.Length) + { + int nextByte = stream.ReadByte(); + + // End of stream? If so, we're done + if (nextByte == -1) + { + return buffer; + } + + // Nope. Resize the buffer, put in the byte we've just read, and continue + byte[] newBuffer = new byte[buffer.Length * 2]; + Array.Copy(buffer, newBuffer, buffer.Length); + newBuffer[read] = (byte)nextByte; + buffer = newBuffer; + read++; + } + } + // Buffer is now too big. Shrink it. + byte[] ret = new byte[read]; + Array.Copy(buffer, ret, read); + return ret; + } + + /// + /// scompatta tutto il contenuto di un file zip + /// + /// + /// + public static bool UnZipFile(string InputPathOfZipFile) + { + bool ret = true; + try + { + if (File.Exists(InputPathOfZipFile)) + { + string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile); + + using (ZipInputStream ZipStream = new + + ZipInputStream(File.OpenRead(InputPathOfZipFile))) + { + ZipEntry theEntry; + while ((theEntry = ZipStream.GetNextEntry()) != null) + { + if (theEntry.IsFile) + { + if (theEntry.Name != "") + { + string strNewFile = @"" + baseDirectory + @"\" + + + theEntry.Name; + if (File.Exists(strNewFile)) + { + continue; + } + + using (FileStream streamWriter = File.Create(strNewFile)) + { + int size = 4096; + byte[] data = new byte[4096]; + while (true) + { + size = ZipStream.Read(data, 0, data.Length); + if (size > 0) + streamWriter.Write(data, 0, size); + else + break; + } + streamWriter.Close(); + } + } + } + else if (theEntry.IsDirectory) + { + string strNewDirectory = @"" + baseDirectory + @"\" + theEntry.Name; + if (!Directory.Exists(strNewDirectory)) + { + Directory.CreateDirectory(strNewDirectory); + } + } + } + ZipStream.Close(); + } + } + } + catch (Exception ex) + { + ret = false; + Log.Error(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex)); + } + return ret; + } + + /// + /// scompatta uno specifico file contenuto in un file zip + /// + /// The input path of zip file. + /// The file2unzip. + /// + public static bool UnZipSingleFile(string InputPathOfZipFile, string file2unzip) + { + bool ret = true; + try + { + if (File.Exists(InputPathOfZipFile)) + { + string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile); + + using (ZipInputStream ZipStream = new + + ZipInputStream(File.OpenRead(InputPathOfZipFile))) + { + ZipEntry theEntry; + while ((theEntry = ZipStream.GetNextEntry()) != null) + { + if (theEntry.IsFile) + { + if (theEntry.Name == file2unzip) + { + string strNewFile = @"" + baseDirectory + @"\" + theEntry.Name; + if (File.Exists(strNewFile)) + { + continue; + } + + using (FileStream streamWriter = File.Create(strNewFile)) + { + int size = 4096; + byte[] data = new byte[4096]; + while (true) + { + size = ZipStream.Read(data, 0, data.Length); + if (size > 0) + streamWriter.Write(data, 0, size); + else + break; + } + streamWriter.Close(); + } + } + } + else if (theEntry.IsDirectory) + { + string strNewDirectory = @"" + baseDirectory + @"\" + + + theEntry.Name; + if (!Directory.Exists(strNewDirectory)) + { + Directory.CreateDirectory(strNewDirectory); + } + } + } + ZipStream.Close(); + } + } + } + catch (Exception ex) + { + ret = false; + Log.Error(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex)); + } + return ret; + } + + /// + /// verifica esistenza directory, eventualmente crea e restituisce controllo DirectoryInfo + /// + /// + public DirectoryInfo checkDir() + { + DirectoryInfo _di = getDirectoryInfo(); + if (!_di.Exists) + { + _di.Create(); + } + return _di; + } + + /// + /// copia il file da From a To... + /// + /// + /// + /// + /// + public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFile) + { + bool fatto = false; + // verifica directory + _pathFrom = verDir(_pathFrom); + _pathTo = verDir(_pathTo); + FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile); + try + { + _fi.CopyTo(_pathTo + _nomeFile, true); + fatto = true; + } + catch (Exception e) + { + Console.WriteLine("{0} Exception caught.", e); + } + return fatto; + } + + /// + /// copia il file da From a To... + /// + /// + /// + /// + /// + /// + public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFileOrig, string _nomeFileDest) + { + bool fatto = false; + // verifica directory + _pathFrom = verDir(_pathFrom); + _pathTo = verDir(_pathTo); + FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFileOrig); + try + { + _fi.CopyTo(System.Web.HttpContext.Current.Server.MapPath(_pathTo) + _nomeFileDest, true); + fatto = true; + } + catch (Exception e) + { + Console.WriteLine("{0} Exception caught.", e); + _fi.CopyTo(_pathTo + _nomeFileDest, true); + fatto = true; + } + return fatto; + } + + /// + /// elimina il file + vecchio + /// + /// + public void deleteOldest() + { + DirectoryInfo _di = checkDir(); + FileInfo[] _fis = _di.GetFiles(); + DateTime _oldest = DateTime.Now; + string _nome = ""; + foreach (FileInfo _file in _fis) + { + if (_file.CreationTime < _oldest) + { + _nome = _file.Name; + } + } + eliminaFile(_nome); + } + + /// + /// ottiene il dataset dei files presenti nella directory indicata all'istanziazione dell'oggetto + /// + /// + public DataLayer_generic.filesDataTable elencoFiles() + { + DirectoryInfo _di = checkDir(); + FileInfo[] _files = _di.GetFiles(); + DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); + return _dsEF; + } + + /// + /// ottiene il dataset dei files DEL TIPO "like {param}" presenti nella directory indicata + /// all'istanziazione dell'oggetto + /// + /// + public DataLayer_generic.filesDataTable elencoFiles(string _param) + { + DirectoryInfo _di = checkDir(); + FileInfo[] _files = _di.GetFiles(_param); + DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); + return _dsEF; + } + + /// + /// elenco dei files come array di oggetti FileInfo + /// + /// + public FileInfo[] elencoFiles_FI() + { + DirectoryInfo _di = checkDir(); + return _di.GetFiles(); + } + + /// + /// elenco dei files come array di oggetti FileInfo filtrati per parametro + /// + /// + /// + public FileInfo[] elencoFiles_FI(string _param) + { + DirectoryInfo _di = checkDir(); + return _di.GetFiles(_param); + } + + /// + /// ottiene il dataset dei files presenti nella directory indicata esplicitamente + /// + /// + /// dir da indicizzare... già mappata! ( es SteamwareStrings.getFilePath(...) ) + /// + /// + public DataLayer_generic.filesDataTable elencoFilesDir(string directory) + { + _workPath = directory; + return elencoFiles(); + } + + /// + /// elenco sub-directory array di oggetti FileInfo filtrati per parametro + /// + /// + public DirectoryInfo[] elencoSubdir_DI() + { + DirectoryInfo _di = checkDir(); + return _di.GetDirectories(); + } + + /// + /// elenco sub-directory array di oggetti FileInfo filtrati per parametro + /// + /// + /// + public DirectoryInfo[] elencoSubdir_DI(string _param) + { + DirectoryInfo _di = checkDir(); + return _di.GetDirectories(_param); + } + + /// + /// elimina la directory di lavoro se è dir virtuale mappata + /// + /// + public bool eliminaDir() + { + DirectoryInfo _di = checkDir(); + bool fatto = false; + try + { + _di.Delete(true); + fatto = true; + } + catch + { + } + return fatto; + } + + /// + /// elimina il file indicato dalla directory di lavoro + /// + /// + /// + public bool eliminaFile(string _nomeFile) + { + FileInfo _fi = getFileInfoByName(_nomeFile); + bool fatto = false; + try + { + _fi.Delete(); + fatto = true; + } + catch + { } + if (fatto) + { + Log.Info($"Eliminazione file {_nomeFile} eseguita"); + } + else + { + Log.Info($"impossibile Eliminare il file {_nomeFile}"); + } + return fatto; + } + + /// + /// elimina il file indicato dalla directory di lavoro + /// + /// The _fi. + /// + public bool eliminaFile(FileInfo _fi) + { + bool fatto = false; + try + { + _fi.Delete(); + fatto = true; + } + catch + { + } + return fatto; + } + + /// + /// verifica se il file indicato esista in workDir + /// + /// + /// + public bool fileExist(string _nomeFile) + { + bool answ = false; + FileInfo _fi = getFileInfoByName(_nomeFile); + answ = _fi.Exists; + if (!answ) + { + // registro che non ho trovaot il file: path e nome file! + Log.Info(string.Format("Attenzione: non e' stato possibile trovare il file!{0}wrkDir:{1}{0}file:{2}", Environment.NewLine, _workPath, _nomeFile)); + } + return answ; + } + + /// + /// verifica se il file indicato esista in _path + /// + /// + /// + /// + public bool fileExist(string _path, string _nomeFile) + { + bool answ = false; + FileInfo _fi = getFileInfoByName(_path, _nomeFile); + answ = _fi.Exists; + if (!answ) + { + // registro che non ho trovaot il file: path e nome file! + Log.Info(string.Format("Attenzione: non e' stato possibile trovare il file!{0}path:{1}{0}file:{2}", Environment.NewLine, _path, _nomeFile)); + } + return answ; + } + + /// + /// sposta il file da From a To... + /// + /// + /// + /// + /// + public bool muoviFile(string _pathFrom, string _pathTo, string _nomeFile) + { + bool fatto = false; + // verifica directory + _pathTo = verDir(_pathTo); + _pathFrom = verDir(_pathFrom); + FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile, true); + try + { + _fi.CopyTo(_pathTo + _nomeFile, true); + _fi.Delete(); + fatto = true; + } + catch (Exception e) + { + Console.WriteLine("{0} Exception caught.", e); + } + return fatto; + } + + /// + /// scrive il file dallo stream byte[] inviato + /// + /// + /// + /// + /// + public bool salvaFileBuffer(string _path, string _nomeFile, byte[] _fileBuffer) + { + _workPath = _path; + DirectoryInfo _di = getDirectoryInfo(_path, true); + if (!_di.Exists) + { + _di.Create(); + } + FileInfo _fi = getFileInfoByName(_path, _nomeFile); + Stream _stream; + if (!_fi.Exists) + { + _stream = _fi.Create(); + } + else + { + _stream = _fi.OpenWrite(); + } + _stream.Write(_fileBuffer, 0, _fileBuffer.Length); + _stream.Flush(); + _stream.Close(); + + return true; + } + + /// + /// scrive il file dallo stream byte[] inviato + /// + /// + /// + /// + public bool salvaFileBuffer(string _nomeFile, byte[] _fileBuffer) + { + DirectoryInfo _di = getDirectoryInfo(); + if (!_di.Exists) + { + _di.Create(); + } + FileInfo _fi = getFileInfoByName(_nomeFile); + Stream _stream; + if (!_fi.Exists) + { + _stream = _fi.Create(); + } + else + { + _stream = _fi.OpenWrite(); + } + _stream.Write(_fileBuffer, 0, _fileBuffer.Length); + _stream.Flush(); + _stream.Close(); + + return true; + } + + /// + /// scrive il file dalla stringa inviata + /// + /// + /// + /// + /// + public bool salvaFileString(string _path, string _nomeFile, string _fileString) + { + return salvaFileBuffer(_path, _nomeFile, strToByte(_fileString)); + } + + /// + /// scrive il file dalla stringa inviata + /// + /// + /// + /// + public bool salvaFileString(string _nomeFile, string _fileString) + { + return salvaFileBuffer(_nomeFile, strToByte(_fileString)); + } + + /// + /// restituisce lo stream del file richiesto + /// + /// + /// + public byte[] scaricaFile(string _nomeFile) + { + FileInfo _fi = getFileInfoByName(_nomeFile); + // verifica ci siano attach... + if (_fi.Exists) + { + Stream _stream = _fi.OpenRead(); + byte[] _risposta = ReadFully(_stream, -1); + _stream.Close(); + return _risposta; + } + else + { + return null; + } + } + + /// + /// Scarica un file dall'url fornito nella directory indicata x il filemover col nome richiesto + /// + /// url del file + /// nome con cui salvare il file + /// + public void scaricaFileFromWeb(string urlFile, string nomeDest) + { + // utilizzo l'oggetto webCli... + + WebCli.Credentials = System.Net.CredentialCache.DefaultCredentials; + WebCli.DownloadFile(urlFile, string.Format("{0}\\{1}", _workPath, nomeDest)); + } + + /// + /// restituisce la stringa letta dal file richiesto + /// + /// + /// + public string scaricaFileString(string _nomeFile) + { + return byteToStr(scaricaFile(_nomeFile)); + } + + /// + /// imposta la dir di lavoro + /// + /// + public void setDirectory(string _path) + { + setDirs(_path); + } + + /// + /// imposta la dir di lavoro + /// + /// + /// non serve +... x retrocompatibilità... + public void setDirectory(string _path, string _log) + { + setDirs(_path); + } + + /// + /// imposta la dir di lavoro impostandola dal mapPath corretto della web app... (come + /// subfolder della web app) + /// + /// + public void setDirectoryMapPath(string _path) + { + setDirs(System.Web.HttpContext.Current.Server.MapPath(_path)); + } + + /// + /// elimina tutti i files con la regexp indicata da una directory, true se cancellato almeno uno + /// + /// regexp selezione files in dir (* = tutti!!!) + /// + public bool svuotaDir(string nomeCercato) + { + bool answ = false; + FileInfo[] _fis = elencoFiles_FI(nomeCercato); + foreach (FileInfo _file in _fis) + { + eliminaFile(_file.Name); + answ = true; + } + return answ; + } + + /// + /// calcola la dim della directory corrente... + /// + /// + public float totalMb() + { + DirectoryInfo _di = checkDir(); + FileInfo[] _fis = _di.GetFiles(); + float _byte = 0; + foreach (FileInfo _file in _fis) + { + _byte += _file.Length; + } + return _byte / 1000000; + } + + /// + /// comprime zip i files corrispondenti alla RegExp indicata nella dir corrente + /// + /// Espressione ricerca, come *.txt + /// Nome del file zip da creare + /// + public bool zippaFilesByRegExp(string regExp, string outZipFileName) + { + bool fatto = false; + // inizializzo il file zip... + DirectoryInfo _di = checkDir(); + // calcolo il nome del file zip... + string nomeZip = string.Format("{0}/{1}.zip", _di.FullName, outZipFileName.Replace(".zip", "")); + // inizio a inserire dati + try + { + using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) + { + s.SetLevel(5); + byte[] buffer = new byte[4096]; + // effettuo una ricerca dei files corrispondenti al criterio regexp, e per + // ognuno effettuo inserimento in zipfile... + FileInfo[] filesTrovati = elencoFiles_FI(regExp); + ZipEntry entry; + foreach (FileInfo _fi in filesTrovati) + { + // calcolo la nuova entry nel file zip... + entry = new ZipEntry(Path.GetFileName(_fi.FullName)); + // Could also use the last write time or similar for the file. + entry.DateTime = DateTime.Now; + s.PutNextEntry(entry); + using (FileStream fs = File.OpenRead(_fi.FullName)) + { + // Using a fixed size buffer here makes no noticeable difference for + // output but keeps a lid on memory usage. + int sourceBytes; + do + { + sourceBytes = fs.Read(buffer, 0, buffer.Length); + s.Write(buffer, 0, sourceBytes); + } while (sourceBytes > 0); + } + } + s.Finish(); + s.Close(); + } + fatto = true; + } + catch (Exception e) + { + Log.Error(string.Format("Errore in creazione file zip con parametri {0} e {1}: {2}", regExp, outZipFileName, e)); + } + return fatto; + } + + /// + /// comprime zip il file indicato + /// + /// + /// + public bool zippaSingoloFile(string _nomeFile) + { + bool fatto = false; + FileInfo _fi = getFileInfoByName(_nomeFile); + // calcolo il nome del file zip... + string nomeZip = string.Format("{0}.zip", _fi.FullName); + try + { + using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) + { + s.SetLevel(5); + byte[] buffer = new byte[4096]; + ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); + // Could also use the last write time or similar for the file. + entry.DateTime = DateTime.Now; + s.PutNextEntry(entry); + using (FileStream fs = File.OpenRead(_fi.FullName)) + { + // Using a fixed size buffer here makes no noticeable difference for output + // but keeps a lid on memory usage. + int sourceBytes; + do + { + sourceBytes = fs.Read(buffer, 0, buffer.Length); + s.Write(buffer, 0, sourceBytes); + } while (sourceBytes > 0); + } + s.Finish(); + s.Close(); + } + fatto = true; + } + catch + { + } + return fatto; + } + + /// + /// comprime zip il file indicato + /// + /// File in formato FileInfo + /// + public bool zippaSingoloFile(FileInfo _fi) + { + bool fatto = false; + // calcolo il nome del file zip... + string nomeZip = string.Format("{0}.zip", _fi.FullName); + try + { + using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) + { + s.SetLevel(5); + byte[] buffer = new byte[4096]; + ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); + // Could also use the last write time or similar for the file. + entry.DateTime = DateTime.Now; + s.PutNextEntry(entry); + using (FileStream fs = File.OpenRead(_fi.FullName)) + { + // Using a fixed size buffer here makes no noticeable difference for output + // but keeps a lid on memory usage. + int sourceBytes; + do + { + sourceBytes = fs.Read(buffer, 0, buffer.Length); + s.Write(buffer, 0, sourceBytes); + } while (sourceBytes > 0); + } + s.Finish(); + s.Close(); + } + fatto = true; + } + catch + { + } + return fatto; + } + + #endregion Public Methods + + #region Protected Fields + + /// + /// path di lavoro dei metodi leggi/scrivi + /// + protected string _workPath; + + #endregion Protected Fields + + #region Protected Methods + + /// + /// converte un byte[] in una string + /// + /// + /// + protected string byteToStr(byte[] _array) + { + System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); + return encod.GetString(_array); + } + + /// + /// Recupera path correttamente (se fisico o virtuale + /// + /// + /// + protected string GetPath(string path) + { + if (Path.IsPathRooted(path)) + { + return path; + } + // altrimenti MapPath! + return System.Web.HttpContext.Current.Server.MapPath(path); + } + + /// + /// converte una string in un byte[] + /// + /// + /// + protected byte[] strToByte(string _val) + { + System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); + return encod.GetBytes(_val); + } + + /// + /// verifica esistenza directory ed eventualmente crea restituendo nome completo di "/" finale + /// + /// + /// + protected string verDir(string _path) + { + DirectoryInfo di = getDirectoryInfo(_path, true); + if (!di.Exists) + { + di.Create(); + } + if (!_path.EndsWith("/") && !_path.EndsWith(@"\")) + { + _path += "/"; + } + return _path; + } + + #endregion Protected Methods + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields + + #region Private Methods + + /// + /// restituisce una tab di files dato l'elenco dei files + /// + /// + /// + private static DataLayer_generic.filesDataTable tabellaFiles(FileInfo[] _files) + { + DataLayer_generic.filesDataTable _dsEF = new DataLayer_generic.filesDataTable(); + DataLayer_generic.filesRow _riga; + foreach (FileInfo _fi in _files) + { + _riga = _dsEF.NewfilesRow(); + _riga.dataCreaz = _fi.CreationTime; + _riga.dataMod = _fi.LastWriteTime; + _riga.Nome = _fi.Name; + _riga.size = _fi.Length / 1000; + _dsEF.AddfilesRow(_riga); + } + return _dsEF; + } + + /// + /// cerca di caricare la directoryInfo o da httpcontext-application re-position o + /// direttamente come workpath + /// + /// + private DirectoryInfo getDirectoryInfo() + { + DirectoryInfo _di; + try + { + _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(_workPath)); + } + catch + { + _di = new DirectoryInfo(_workPath); + } + return _di; + } + + /// + /// imposta la directory richiesta... + /// + /// + private DirectoryInfo getDirectoryInfo(string path, bool absPath) + { + DirectoryInfo _di; + if (absPath) + { + _di = new DirectoryInfo(path); + } + else + { + try + { + _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(path)); + } + catch + { + _di = new DirectoryInfo(path); + } + } + return _di; + } + + /// + /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente + /// come workpath + nomefile + /// + /// + /// + private FileInfo getFileInfoByName(string _nomeFile) + { + FileInfo _fi; + try + { + _fi = new FileInfo(GetPath(_workPath + "\\" + _nomeFile)); + } + catch (Exception exc) + { + Log.Error($"Errore in recupero info file: {_nomeFile}{Environment.NewLine}{exc}"); + _fi = new FileInfo(_workPath + "\\" + _nomeFile); + } + return _fi; + } + + /// + /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente + /// come workpath + nomefile + /// + /// The _path. + /// The _nome file. + /// + private FileInfo getFileInfoByName(string _path, string _nomeFile) + { + FileInfo _fi; + try + { + _fi = new FileInfo(GetPath(_path + _nomeFile)); + } + catch (Exception exc) + { + Log.Error($"Errore in recupero info path: {_path} | file: {_nomeFile}{Environment.NewLine}{exc}"); + _fi = new FileInfo(_path + "\\" + _nomeFile); + } #if false try { _fi = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(_path + _nomeFile)); - } catch { _fi = new FileInfo(_path + "\\" + _nomeFile); - } + } #endif - return _fi; - } - /// - /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile - /// - /// cartella file - /// nome file - /// indica se il path sia assoluto - /// - private FileInfo getFileInfoByName(string _path, string _nomeFile, bool absPath) - { - FileInfo _fi; - if (absPath) - { - _fi = new FileInfo(_path + "\\" + _nomeFile); - } - else - { - _fi = getFileInfoByName(_path, _nomeFile); - } - return _fi; - } - /// - /// cerca di caricare la directoryInfo o da httpcontext-application re-position o direttamente come workpath - /// - /// - private DirectoryInfo getDirectoryInfo() - { - DirectoryInfo _di; - try - { - _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(_workPath)); - } - catch - { - _di = new DirectoryInfo(_workPath); - } - return _di; - } - /// - /// imposta la directory richiesta... - /// - /// - private DirectoryInfo getDirectoryInfo(string path, bool absPath) - { - DirectoryInfo _di; - if (absPath) - { - _di = new DirectoryInfo(path); - } - else - { - - try - { - _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(path)); + return _fi; } - catch + + /// + /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente + /// come workpath + nomefile + /// + /// cartella file + /// nome file + /// indica se il path sia assoluto + /// + private FileInfo getFileInfoByName(string _path, string _nomeFile, bool absPath) { - _di = new DirectoryInfo(path); - } - } - return _di; - } - - #region oggetti public - - /// - /// Legge i dati da uno stream fino a quando arriva alla fine. - /// I dati sono restituiti come un byte[] array. un eccezione IOException è - /// sollevata se una delle chiamate IO sottostanti fallisce. - /// - /// Lo stream da cui leggere - /// Lunghezza buffer iniziale (-1 = default 32k) - public static byte[] ReadFully(Stream stream, int initialLength) - { - // If we've been passed an unhelpful initial length, just - // use 32K. - if (initialLength < 1) - { - initialLength = 32768; - } - - byte[] buffer = new byte[initialLength]; - int read = 0; - - int chunk; - while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0) - { - read += chunk; - - // If we've reached the end of our buffer, check to see if there's - // any more information - if (read == buffer.Length) - { - int nextByte = stream.ReadByte(); - - // End of stream? If so, we're done - if (nextByte == -1) - { - return buffer; - } - - // Nope. Resize the buffer, put in the byte we've just - // read, and continue - byte[] newBuffer = new byte[buffer.Length * 2]; - Array.Copy(buffer, newBuffer, buffer.Length); - newBuffer[read] = (byte)nextByte; - buffer = newBuffer; - read++; - } - } - // Buffer is now too big. Shrink it. - byte[] ret = new byte[read]; - Array.Copy(buffer, ret, read); - return ret; - } - - /// - /// verifica esistenza directory, eventualmente crea e restituisce controllo DirectoryInfo - /// - /// - public DirectoryInfo checkDir() - { - DirectoryInfo _di = getDirectoryInfo(); - if (!_di.Exists) - { - _di.Create(); - } - return _di; - } - - /// - /// ottiene il dataset dei files presenti nella directory indicata esplicitamente - /// - /// dir da indicizzare... già mappata! ( es SteamwareStrings.getFilePath(...) ) - /// - public DataLayer_generic.filesDataTable elencoFilesDir(string directory) - { - _workPath = directory; - return elencoFiles(); - } - - /// - /// ottiene il dataset dei files presenti nella directory indicata all'istanziazione dell'oggetto - /// - /// - public DataLayer_generic.filesDataTable elencoFiles() - { - DirectoryInfo _di = checkDir(); - FileInfo[] _files = _di.GetFiles(); - DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); - return _dsEF; - } - /// - /// ottiene il dataset dei files DEL TIPO "like {param}" presenti nella directory indicata all'istanziazione dell'oggetto - /// - /// - public DataLayer_generic.filesDataTable elencoFiles(string _param) - { - DirectoryInfo _di = checkDir(); - FileInfo[] _files = _di.GetFiles(_param); - DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); - return _dsEF; - } - /// - /// elenco dei files come array di oggetti FileInfo - /// - /// - public FileInfo[] elencoFiles_FI() - { - DirectoryInfo _di = checkDir(); - return _di.GetFiles(); - } - /// - /// elenco dei files come array di oggetti FileInfo filtrati per parametro - /// - /// - /// - public FileInfo[] elencoFiles_FI(string _param) - { - DirectoryInfo _di = checkDir(); - return _di.GetFiles(_param); - } - /// - /// elenco sub-directory array di oggetti FileInfo filtrati per parametro - /// - /// - public DirectoryInfo[] elencoSubdir_DI() - { - DirectoryInfo _di = checkDir(); - return _di.GetDirectories(); - } - /// - /// elenco sub-directory array di oggetti FileInfo filtrati per parametro - /// - /// - /// - public DirectoryInfo[] elencoSubdir_DI(string _param) - { - DirectoryInfo _di = checkDir(); - return _di.GetDirectories(_param); - } - /// - /// elimina la directory di lavoro se è dir virtuale mappata - /// - /// - public bool eliminaDir() - { - DirectoryInfo _di = checkDir(); - bool fatto = false; - try - { - _di.Delete(true); - fatto = true; - } - catch - { - } - return fatto; - } - - /// - /// elimina tutti i files con la regexp indicata da una directory, true se cancellato almeno uno - /// - /// regexp selezione files in dir (* = tutti!!!) - /// - public bool svuotaDir(string nomeCercato) - { - bool answ = false; - FileInfo[] _fis = elencoFiles_FI(nomeCercato); - foreach (FileInfo _file in _fis) - { - eliminaFile(_file.Name); - answ = true; - } - return answ; - } - - /// - /// verifica se il file indicato esista in workDir - /// - /// - /// - public bool fileExist(string _nomeFile) - { - bool answ = false; - FileInfo _fi = getFileInfoByName(_nomeFile); - answ = _fi.Exists; - if (!answ) - { - // registro che non ho trovaot il file: path e nome file! - Logging.Instance.Info(string.Format("Attenzione: non e' stato possibile trovare il file!{0}wrkDir:{1}{0}file:{2}", Environment.NewLine, _workPath, _nomeFile)); - } - return answ; - } - /// - /// verifica se il file indicato esista in _path - /// - /// - /// - /// - public bool fileExist(string _path, string _nomeFile) - { - bool answ = false; - FileInfo _fi = getFileInfoByName(_path, _nomeFile); - answ = _fi.Exists; - if (!answ) - { - // registro che non ho trovaot il file: path e nome file! - Logging.Instance.Info(string.Format("Attenzione: non e' stato possibile trovare il file!{0}path:{1}{0}file:{2}", Environment.NewLine, _path, _nomeFile)); - } - return answ; - } - /// - /// elimina il file indicato dalla directory di lavoro - /// - /// - /// - public bool eliminaFile(string _nomeFile) - { - FileInfo _fi = getFileInfoByName(_nomeFile); - bool fatto = false; - try - { - _fi.Delete(); - fatto = true; - } - catch - { } - if (fatto) - { - Logging.Instance.Info($"Eliminazione file {_nomeFile} eseguita"); - } - else - { - Logging.Instance.Info($"impossibile Eliminare il file {_nomeFile}"); - } - return fatto; - } - /// - /// elimina il file indicato dalla directory di lavoro - /// - /// The _fi. - /// - public bool eliminaFile(FileInfo _fi) - { - bool fatto = false; - try - { - _fi.Delete(); - fatto = true; - } - catch - { - } - return fatto; - } - /// - /// restituisce lo stream del file richiesto - /// - /// - /// - public byte[] scaricaFile(string _nomeFile) - { - FileInfo _fi = getFileInfoByName(_nomeFile); - // verifica ci siano attach... - if (_fi.Exists) - { - Stream _stream = _fi.OpenRead(); - byte[] _risposta = ReadFully(_stream, -1); - _stream.Close(); - return _risposta; - } - else - { - return null; - } - } - /// - /// restituisce la stringa letta dal file richiesto - /// - /// - /// - public string scaricaFileString(string _nomeFile) - { - return byteToStr(scaricaFile(_nomeFile)); - } - /// - /// scrive il file dallo stream byte[] inviato - /// - /// - /// - /// - /// - public bool salvaFileBuffer(string _path, string _nomeFile, byte[] _fileBuffer) - { - _workPath = _path; - DirectoryInfo _di = getDirectoryInfo(_path, true); - if (!_di.Exists) - { - _di.Create(); - } - FileInfo _fi = getFileInfoByName(_path, _nomeFile); - Stream _stream; - if (!_fi.Exists) - { - _stream = _fi.Create(); - } - else - { - _stream = _fi.OpenWrite(); - } - _stream.Write(_fileBuffer, 0, _fileBuffer.Length); - _stream.Flush(); - _stream.Close(); - - return true; - } - /// - /// scrive il file dallo stream byte[] inviato - /// - /// - /// - /// - public bool salvaFileBuffer(string _nomeFile, byte[] _fileBuffer) - { - DirectoryInfo _di = getDirectoryInfo(); - if (!_di.Exists) - { - _di.Create(); - } - FileInfo _fi = getFileInfoByName(_nomeFile); - Stream _stream; - if (!_fi.Exists) - { - _stream = _fi.Create(); - } - else - { - _stream = _fi.OpenWrite(); - } - _stream.Write(_fileBuffer, 0, _fileBuffer.Length); - _stream.Flush(); - _stream.Close(); - - return true; - } - /// - /// scrive il file dalla stringa inviata - /// - /// - /// - /// - /// - public bool salvaFileString(string _path, string _nomeFile, string _fileString) - { - return salvaFileBuffer(_path, _nomeFile, strToByte(_fileString)); - } - /// - /// scrive il file dalla stringa inviata - /// - /// - /// - /// - public bool salvaFileString(string _nomeFile, string _fileString) - { - return salvaFileBuffer(_nomeFile, strToByte(_fileString)); - } - /// - /// converte una string in un byte[] - /// - /// - /// - protected byte[] strToByte(string _val) - { - System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); - return encod.GetBytes(_val); - } - /// - /// converte un byte[] in una string - /// - /// - /// - protected string byteToStr(byte[] _array) - { - System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); - return encod.GetString(_array); - } - - /// - /// sposta il file da From a To... - /// - /// - /// - /// - /// - public bool muoviFile(string _pathFrom, string _pathTo, string _nomeFile) - { - bool fatto = false; - // verifica directory - _pathTo = verDir(_pathTo); - _pathFrom = verDir(_pathFrom); - FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile, true); - try - { - _fi.CopyTo(_pathTo + _nomeFile, true); - _fi.Delete(); - fatto = true; - } - catch (Exception e) - { - Console.WriteLine("{0} Exception caught.", e); - } - return fatto; - } - /// - /// Copia il contenuto directory da From a To (opzionalmente in modo ricorsivo)... - /// - /// Nome dir sorgente - /// Nome dir destinazione - /// Indica se copiare ricorsivamente - /// Indica se sovrascrivere i dati (default = true) - /// - public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, bool overwrite = true) - { - // Get the subdirectories for the specified directory. - DirectoryInfo dir = new DirectoryInfo(sourceDirName); - - if (!dir.Exists) - { - throw new DirectoryNotFoundException( - "Source directory does not exist or could not be found: " - + sourceDirName); - } - - DirectoryInfo[] dirs = dir.GetDirectories(); - // If the destination directory doesn't exist, create it. - if (!Directory.Exists(destDirName)) - { - Directory.CreateDirectory(destDirName); - } - - // Get the files in the directory and copy them to the new location. - FileInfo[] files = dir.GetFiles(); - foreach (FileInfo file in files) - { - string temppath = Path.Combine(destDirName, file.Name); - file.CopyTo(temppath, overwrite); - } - - // If copying subdirectories, copy them and their contents to new location. - if (copySubDirs) - { - foreach (DirectoryInfo subdir in dirs) - { - string temppath = Path.Combine(destDirName, subdir.Name); - DirectoryCopy(subdir.FullName, temppath, copySubDirs); - } - } - } - - /// - /// copia il file da From a To... - /// - /// - /// - /// - /// - public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFile) - { - bool fatto = false; - // verifica directory - _pathFrom = verDir(_pathFrom); - _pathTo = verDir(_pathTo); - FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile); - try - { - _fi.CopyTo(_pathTo + _nomeFile, true); - fatto = true; - } - catch (Exception e) - { - Console.WriteLine("{0} Exception caught.", e); - } - return fatto; - } - /// - /// copia il file da From a To... - /// - /// - /// - /// - /// - /// - public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFileOrig, string _nomeFileDest) - { - bool fatto = false; - // verifica directory - _pathFrom = verDir(_pathFrom); - _pathTo = verDir(_pathTo); - FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFileOrig); - try - { - _fi.CopyTo(System.Web.HttpContext.Current.Server.MapPath(_pathTo) + _nomeFileDest, true); - fatto = true; - } - catch (Exception e) - { - Console.WriteLine("{0} Exception caught.", e); - _fi.CopyTo(_pathTo + _nomeFileDest, true); - fatto = true; - } - return fatto; - } - /// - /// Effettua copia files da locale a rete con auth (Local 2 Network)... - /// - /// - /// - /// - /// - /// - /// - /// - public static bool copiaFileL2N(string pathSource, string pathDest, NetworkCredential credentialsDest, string fileSource, string fileDest) - { - bool fatto = false; - Logging.Instance.Info($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}"); - try - { - using (new NetworkConnection(pathDest, credentialsDest)) - { - File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); - fatto = true; - } - } - catch (Exception exc) - { - Logging.Instance.Error($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}"); - } - return fatto; - } - /// - /// Effettua copia files via rete con auth (Net 2 Net)... - /// - /// - /// - /// - /// - /// - /// - /// - public static bool copiaFileN2N(string pathSource, string pathDest, NetworkCredential credentialsSource, NetworkCredential credentialsDest, string fileSource, string fileDest) - { - bool fatto = false; - Logging.Instance.Info($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}"); - try - { - using (new NetworkConnection(pathSource, credentialsSource)) - using (new NetworkConnection(pathDest, credentialsDest)) - { - File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); - fatto = true; - } - } - catch (Exception exc) - { - Logging.Instance.Error($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}"); - } - return fatto; - } - - /// - /// imposta la dir di lavoro - /// - /// - public void setDirectory(string _path) - { - setDirs(_path); - } - /// - /// imposta la dir di lavoro - /// - /// - /// non serve +... x retrocompatibilità... - public void setDirectory(string _path, string _log) - { - setDirs(_path); - } - /// - /// imposta la dir di lavoro impostandola dal mapPath corretto della web app... (come subfolder della web app) - /// - /// - public void setDirectoryMapPath(string _path) - { - setDirs(System.Web.HttpContext.Current.Server.MapPath(_path)); - } - /// - /// restituisce la stringa completa e corretta del filepath del server (anche con vDir) - /// - /// path relativo alla cartella iis dell'applicativo - /// path fisico tradotto - public static string getFilePath(string pathRel) - { - return System.Web.HttpContext.Current.Server.MapPath(pathRel); - } - /// - /// esegue un comando in shell - /// - /// - /// - /// - /// - public static int ExecuteCommand(string workDir, string Command, int Timeout) - { - int ExitCode; - ProcessStartInfo ProcessInfo; - Process Process; - - ProcessInfo = new ProcessStartInfo(Command); - ProcessInfo.CreateNoWindow = false; - ProcessInfo.UseShellExecute = true; - ProcessInfo.WorkingDirectory = workDir; - //ProcessInfo.RedirectStandardError = true; - //ProcessInfo.RedirectStandardInput = true; - //ProcessInfo.RedirectStandardOutput = true; - Process = Process.Start(ProcessInfo); - Process.WaitForExit(Timeout); - ExitCode = Process.ExitCode; - Process.Close(); - - return ExitCode; - } - /// - /// esegue un comando in shell - /// - /// - /// - /// - /// - public static void LaunchCommand(string workDir, string Command, int Timeout) - { - //int ExitCode; - ProcessStartInfo ProcessInfo; - Process Process; - - ProcessInfo = new ProcessStartInfo(Command); - ProcessInfo.CreateNoWindow = false; - ProcessInfo.UseShellExecute = true; - ProcessInfo.WorkingDirectory = workDir; - //ProcessInfo.RedirectStandardError = true; - //ProcessInfo.RedirectStandardInput = true; - //ProcessInfo.RedirectStandardOutput = true; - Process = Process.Start(ProcessInfo); - //Process.WaitForExit(Timeout); - //ExitCode = Process.ExitCode; - //Process.Close(); - } - /// - /// Scarica un file dall'url fornito nella directory indicata x il filemover col nome richiesto - /// - /// url del file - /// nome con cui salvare il file - /// - public void scaricaFileFromWeb(string urlFile, string nomeDest) - { - // utilizzo l'oggetto webCli... - - WebCli.Credentials = System.Net.CredentialCache.DefaultCredentials; - WebCli.DownloadFile(urlFile, string.Format("{0}\\{1}", _workPath, nomeDest)); - } - /// - /// comprime zip il file indicato - /// - /// - /// - public bool zippaSingoloFile(string _nomeFile) - { - bool fatto = false; - FileInfo _fi = getFileInfoByName(_nomeFile); - // calcolo il nome del file zip... - string nomeZip = string.Format("{0}.zip", _fi.FullName); - try - { - using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) - { - s.SetLevel(5); - byte[] buffer = new byte[4096]; - ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); - // Could also use the last write time or similar for the file. - entry.DateTime = DateTime.Now; - s.PutNextEntry(entry); - using (FileStream fs = File.OpenRead(_fi.FullName)) - { - // Using a fixed size buffer here makes no noticeable difference for output - // but keeps a lid on memory usage. - int sourceBytes; - do + FileInfo _fi; + if (absPath) { - sourceBytes = fs.Read(buffer, 0, buffer.Length); - s.Write(buffer, 0, sourceBytes); - } while (sourceBytes > 0); - } - s.Finish(); - s.Close(); - } - fatto = true; - } - catch - { - } - return fatto; - } - - /// - /// comprime zip il file indicato - /// - /// File in formato FileInfo - /// - public bool zippaSingoloFile(FileInfo _fi) - { - bool fatto = false; - // calcolo il nome del file zip... - string nomeZip = string.Format("{0}.zip", _fi.FullName); - try - { - using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) - { - s.SetLevel(5); - byte[] buffer = new byte[4096]; - ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); - // Could also use the last write time or similar for the file. - entry.DateTime = DateTime.Now; - s.PutNextEntry(entry); - using (FileStream fs = File.OpenRead(_fi.FullName)) - { - // Using a fixed size buffer here makes no noticeable difference for output - // but keeps a lid on memory usage. - int sourceBytes; - do - { - sourceBytes = fs.Read(buffer, 0, buffer.Length); - s.Write(buffer, 0, sourceBytes); - } while (sourceBytes > 0); - } - s.Finish(); - s.Close(); - } - fatto = true; - } - catch - { - } - return fatto; - } - /// - /// comprime zip i files corrispondenti alla RegExp indicata nella dir corrente - /// - /// Espressione ricerca, come *.txt - /// Nome del file zip da creare - /// - public bool zippaFilesByRegExp(string regExp, string outZipFileName) - { - bool fatto = false; - // inizializzo il file zip... - DirectoryInfo _di = checkDir(); - // calcolo il nome del file zip... - string nomeZip = string.Format("{0}/{1}.zip", _di.FullName, outZipFileName.Replace(".zip", "")); - // inizio a inserire dati - try - { - using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) - { - s.SetLevel(5); - byte[] buffer = new byte[4096]; - // effettuo una ricerca dei files corrispondenti al criterio regexp, e per ognuno effettuo inserimento in zipfile... - FileInfo[] filesTrovati = elencoFiles_FI(regExp); - ZipEntry entry; - foreach (FileInfo _fi in filesTrovati) - { - // calcolo la nuova entry nel file zip... - entry = new ZipEntry(Path.GetFileName(_fi.FullName)); - // Could also use the last write time or similar for the file. - entry.DateTime = DateTime.Now; - s.PutNextEntry(entry); - using (FileStream fs = File.OpenRead(_fi.FullName)) - { - // Using a fixed size buffer here makes no noticeable difference for output but keeps a lid on memory usage. - int sourceBytes; - do - { - sourceBytes = fs.Read(buffer, 0, buffer.Length); - s.Write(buffer, 0, sourceBytes); - } while (sourceBytes > 0); + _fi = new FileInfo(_path + "\\" + _nomeFile); } - } - s.Finish(); - s.Close(); - } - fatto = true; - } - catch (Exception e) - { - Logging.Instance.Error(string.Format("Errore in creazione file zip con parametri {0} e {1}: {2}", regExp, outZipFileName, e)); - } - return fatto; - } - /// - /// scompatta tutto il contenuto di un file zip - /// - /// - /// - public static bool UnZipFile(string InputPathOfZipFile) - { - bool ret = true; - try - { - if (File.Exists(InputPathOfZipFile)) - { - string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile); - - using (ZipInputStream ZipStream = new - -ZipInputStream(File.OpenRead(InputPathOfZipFile))) - { - ZipEntry theEntry; - while ((theEntry = ZipStream.GetNextEntry()) != null) + else { - if (theEntry.IsFile) - { - if (theEntry.Name != "") - { - string strNewFile = @"" + baseDirectory + @"\" + - -theEntry.Name; - if (File.Exists(strNewFile)) - { - continue; - } - - using (FileStream streamWriter = File.Create(strNewFile)) - { - int size = 4096; - byte[] data = new byte[4096]; - while (true) - { - size = ZipStream.Read(data, 0, data.Length); - if (size > 0) - streamWriter.Write(data, 0, size); - else - break; - } - streamWriter.Close(); - } - } - } - else if (theEntry.IsDirectory) - { - string strNewDirectory = @"" + baseDirectory + @"\" + theEntry.Name; - if (!Directory.Exists(strNewDirectory)) - { - Directory.CreateDirectory(strNewDirectory); - } - } + _fi = getFileInfoByName(_path, _nomeFile); } - ZipStream.Close(); - } + return _fi; } - } - catch (Exception ex) - { - ret = false; - Logging.Instance.Error(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex)); - } - return ret; - } - /// - /// scompatta uno specifico file contenuto in un file zip - /// - /// The input path of zip file. - /// The file2unzip. - /// - public static bool UnZipSingleFile(string InputPathOfZipFile, string file2unzip) - { - bool ret = true; - try - { - if (File.Exists(InputPathOfZipFile)) + + /// + /// setta le directory + /// + /// + private void setDirs(string _path) { - string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile); - - using (ZipInputStream ZipStream = new - -ZipInputStream(File.OpenRead(InputPathOfZipFile))) - { - ZipEntry theEntry; - while ((theEntry = ZipStream.GetNextEntry()) != null) - { - if (theEntry.IsFile) - { - if (theEntry.Name == file2unzip) - { - string strNewFile = @"" + baseDirectory + @"\" + theEntry.Name; - if (File.Exists(strNewFile)) - { - continue; - } - - using (FileStream streamWriter = File.Create(strNewFile)) - { - int size = 4096; - byte[] data = new byte[4096]; - while (true) - { - size = ZipStream.Read(data, 0, data.Length); - if (size > 0) - streamWriter.Write(data, 0, size); - else - break; - } - streamWriter.Close(); - } - } - } - else if (theEntry.IsDirectory) - { - string strNewDirectory = @"" + baseDirectory + @"\" + - -theEntry.Name; - if (!Directory.Exists(strNewDirectory)) - { - Directory.CreateDirectory(strNewDirectory); - } - } - } - ZipStream.Close(); - } + _workPath = _path; } - } - catch (Exception ex) - { - ret = false; - Logging.Instance.Error(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex)); - } - return ret; - } - /// - /// elimina il file indicato - /// - /// - /// - public static bool deleteFile(string PathOfFile2Delete) - { - bool ret = true; - try - { - if (File.Exists(PathOfFile2Delete)) - { - File.Delete(PathOfFile2Delete); - } - } - catch (Exception ex) - { - ret = false; - Logging.Instance.Error(string.Format("Non sono riuscito ad eliminare file: eccezione {0}", ex)); - } - return ret; - } - /// - /// elimina la folder indicata - /// - /// Path della fodler da eliminare - /// Indica se cancellare in modo ricorsivo - /// - public static bool deleteDir(string PathOfDir2Delete, bool recursive = true) - { - bool ret = true; - try - { - if (Directory.Exists(PathOfDir2Delete)) - { - Directory.Delete(PathOfDir2Delete, recursive); - } - } - catch (Exception ex) - { - ret = false; - Logging.Instance.Error($"Non sono riuscito ad eliminare la directory {PathOfDir2Delete} richiesta: eccezione {ex}"); - } - return ret; - } - - /// - /// calcola la dim della directory corrente... - /// - /// - public float totalMb() - { - DirectoryInfo _di = checkDir(); - FileInfo[] _fis = _di.GetFiles(); - float _byte = 0; - foreach (FileInfo _file in _fis) - { - _byte += _file.Length; - } - return _byte / 1000000; + #endregion Private Methods } - /// - /// elimina il file + vecchio - /// - /// - public void deleteOldest() - { - DirectoryInfo _di = checkDir(); - FileInfo[] _fis = _di.GetFiles(); - DateTime _oldest = DateTime.Now; - string _nome = ""; - foreach (FileInfo _file in _fis) - { - if (_file.CreationTime < _oldest) - { - _nome = _file.Name; - } - } - eliminaFile(_nome); - } - - #endregion - - /// - /// versione statica (singleton) del'oggetto fileMover - /// - public static fileMover obj = new fileMover(); - - } -} +} \ No newline at end of file diff --git a/SteamWare.IO/memLayer.cs b/SteamWare.IO/memLayer.cs index 9cec4ff..3a4b5df 100644 --- a/SteamWare.IO/memLayer.cs +++ b/SteamWare.IO/memLayer.cs @@ -1,5 +1,7 @@ using MongoDB.Driver; using Newtonsoft.Json; +using NLog.Fluent; +using NLog; using StackExchange.Redis; using SteamWare.Logger; using System; @@ -89,11 +91,16 @@ namespace SteamWare.IO #region Protected Constructors + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); /// /// classe gestione accessi a Session, cache, viewstate, configuration... /// protected memLayer() { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } // istanzia il conf setting reader... configAppSetReader = new AppSettingsReader(); // avvio e configuro TA @@ -304,7 +311,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Errore in lettura valore maxAgeAppConf_min{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Errore in lettura valore maxAgeAppConf_min{0}{1}", Environment.NewLine, exc)); } return maxAge * 60; } @@ -380,7 +387,7 @@ namespace SteamWare.IO catch (Exception exc) { answ = new Dictionary(); - Logging.Instance.Error(string.Format("Eccezzione in tabelleInCache{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Eccezzione in tabelleInCache{0}{1}", Environment.NewLine, exc)); } return answ; } @@ -486,7 +493,7 @@ namespace SteamWare.IO catch (Exception exc) { numTry--; - Logging.Instance.Error($"Errore procedura nML.taConfig.GetData(), numTry = {numTry}, now {waitMs}ms wait{Environment.NewLine}{exc}"); + Log.Error($"Errore procedura nML.taConfig.GetData(), numTry = {numTry}, now {waitMs}ms wait{Environment.NewLine}{exc}"); Thread.Sleep(waitMs); } } while (numTry > 0 && tabDati == null); @@ -501,11 +508,11 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Errore procedura ricaricaAppConf per kvp: {0} / {1}{2}{3}", riga.chiave, riga.valore, Environment.NewLine, exc)); + Log.Error(string.Format("Errore procedura ricaricaAppConf per kvp: {0} / {1}{2}{3}", riga.chiave, riga.valore, Environment.NewLine, exc)); } } // log ricarica - Logging.Instance.Info(string.Format("Effettuata procedura ricaricaAppConf per {0} records", answ.Count)); + Log.Info(string.Format("Effettuata procedura ricaricaAppConf per {0} records", answ.Count)); } return answ; } @@ -559,17 +566,17 @@ namespace SteamWare.IO } // salvo in redis valori (con TTL) redSaveHash(ACBH, valori, maxAgeAppConf); - Logging.Instance.Info("Completato procedura startupAppConf"); + Log.Info("Completato procedura startupAppConf"); } else { - Logging.Instance.Error("Errore in procedura startupAppConf, ritornato insieme vuoto"); + Log.Error("Errore in procedura startupAppConf, ritornato insieme vuoto"); } } } catch (Exception exc) { - Logging.Instance.Error(string.Format("Errore in startupAppConf:{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Errore in startupAppConf:{0}{1}", Environment.NewLine, exc)); } } } @@ -707,12 +714,12 @@ namespace SteamWare.IO bool fatto = bool.TryParse(sVal, out answ); if (!fatto) { - Logging.Instance.Error($"Errore in lettura chiave [{chiave}] durante cdvb: ricevuto {sVal}"); + Log.Error($"Errore in lettura chiave [{chiave}] durante cdvb: ricevuto {sVal}"); } } catch (Exception exc) { - Logging.Instance.Error($"Eccezzione in lettura chiave [{chiave}] durante cdvb{Environment.NewLine}{exc}"); + Log.Error($"Eccezzione in lettura chiave [{chiave}] durante cdvb{Environment.NewLine}{exc}"); } } return answ; @@ -735,12 +742,12 @@ namespace SteamWare.IO bool fatto = int.TryParse(sVal, out answ); if (!fatto) { - Logging.Instance.Error($"Errore in lettura chiave [{chiave}] durante cdvi: ricevuto {sVal}"); + Log.Error($"Errore in lettura chiave [{chiave}] durante cdvi: ricevuto {sVal}"); } } catch (Exception exc) { - Logging.Instance.Error($"Eccezzione in lettura chiave [{chiave}] durante cdvi{Environment.NewLine}{exc}"); + Log.Error($"Eccezzione in lettura chiave [{chiave}] durante cdvi{Environment.NewLine}{exc}"); } } return answ; @@ -793,7 +800,7 @@ namespace SteamWare.IO // controllo SE in redis ci sia ancora il valore, altrimenti rileggo... if (!redKeyPresent(ACBH)) { - Logging.Instance.Info(string.Format("Manca HASH in redis --> rileggo da DB --> REDIS --> Memoria | {0} | {1}", ACBH, chiave)); + Log.Info(string.Format("Manca HASH in redis --> rileggo da DB --> REDIS --> Memoria | {0} | {1}", ACBH, chiave)); resetAppConf(); } // provo a leggere da DICT @@ -805,7 +812,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Errore in lettura AppConf[{0}] durante configDbVal{1}{2}", chiave, Environment.NewLine, exc)); + Log.Error(string.Format("Errore in lettura AppConf[{0}] durante configDbVal{1}{2}", chiave, Environment.NewLine, exc)); } } } @@ -1152,7 +1159,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezione in getRSV:{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Eccezione in getRSV:{0}{1}", Environment.NewLine, exc)); } return answInt; } @@ -1193,7 +1200,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezione in getRKeys:{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Eccezione in getRKeys:{0}{1}", Environment.NewLine, exc)); } return answ; } @@ -1212,7 +1219,7 @@ namespace SteamWare.IO } catch (Exception exc) { - //logger.lg.scriviLog(string.Format("Errore in getRSV:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + Log.Error($"Eccezione in getRSV:{Environment.NewLine}{exc}"); } return answ; } @@ -1283,7 +1290,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezzione in verifica isInCacheObject REDIS per chiave{0}{1}{2}", nomeVar, Environment.NewLine, exc)); + Log.Error(string.Format("Eccezzione in verifica isInCacheObject REDIS per chiave{0}{1}{2}", nomeVar, Environment.NewLine, exc)); } } else @@ -1302,7 +1309,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezzione in verifica isInCacheObject per chiave{0}{1}{2}", nomeVar, Environment.NewLine, exc)); + Log.Error(string.Format("Eccezzione in verifica isInCacheObject per chiave{0}{1}{2}", nomeVar, Environment.NewLine, exc)); } } return answ; @@ -1491,7 +1498,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error($"Eccezione in redCountKey:{Environment.NewLine}{exc}"); + Log.Error($"Eccezione in redCountKey:{Environment.NewLine}{exc}"); } return answ; } @@ -1542,7 +1549,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error($"Eccezione in redFlushKey{Environment.NewLine}{exc}"); + Log.Error($"Eccezione in redFlushKey{Environment.NewLine}{exc}"); } return answ; } @@ -1577,7 +1584,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error($"Eccezione in redGetCounterByKey{Environment.NewLine}{exc}"); + Log.Error($"Eccezione in redGetCounterByKey{Environment.NewLine}{exc}"); } // ora recupero valori! var valori = getRKeys(chiavi); @@ -1719,7 +1726,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezione in redHashPresent per la key {2}{0}{1}", Environment.NewLine, exc, key)); + Log.Error(string.Format("Eccezione in redHashPresent per la key {2}{0}{1}", Environment.NewLine, exc, key)); } return answ; } @@ -1757,7 +1764,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezione in redKeyPresent per la key {2}:{0}{1}", Environment.NewLine, exc, key)); + Log.Error(string.Format("Eccezione in redKeyPresent per la key {2}:{0}{1}", Environment.NewLine, exc, key)); } return answ; } @@ -1940,7 +1947,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error($"redServInfo:{Environment.NewLine}{exc}"); + Log.Error($"redServInfo:{Environment.NewLine}{exc}"); } return answ; } @@ -1968,7 +1975,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezione in resetRCnt:{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Eccezione in resetRCnt:{0}{1}", Environment.NewLine, exc)); } return answ; } @@ -2091,7 +2098,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezzione in setRCD:{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Eccezzione in setRCD:{0}{1}", Environment.NewLine, exc)); } return answ; } @@ -2110,7 +2117,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezzione in setRCI:{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Eccezzione in setRCI:{0}{1}", Environment.NewLine, exc)); } return answ; } @@ -2130,7 +2137,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezione in setRKeys:{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Eccezione in setRKeys:{0}{1}", Environment.NewLine, exc)); } return answ; } @@ -2153,12 +2160,12 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezzione in setRSV:{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Eccezzione in setRSV:{0}{1}", Environment.NewLine, exc)); } } else { - Logging.Instance.Error("Errore: chiave non valida (vuota) in setRSV"); + Log.Error("Errore: chiave non valida (vuota) in setRSV"); } return answ; } @@ -2182,7 +2189,7 @@ namespace SteamWare.IO } catch (Exception exc) { - Logging.Instance.Error(string.Format("Eccezzione in setRSV:{0}{1}", Environment.NewLine, exc)); + Log.Error(string.Format("Eccezzione in setRSV:{0}{1}", Environment.NewLine, exc)); } return answ; } diff --git a/SteamWare/App_Readme/README_SteamWare.txt b/SteamWare/App_Readme/README_SteamWare.txt deleted file mode 100644 index 954eff8..0000000 --- a/SteamWare/App_Readme/README_SteamWare.txt +++ /dev/null @@ -1,12 +0,0 @@ ---------------------------------------------------------------- -------- SteamWare SDK ------- ---------------------------------------------------------------- - -Libreria di utility base di SteamWare. - -Le dipendenze inserite sono necessarie al funzionamento dell'SDK. - -Sono inclusi a titolo di esempio vari files di conf: - * example-NLog.config - -Attenzione a configurare correttamente il file NLog.xml includendo il rule per la classe, vedere ad esempio il file example-NLog.config allegato. \ No newline at end of file diff --git a/SteamWare/App_Readme/SteamWare_demo/example-favicon.ico b/SteamWare/App_Readme/SteamWare_demo/example-favicon.ico deleted file mode 100644 index 4f0e0ad0a8300d86881040676f2c05f93ec4c1a3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 31702 zcmeHQ33yf2o&P6+ko7Hj*%JxKA_;9>u%!k=XmD$-)>_3C$zrUnyQGky5-OObRw*h7 zBrFODByX{uX}|fp(fQhHXKHI(txjE7YFj(sj3czu5lhUO-~ZfuZqB>!-nWE+XgMDz z|8xG^+1L9&527^6q5Lw@A46S=V}$tqFq@;H++f6 z2RzH)JdP;yZWYg>o5vH~zJzE7>x5qc&wSFYFo5lE8scN>_id&P`!j`Mb{-kWxObWZ529F({4V(8SqrJ;D{0=n8>t)P;oC1iO64wPjHl~(mj7g0Cu<;H z4J5t(+m&F>dq&$2wAkq%<~Y`Y|FW+I2R6~UALcTvvi)ogdF*93<3|+F2MF>!os!$T zo@Tq0|3uvb>T3~~RgbIk+i|Y(J)M;0QhsiKS2>Nwc{pA!nf#>8gR{V&>~-+!S~>-V zN=Dc5DtpT5l!S7N%R=6jmEZJCO(eXxpMJWxkA?vMiv7@qiTF=+dU==v1yB1$LB#OI zLC>`(dY;E1f7bdR2>Xu|JY9hDv-gVt!egNS1ET_EeowW%f*+X7k3mK&LfMsi|1Sx7 zZgErl=7W^0=06_)ZhRjAJkQsb^X{B5sUYm#Su&VE+d?`7uEMp!79~ z^Q6aB`R%y4an<$~+)S@K=uImK`Tp#W_};P6I1k6m#VrRiF)BLlLVs_So$o^X2wyE? zb*b@G9P$3M1O0f_LCWbAMSRck9EdsKHaB71dH(@^nD0g1c+@;v70lyLHqsS_a>{t0 zq2ebREDCyl#Q6@G`+&lonbXHAkLU+os!qzno@>TR?@{Qn)_+q+nm_FOn=HTF3;0E8 z$a~jO=#LUDi1>!MUIW-;_#^)Rj3TBU;j!!F-0)7kF}T98_gU3O3`=+C)xyU) zU)xL{b)ZSP!mwvQ_kHQZ{$Y(TopD@#MMn?H)adcjRWz`t<}gRUrRuyO;)xmKSo3d1 zyT80|i!{SXO}Ps<=9?!A!k!nawh$~p3^#QRO&H0CQ4bg!umCx>4&{GW*124#WS<+8 z1krCcs=o7bzx-~LP_JHooX@#$jJ1nd|BE8|D`fex{+9&3jhrCz{RV&I$9#ADXfp83 zLzJz3D-diykc^&6$Q6cs-!I@j**5anWVnwzIXAo$uOqHqeX4E9k%2 zKl~8ijqe?;j#0{~wZILsT8kFwr+hj7u`ki_2uH1jHku`$Djsvn0`##BsmdKI{y-={ zXv}}ui)r<8EW!si({EMZVu&=xx{jeTb>|Oz-|(h0*#S`*i48AMV=%=A8N%m2x>$i_ll}cMd zm8Oa_M79)Uy7D03_OiHRop3X9YEHqt5o$cKigf{@+Id-g|q2YW6g%9 z^jG_-Rmzxaj69Y>mUVU9Z)N#Sc@@T) zU(MOBvhfHgr)5h}68790k9RaQ9$zZ2b~s?%5hkV9bsY5*US*BmsryRV-^23T=jfHW zNMepWT`xP@ayZ31$u#JAPS>HrVqj!1W=mf7WrZsa<$qGnX*{lRj|;q{7lnO4RQM9u z6qx+FEQgh6vZ5)d4`NLGkOmK?M&%P*Hcwy zhH@PBN39=9k0UGy`;HjpG;D?{w^D`D9q6Tex^3*%VzWGs`G`lu`WyYNp37<6<5;>- z_MfBd2QlAY9#5B@R)9NM!(PfLf5DFIPk@J=rThI1W1Wb)yVTqI74v(X%=RiMQnrw=Jr}<7;*@hahe9-sVWaZy4K7O<3beDiV|KE@&dw=6>s=i|n z$Fx7b#j5_tyvphFjI+n>d~S5b=LD6Eg3P0bm5ju7^1H=8`i<%bSo3RD|(ed8uGe8gMP&1KV)!; z{Wf^Wq#qeF_{C6Fy<{1xmx!U^dKpJ?qzb@;OjmH|uqb<$5eG$8w}QwL@O!!e58o%m z^9(!18-n5U;(*u!#%BT9jlg#}It0HD{xCe)Wt<^93)ai1*eelRgi!^a&LJ-ltMlrI zJQIYN0GO8nxOwq#WrpbPM*2e;V&&@L#SAmVP^TE4z!2KJfM4%~);CugseJW$6Pl@# zkt;z)EdUz1Pcz|HP55K+SD809I-Cc;0zOTd7ED4U)`|2q66xtA#$}M0FrGwKCc?RC zVmy3)HVID-2`{`amxMo$L?E9;p@&3fQMxGglPD`7Q63;sSx91135m(@Q_Dz9Dy%~3px02|)jYR+LBsSeaV)LCOw!lAeH;L_w;oC^;_zH=g@WBoep=BhV zzL&%|?<4W86J-n^$`@sic*H4d@qk#bb|@lT*-rmd~mdTtY9Q4HEeTDAwB`} zp-?0g+!deAl^Qbg9~tfMBJ48DKgBhL_ykWd6oh*sK36>IE{Gr1Em%C|NzvwRII34A zJGct3NGc^KrpF@O{y`^FQn=kl3y#{*-|RsPl1j{hX)wrLAmni%C55_5=0DW|{Ly9Y z%S^leZK%J{yrj|^VOrMR-QA(0=S@|iq+xq^S9ed++_8*pU0q#E4RrdpU45|(2{0YV zf3LwafC}86fIWtM=8~lyizN13uK&?@KU&A*U&=SNx7{C;kUQcd*Rhc;5qCf-zpA^d z-JRV|xwE~e;|50Vj6_0PIk2J!O}c2+s*iIdp=-B#K*8nasc!lGGYRPAGSLHh2Tq{P zc1@6j-o@RExd-;`{Ji4aJ~-fSm;LIl71avq2Jh@`@4)HssZb=i-r)H(Dso_Xd;6WV ztf!~lxFK~qubLWX-OL|wwbsX4V9rBJ+q%0~5#6?IS==`%teodAv-hl39f5kf+PXSu zcF*FrwlA8g#en} zlG_Ojv8277?e?AB^{ZB$jd?Q?weklep>V{R-wDfmkEo%)4Pzn6vFv@|tF%2h7@V#v z&O;MCsUzIOsNEIx;Fb#UKSqt+Bz_>Nu!JeA06C`h%9ey7N<5sqJBeu7v=L1jRd1!%NTq+(SOmT$d#}j35<5}(9 zZO)Tz#@1cCxStSx9ZfoTJ`JEfBau%jgrX?#UDwH$qlNk@qAZ%HJ->`VT z%uA`Y8MDx_0aRjGb}1VPQ_0dhZ8)bWlE?I_w3YN-R`-&ojn+5q^rMI;tb6E=dTYdS7eAV8 zxak@Vel+Q)Bm?`8+*I`VJdwf72ep?Bqpl;8N=;g z7WS^?Fu!GieaV#wa@j41IpOcHMW}|Y*kRZa9b`gr#OHhlw4|Z}R$T(?8g^=X=C|XE z@V=S9@8P}M|1!NWod3O|u;*Xn>DFinj^x2?TZ!X-Z*O~@R}Zs26@CrF&p54J+{(uK zV_X@2GeM@mhsMFKZ9xo!hCsenYI)NrDa|7>?XMKEZmj=YhwQib zi@4QGT4BihGpOJ;=66!Ad}B!C99!w=?XTnGg}JV@wy<=?kpXG!oR)s7O7-^F^R4tS zJ$;Q~|EqA!$9M%9ufpllCeP?QJV#1-W-y)NV;I+?Ot?WYc(n4xjD5wUpyFl7xYyRx z*$RiZF;h)G0O>dn>{MQ4Sn=cAeLd4u+#c56MJRdZeU;Xk!j@Vonafuk^AL{%CQ@r0A_ zXF+dkouwF&mV%XoEQ$PItk@{h=rCw~=B8K+}F)Z!W*j5epf8Sa@ zOPqDXt9vZqE_L_vT9bvO6v%ap&hqw86e?*#Z&|+(2Ue zEhKg=B@w=d#J4+PL-#({W&`Zesbqa&>(*TUv&T__TLMQdw|^8{xs4GUXZnkPFe z$ea6d%$6;#<(tz`%Ywzu(nND5y{Y-rE)1SIunCyn($Yc|b-b&HaUZF}e+bdsdOg)Q z%>Bf?7&6sy0+}Ts)aTbW#M0+9%%`U2(}+r&o95Tes+(hHsY<8TmL`04yb*0UzqY|! zH(&qcF}Gn3lIP}cyzY{WIrHb9+t6T`F&K*K8a~x@oe^wqg&LYUzwV<(T>dSaw@6i9 zvkGWr`gq-W&1U0&q49$28g&|n=QL>Fh%aevU1VqQX^4wkTd%)LWkqCT$O)|L&O^&9t$%^5n(`ymYGEh*&Z> zJ6iW{+Id;haVN$TX_`t0XJ1|qB&{&$}^gU=iI?M+dLGe!~Kl<+yD zZAZ5F_6m|`ij~{5L~!dk@skJf-UDZe7xeQ2&JC__I&fZi4eb{5rUPw@?4R@}>)>P` z7`r||r_7ADT%Kf$)2UGgr$p5=dG0e^zK^E!Y@?jVM>DE3w6_Jmz_c0JzJQ{W&r@AF zp*rC62gXU9uW&{YO`8!Y@a4&P!E_`yt$Lyo2*~YG@yyA5(adgIdCh6l=#&{Vr&L#A zrkhqXt){djKvQPSm^ou&MNM^Px-SsmeQ#BDRdsb$S&kns6HQlxq6W0x_0i6={}21I BZR`L5 diff --git a/SteamWare/HwSwInfo.cs b/SteamWare/HwSwInfo.cs index f7a37f8..dc2bfb2 100644 --- a/SteamWare/HwSwInfo.cs +++ b/SteamWare/HwSwInfo.cs @@ -1,6 +1,6 @@ using Microsoft.VisualBasic.Devices; +using NLog; using System; -using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; @@ -13,15 +13,6 @@ namespace SteamWare /// public class HwSwInfo { - #region Protected Fields - - /// - /// Assembly di base - /// - protected Assembly assembly = Assembly.GetExecutingAssembly(); - - #endregion Protected Fields - #region Public Constructors /// @@ -29,8 +20,13 @@ namespace SteamWare /// public HwSwInfo() { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } assembly = Assembly.GetExecutingAssembly(); } + /// /// Info hw/sw del server /// @@ -42,13 +38,6 @@ namespace SteamWare #endregion Public Constructors -#if false - /// - /// Singleton! - /// - public static HwSwInfo man = new HwSwInfo(); -#endif - #region Public Properties /// @@ -87,8 +76,10 @@ namespace SteamWare answ += referencedAssemblyName.FullName + Environment.NewLine; } } - catch - { } + catch (Exception exc) + { + Log.Error($"Eccezione librariesVers{Environment.NewLine}{exc}"); + } return answ; } } @@ -105,8 +96,10 @@ namespace SteamWare { answ = assembly.FullName; } - catch - { } + catch (Exception exc) + { + Log.Error($"Eccezione mainAssembly{Environment.NewLine}{exc}"); + } return answ; } } @@ -127,8 +120,10 @@ namespace SteamWare numLib++; } } - catch - { } + catch (Exception exc) + { + Log.Error($"Eccezione numLibraries{Environment.NewLine}{exc}"); + } return numLib; } } @@ -202,7 +197,7 @@ namespace SteamWare } catch (Exception exc) { - logger.lg.scriviLog(string.Format("Errore in redisServersData{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + Log.Error($"Eccezione redisServersData{Environment.NewLine}{exc}"); } return sb.ToString(); } @@ -220,8 +215,10 @@ namespace SteamWare { answ = assembly.ImageRuntimeVersion; } - catch - { } + catch (Exception exc) + { + Log.Error($"Eccezione runtimeImg{Environment.NewLine}{exc}"); + } return answ; } } @@ -260,7 +257,7 @@ namespace SteamWare } catch (Exception exc) { - logger.lg.scriviLog(string.Format("Errore in ServerStats{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); + Log.Error($"Eccezione ServerStats{Environment.NewLine}{exc}"); } return sb.ToString(); } @@ -268,28 +265,6 @@ namespace SteamWare #endregion Public Properties - #region Private Methods - - private static string getBrowserData(string redPattern) - { - StringBuilder sb = new StringBuilder(); - int numRec = memLayer.ML.redCountKey(redPattern); - var redKeys = memLayer.ML.redGetKeys(redPattern); - // riordino elenco - sb.AppendLine(string.Format("Trovate {0} combinazioni", numRec)); - string currKey = ""; - string currVal = ""; - foreach (var item in redKeys) - { - currKey = item.ToString().Replace(memLayer.ML.redHash(redPattern.Replace(":*", ":")), ""); - currVal = memLayer.ML.getRSV(item); - sb.AppendLine($"{currKey}: {currVal}"); - } - return sb.ToString(); - } - - #endregion Private Methods - #region Public Methods /// @@ -316,8 +291,8 @@ namespace SteamWare rawSize = rawSize / 1024; } - // Adjust the format string to your preferences. For example "{0:0.#}{1}" would - // show a single decimal place, and no space. + // Adjust the format string to your preferences. For example "{0:0.#}{1}" would show a + // single decimal place, and no space. return String.Format("{0:0.##} {1}", rawSize, sizes[order]); } @@ -332,5 +307,42 @@ namespace SteamWare } #endregion Public Methods + + #region Protected Fields + + /// + /// Assembly di base + /// + protected Assembly assembly = Assembly.GetExecutingAssembly(); + + #endregion Protected Fields + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields + + #region Private Methods + + private static string getBrowserData(string redPattern) + { + StringBuilder sb = new StringBuilder(); + int numRec = memLayer.ML.redCountKey(redPattern); + var redKeys = memLayer.ML.redGetKeys(redPattern); + // riordino elenco + sb.AppendLine(string.Format("Trovate {0} combinazioni", numRec)); + string currKey = ""; + string currVal = ""; + foreach (var item in redKeys) + { + currKey = item.ToString().Replace(memLayer.ML.redHash(redPattern.Replace(":*", ":")), ""); + currVal = memLayer.ML.getRSV(item); + sb.AppendLine($"{currKey}: {currVal}"); + } + return sb.ToString(); + } + + #endregion Private Methods } } \ No newline at end of file diff --git a/SteamWare/SteamWare.csproj b/SteamWare/SteamWare.csproj index 32bd825..2a8c215 100644 --- a/SteamWare/SteamWare.csproj +++ b/SteamWare/SteamWare.csproj @@ -118,9 +118,6 @@ ..\packages\StackExchange.Redis.2.5.61\lib\net461\StackExchange.Redis.dll - - ..\packages\SteamWare.Logger.5.3.2309.1309\lib\net462\SteamWare.Logger.dll - ..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.dll @@ -315,9 +312,7 @@ - - Always diff --git a/SteamWare/UpdateMan.cs b/SteamWare/UpdateMan.cs index 8c2fcb7..f2bd69b 100644 --- a/SteamWare/UpdateMan.cs +++ b/SteamWare/UpdateMan.cs @@ -1,50 +1,47 @@ -using Newtonsoft.Json; +using NLog; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Net; using System.Net.Http; -using System.Text; -using System.Threading.Tasks; using System.Xml; namespace SteamWare { /// - /// Object of this class gives you all the details about the update useful in handling the update logic yourself. + /// Object of this class gives you all the details about the update useful in handling the + /// update logic yourself. /// public class UpdateInfoEventArgs : EventArgs { #region Public Properties /// - /// URL of the webpage specifying changes in the new update. + /// URL of the webpage specifying changes in the new update. /// public string ChangelogURL { get; set; } /// - /// Returns newest version of the application available to download. + /// Returns newest version of the application available to download. /// public Version CurrentVersion { get; set; } /// - /// Download URL of the update file. + /// Download URL of the update file. /// public string DownloadURL { get; set; } /// - /// Returns version of the application currently installed on the user's PC. + /// Returns version of the application currently installed on the user's PC. /// public Version InstalledVersion { get; set; } /// - /// If new update is available then returns true otherwise false. + /// If new update is available then returns true otherwise false. /// public bool IsUpdateAvailable { get; set; } /// - /// Shows if the update is required or optional. + /// Shows if the update is required or optional. /// public bool Mandatory { get; set; } @@ -71,7 +68,12 @@ namespace SteamWare /// Init classe /// public UpdateMan() - { } + { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } + } /// /// Init classe @@ -80,25 +82,16 @@ namespace SteamWare /// public UpdateMan(string user, string pwd) { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } userName = user; passwd = pwd; } #endregion Public Constructors - #region Protected Properties - - /// - /// password - /// - protected string passwd { get; set; } = ""; - /// - /// Username - /// - protected string userName { get; set; } = ""; - - #endregion Protected Properties - #region Public Methods /// @@ -150,7 +143,7 @@ namespace SteamWare //var myReader = data.Content.ReadAsStreamAsync(); if (data.StatusCode != HttpStatusCode.OK) { - logger.lg.scriviLog($"Errore in chiamata getUpdateInfo per URL {remoteUrl}: status code: {data.StatusCode}", tipoLog.INFO); + Log.Info($"Errore in chiamata getUpdateInfo per URL {remoteUrl}: status code: {data.StatusCode}", tipoLog.INFO); } else { @@ -220,7 +213,7 @@ namespace SteamWare var myReader = data.Content.ReadAsStreamAsync(); if (data.StatusCode != HttpStatusCode.OK) { - logger.lg.scriviLog($"Errore in chiamata getUpdateInfo per URL {remoteUrl}: status code: {data.StatusCode}", tipoLog.INFO); + Log.Info($"Errore in chiamata getUpdateInfo per URL {remoteUrl}: status code: {data.StatusCode}", tipoLog.INFO); } else { @@ -249,7 +242,7 @@ namespace SteamWare } catch (Exception exc) { - logger.lg.scriviLog($"Eccezione in getUpdateInfo:{Environment.NewLine}{exc}"); + Log.Error($"Eccezione in getUpdateInfo:{Environment.NewLine}{exc}"); // metto versione = 0 + errore... args.IsUpdateAvailable = false; args.CurrentVersion = new Version("0.0.0.0"); @@ -258,5 +251,25 @@ namespace SteamWare } #endregion Public Methods + + #region Protected Properties + + /// + /// password + /// + protected string passwd { get; set; } = ""; + + /// + /// Username + /// + protected string userName { get; set; } = ""; + + #endregion Protected Properties + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields } } \ No newline at end of file diff --git a/SteamWare/UserControl.cs b/SteamWare/UserControl.cs index 039a39e..970a62f 100644 --- a/SteamWare/UserControl.cs +++ b/SteamWare/UserControl.cs @@ -1,352 +1,439 @@ -using System; +using NLog; +using System; using System.Web.UI.WebControls; namespace SteamWare { - /// - /// Base class for every user control in the application, containing some common - /// behaviour and utility methods. - /// It is not meant to be be used directly. - /// - public class UserControl : System.Web.UI.UserControl - { /// - /// UID formattato con "_" + /// Base class for every user control in the application, containing some common behaviour and + /// utility methods. It is not meant to be be used directly. /// - public string uid + public class UserControl : System.Web.UI.UserControl { - get - { - return this.UniqueID.Replace("$", "_").Replace("-", "_"); - } - } - /// - /// event handler generico - /// - public event EventHandler eh_ucev; - /// - /// sollevo evento selezione - /// - protected void raiseEvent(ucEvType evType) - { - // sollevo evento nuovo valore... - if (eh_ucev != null) - { - ucEvent evento = new ucEvent(evType); - eh_ucev(this, evento); - } - } - /// - /// wrapper traduzione - /// - /// - /// - public string traduci(object lemma) - { - string answ = ""; - if (lemma != null) - { - if (lemma.ToString() != "") - { - answ = user_std.UtSn.Traduci(lemma.ToString()); - } - } - else - { - answ = "--"; - } - return answ; - } - /// - /// modalità operativa controllo - /// - public ucMode modoContr { get; set; } + #region Public Constructors - /// - /// escape dei parametri input dell'ODS - /// - /// - public static void escapeInputParam(ObjectDataSourceMethodEventArgs e) - { - // escape GENERALE!!! - for (int i = 0; i < e.InputParameters.Count; i++) - { - try + /// + /// init classe + /// + public UserControl() { - e.InputParameters[i] = e.InputParameters[i].ToString().Replace("'", "''"); + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } } - catch - { } - } - } - /// - /// indica se i caratteri vadano forzati a maiuscoli - /// - public bool forceUppercase - { - get - { - bool answ = false; - try - { - answ = memLayer.ML.CRB("forceUppercase"); - } - catch - { } - return answ; - } - } - /// - /// determina se l'utente sia abilitato a scrivere nella pagina corrente (quindi modificare e cancellare...) - /// - public bool isWriteEnabled - { - get - { - bool answ = false; - try - { - answ = devicesAuthProxy.stObj.isPageWriteEnabled(titolo); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore isWriteEnabled{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - } - /// - /// determina se l'utente sia abilitato alla pagina corrente (di base visualizzazione...) - /// - public bool isPageEnabled - { - get - { - return devicesAuthProxy.stObj.isPageEnabled(titolo); - } - } - /// - /// titolo pagina - /// - public string titolo - { - get - { - return devicesAuthProxy.getPage(Request.Url).Replace(".aspx", ""); - } - } - /// - /// evento standard agganciabile da grView x aggiunta doppio click e singolo click (x edit e select) - /// - /// - /// - protected virtual void grView_RowDataBound(object sender, GridViewRowEventArgs e) - { - GridView grView = (GridView)sender; - if (e.Row.RowType == DataControlRowType.DataRow) - { - // single click --> edit - e.Row.Attributes["ondblclick"] = Page.ClientScript.GetPostBackClientHyperlink(grView, "Edit$" + e.Row.RowIndex); - e.Row.Attributes["style"] = "cursor:pointer"; - } - } - /// - /// evento andata in editing del controllo - /// - /// - /// - protected virtual void grView_RowEditing(object sender, GridViewEditEventArgs e) - { - GridView grView = (GridView)sender; - if (grView.EditIndex >= 0) - { - grView.UpdateRow(grView.EditIndex, false); - } - } + #endregion Public Constructors - /// - /// restituisce la stringa del path corretto per l'immagine richiesta nel formato "~/images/{0}{1}" - /// - /// verrà usato x posizione {0}, tipo "view" - /// verrà usato x posizione {1}, tipo "_s.png" - /// - public string imgPath(tipoImg _tipo, dimImg _dimensione) - { - return imgPath(_tipo, _dimensione, tipoFileImg.png); - } + #region Public Events - /// - /// restituisce la stringa del path corretto per l'immagine richiesta nel formato "~/images/{0}{1}" - /// - /// verrà usato x posizione {0}, tipo "view" - /// verrà usato x posizione {1}, tipo "_s.png" - /// tipo del file richiesto..." - /// - public string imgPath(tipoImg _tipo, dimImg _dimensione, tipoFileImg _tipoFile) - { - string _imgName = "unknown"; - string _imgDim = "_s"; - string _imgType = "png"; - switch (_tipo) - { - case tipoImg.annulla: - _imgName = "cancel"; - break; - case tipoImg.approva: - _imgName = "approva"; - break; - case tipoImg.barcode: - _imgName = "barcode_white"; - break; - case tipoImg.barcodeArancio: - _imgName = "barcode_orange"; - break; - case tipoImg.clona: - _imgName = "clonaObj"; - break; - case tipoImg.conferma: - _imgName = "apply"; - break; - case tipoImg.elimina: - _imgName = "elimina"; - break; - case tipoImg.modifica: - _imgName = "edit"; - break; - case tipoImg.notepad: - _imgName = "notepad"; - break; - case tipoImg.notepadPdf: - _imgName = "notepadPdf"; - break; - case tipoImg.nuovo: - _imgName = "new"; - break; - case tipoImg.seleziona: - _imgName = "view"; - break; - case tipoImg.semaforoGiallo: - _imgName = "semaGiallo"; - break; - case tipoImg.semaforoRosso: - _imgName = "semaRosso"; - break; - case tipoImg.semaforoVerde: - _imgName = "semaVerde"; - break; - case tipoImg.stampa: - _imgName = "print"; - break; - default: - break; - } - switch (_dimensione) - { - case dimImg.small: - _imgDim = "_s"; - break; - case dimImg.medium: - _imgDim = "_m"; - break; - case dimImg.large: - _imgDim = "_l"; - break; - default: - break; - } - switch (_tipoFile) - { - case tipoFileImg.gif: - _imgType = "gif"; - break; - case tipoFileImg.jpg: - _imgType = "jpg"; - break; - case tipoFileImg.png: - _imgType = "png"; - break; - default: - break; - } - return string.Format("~/images/{0}{1}.{2}", _imgName, _imgDim, _imgType); - } - /// - /// Classe help email x SteamWare.UserControl - /// - public class email - { - /// - /// Email dell'account admin applicativo - /// - public static string adminEmail - { - get + /// + /// event handler generico + /// + public event EventHandler eh_ucev; + + #endregion Public Events + + #region Public Properties + + /// + /// indica se i caratteri vadano forzati a maiuscoli + /// + public bool forceUppercase { - return memLayer.ML.CRS("_adminEmail"); + get + { + bool answ = false; + try + { + answ = memLayer.ML.CRB("forceUppercase"); + } + catch (Exception exc) + { + Log.Error($"Eccezione forceUppercase{Environment.NewLine}{exc}"); + } + return answ; + } } - } - /// - /// Email dell'account sender applicativo - /// - public static string senderEmail - { - get - { - return memLayer.ML.CRS("_fromEmail"); - } - } - } - /// - /// Numero Righe standard - /// - public int righeDataGrid - { - get - { - return memLayer.ML.CRI("_righeDataGrid"); - } - } - /// - /// Numero Righe standard ANAGR - /// - public int righeDataGridAnagr - { - get - { - return memLayer.ML.CRI("_righeDataGridAnagr"); - } - } - /// - /// Numero Righe standard LONG - /// - public int righeDataGridLong - { - get - { - return memLayer.ML.CRI("_righeDataGridLong"); - } - } - /// - /// Numero Righe standard MED - /// - public int righeDataGridMed - { - get - { - return memLayer.ML.CRI("_righeDataGridMed"); - } - } - /// - /// Numero Righe standard SHORT - /// - public int righeDataGridShort - { - get - { - return memLayer.ML.CRI("_righeDataGridShort"); - } - } - } -} + /// + /// determina se l'utente sia abilitato alla pagina corrente (di base visualizzazione...) + /// + public bool isPageEnabled + { + get + { + return devicesAuthProxy.stObj.isPageEnabled(titolo); + } + } + + /// + /// determina se l'utente sia abilitato a scrivere nella pagina corrente (quindi modificare + /// e cancellare...) + /// + public bool isWriteEnabled + { + get + { + bool answ = false; + try + { + answ = devicesAuthProxy.stObj.isPageWriteEnabled(titolo); + } + catch (Exception exc) + { + Log.Error($"Eccezione isWriteEnabled{Environment.NewLine}{exc}"); + } + return answ; + } + } + + /// + /// modalità operativa controllo + /// + public ucMode modoContr { get; set; } + + /// + /// Numero Righe standard + /// + public int righeDataGrid + { + get + { + return memLayer.ML.CRI("_righeDataGrid"); + } + } + + /// + /// Numero Righe standard ANAGR + /// + public int righeDataGridAnagr + { + get + { + return memLayer.ML.CRI("_righeDataGridAnagr"); + } + } + + /// + /// Numero Righe standard LONG + /// + public int righeDataGridLong + { + get + { + return memLayer.ML.CRI("_righeDataGridLong"); + } + } + + /// + /// Numero Righe standard MED + /// + public int righeDataGridMed + { + get + { + return memLayer.ML.CRI("_righeDataGridMed"); + } + } + + /// + /// Numero Righe standard SHORT + /// + public int righeDataGridShort + { + get + { + return memLayer.ML.CRI("_righeDataGridShort"); + } + } + + /// + /// titolo pagina + /// + public string titolo + { + get + { + return devicesAuthProxy.getPage(Request.Url).Replace(".aspx", ""); + } + } + + /// + /// UID formattato con "_" + /// + public string uid + { + get + { + return this.UniqueID.Replace("$", "_").Replace("-", "_"); + } + } + + #endregion Public Properties + + #region Public Methods + + /// + /// escape dei parametri input dell'ODS + /// + /// + public static void escapeInputParam(ObjectDataSourceMethodEventArgs e) + { + // escape GENERALE!!! + for (int i = 0; i < e.InputParameters.Count; i++) + { + try + { + e.InputParameters[i] = e.InputParameters[i].ToString().Replace("'", "''"); + } + catch (Exception exc) + { + Log.Error($"Eccezione escapeInputParam{Environment.NewLine}{exc}"); + } + } + } + + /// + /// restituisce la stringa del path corretto per l'immagine richiesta nel formato "~/images/{0}{1}" + /// + /// verrà usato x posizione {0}, tipo "view" + /// verrà usato x posizione {1}, tipo "_s.png" + /// + public string imgPath(tipoImg _tipo, dimImg _dimensione) + { + return imgPath(_tipo, _dimensione, tipoFileImg.png); + } + + /// + /// restituisce la stringa del path corretto per l'immagine richiesta nel formato "~/images/{0}{1}" + /// + /// verrà usato x posizione {0}, tipo "view" + /// verrà usato x posizione {1}, tipo "_s.png" + /// tipo del file richiesto..." + /// + public string imgPath(tipoImg _tipo, dimImg _dimensione, tipoFileImg _tipoFile) + { + string _imgName = "unknown"; + string _imgDim = "_s"; + string _imgType = "png"; + switch (_tipo) + { + case tipoImg.annulla: + _imgName = "cancel"; + break; + + case tipoImg.approva: + _imgName = "approva"; + break; + + case tipoImg.barcode: + _imgName = "barcode_white"; + break; + + case tipoImg.barcodeArancio: + _imgName = "barcode_orange"; + break; + + case tipoImg.clona: + _imgName = "clonaObj"; + break; + + case tipoImg.conferma: + _imgName = "apply"; + break; + + case tipoImg.elimina: + _imgName = "elimina"; + break; + + case tipoImg.modifica: + _imgName = "edit"; + break; + + case tipoImg.notepad: + _imgName = "notepad"; + break; + + case tipoImg.notepadPdf: + _imgName = "notepadPdf"; + break; + + case tipoImg.nuovo: + _imgName = "new"; + break; + + case tipoImg.seleziona: + _imgName = "view"; + break; + + case tipoImg.semaforoGiallo: + _imgName = "semaGiallo"; + break; + + case tipoImg.semaforoRosso: + _imgName = "semaRosso"; + break; + + case tipoImg.semaforoVerde: + _imgName = "semaVerde"; + break; + + case tipoImg.stampa: + _imgName = "print"; + break; + + default: + break; + } + switch (_dimensione) + { + case dimImg.small: + _imgDim = "_s"; + break; + + case dimImg.medium: + _imgDim = "_m"; + break; + + case dimImg.large: + _imgDim = "_l"; + break; + + default: + break; + } + switch (_tipoFile) + { + case tipoFileImg.gif: + _imgType = "gif"; + break; + + case tipoFileImg.jpg: + _imgType = "jpg"; + break; + + case tipoFileImg.png: + _imgType = "png"; + break; + + default: + break; + } + return string.Format("~/images/{0}{1}.{2}", _imgName, _imgDim, _imgType); + } + + /// + /// wrapper traduzione + /// + /// + /// + public string traduci(object lemma) + { + string answ = ""; + if (lemma != null) + { + if (lemma.ToString() != "") + { + answ = user_std.UtSn.Traduci(lemma.ToString()); + } + } + else + { + answ = "--"; + } + return answ; + } + + #endregion Public Methods + + #region Public Classes + + /// + /// Classe help email x SteamWare.UserControl + /// + public class email + { + #region Public Properties + + /// + /// Email dell'account admin applicativo + /// + public static string adminEmail + { + get + { + return memLayer.ML.CRS("_adminEmail"); + } + } + + /// + /// Email dell'account sender applicativo + /// + public static string senderEmail + { + get + { + return memLayer.ML.CRS("_fromEmail"); + } + } + + #endregion Public Properties + } + + #endregion Public Classes + + #region Protected Methods + + /// + /// evento standard agganciabile da grView x aggiunta doppio click e singolo click (x edit e select) + /// + /// + /// + protected virtual void grView_RowDataBound(object sender, GridViewRowEventArgs e) + { + GridView grView = (GridView)sender; + if (e.Row.RowType == DataControlRowType.DataRow) + { + // single click --> edit + e.Row.Attributes["ondblclick"] = Page.ClientScript.GetPostBackClientHyperlink(grView, "Edit$" + e.Row.RowIndex); + e.Row.Attributes["style"] = "cursor:pointer"; + } + } + + /// + /// evento andata in editing del controllo + /// + /// + /// + protected virtual void grView_RowEditing(object sender, GridViewEditEventArgs e) + { + GridView grView = (GridView)sender; + if (grView.EditIndex >= 0) + { + grView.UpdateRow(grView.EditIndex, false); + } + } + + /// + /// sollevo evento selezione + /// + protected void raiseEvent(ucEvType evType) + { + // sollevo evento nuovo valore... + if (eh_ucev != null) + { + ucEvent evento = new ucEvent(evType); + eh_ucev(this, evento); + } + } + + #endregion Protected Methods + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields + } +} \ No newline at end of file diff --git a/SteamWare/dbUpdateManager.cs b/SteamWare/dbUpdateManager.cs index 25c07d6..3b6b45a 100644 --- a/SteamWare/dbUpdateManager.cs +++ b/SteamWare/dbUpdateManager.cs @@ -1,4 +1,5 @@ -using System; +using NLog; +using System; using System.Data.SqlClient; namespace SteamWare @@ -8,27 +9,17 @@ namespace SteamWare /// public class dbUpdateManager { - /// - /// oggetto connessione - /// - protected SqlConnection conn = null; - /// - /// stringa di connessione - /// - protected string _connString; - /// - /// dir che contiene gli script da eseguire... - /// - protected string _sqlScriptDir; - /// - /// formato del file SQL impiegato (nel senso di formato come iFormat del tipo "App_{0:0000}.sql" --> da App_0001.sql ad App_9999.sql) - /// - protected string _sqlFileFormat; + #region Public Constructors + /// /// avvio protected della classe /// public dbUpdateManager(string connectionString, string sqlDir, string sqlFileFormat) { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } // salvo valori di avvio _sqlFileFormat = sqlFileFormat; _connString = connectionString; @@ -40,8 +31,38 @@ namespace SteamWare { _sqlScriptDir = sqlDir; } - //logger.lg.scriviLog(_sqlScriptDir, tipoLog.INFO); } + + #endregion Public Constructors + + #region Public Methods + + /// + /// verifica se il db indicato esiste o meno... + /// + /// + /// + /// + public bool checkDbExisting(string dbname, string connectionString) + { + bool answ = false; + // !!!FARE!!! + return answ; + } + + /// + /// crea il db indicato con i parametri di connessione specificati + /// + /// + /// + /// + public bool createDb(string dbname, string connectionString) + { + bool answ = false; + // !!!FARE!!! per ora non c'è creazione ma SOLO fasi di update... + return answ; + } + /// /// esegue gli script di sql di update dal file richiesto /// @@ -61,7 +82,7 @@ namespace SteamWare // apro connessione conn.Open(); // creo e popolo comando - logger.lg.scriviLog(string.Format("Inizio esecuzione comandl SQL del file {0}", nomeFile), tipoLog.INFO); + Log.Info(string.Format("Inizio esecuzione comandl SQL del file {0}", nomeFile), tipoLog.INFO); DateTime inizio = DateTime.Now; SqlCommand comando = conn.CreateCommand(); // eseguo un comando alla volta (fino al GO...) @@ -81,13 +102,13 @@ namespace SteamWare // ricaolco posizione prox GO... i_GO = sqlCmd.IndexOf("GO\r\n"); } - logger.lg.scriviLog(string.Format("Completata esecuzione SQL {0} in {1} msec", nomeFile, DateTime.Now.Subtract(inizio).TotalMilliseconds), tipoLog.INFO); + Log.Info(string.Format("Completata esecuzione SQL {0} in {1} msec", nomeFile, DateTime.Now.Subtract(inizio).TotalMilliseconds), tipoLog.INFO); // segno come fatto answ = true; } - catch (Exception e) + catch (Exception exc) { - logger.lg.scriviLog(string.Format("Errore durante l'esecuzione SQL {0}, errore \n\r {1}", nomeFile, e), tipoLog.EXCEPTION); + Log.Error($"Eccezione durante l'esecuzione SQL {nomeFile}{Environment.NewLine}{exc}"); } finally { @@ -99,19 +120,20 @@ namespace SteamWare conn.Close(); conn.Dispose(); } - catch (Exception e) + catch (Exception exc) { - logger.lg.scriviLog(string.Format("Errore durante la chiusura della connessione, errore:\n\r {0}", e), tipoLog.EXCEPTION); + Log.Error($"Eccezione durante la chiusura della connessione{Environment.NewLine}{exc}"); } } - } return answ; } + /// /// Aggiorna il db eseguendo gli script dalla versione di partenza a quella di arrivo - /// - /// NB: per definizione rev 0 = resetta svuotando DB, rev 1 crea tabelle iniziali, rev 2 inserisce i valori di default + /// + /// NB: per definizione rev 0 = resetta svuotando DB, rev 1 crea tabelle iniziali, rev 2 + /// inserisce i valori di default /// /// nome DB di cui cercare script /// revisione di partenza @@ -128,33 +150,38 @@ namespace SteamWare } return answ; } + + #endregion Public Methods + + #region Protected Fields + /// - /// verifica se il db indicato esiste o meno... + /// stringa di connessione /// - /// - /// - /// - public bool checkDbExisting(string dbname, string connectionString) - { - bool answ = false; + protected string _connString; - // !!!FARE!!! - - return answ; - } /// - /// crea il db indicato con i parametri di connessione specificati + /// formato del file SQL impiegato (nel senso di formato come iFormat del tipo + /// "App_{0:0000}.sql" --> da App_0001.sql ad App_9999.sql) /// - /// - /// - /// - public bool createDb(string dbname, string connectionString) - { - bool answ = false; + protected string _sqlFileFormat; - // !!!FARE!!! per ora non c'è creazione ma SOLO fasi di update... + /// + /// dir che contiene gli script da eseguire... + /// + protected string _sqlScriptDir; - return answ; - } + /// + /// oggetto connessione + /// + protected SqlConnection conn = null; + + #endregion Protected Fields + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields } -} +} \ No newline at end of file diff --git a/SteamWare/devicesAuthProxy.cs b/SteamWare/devicesAuthProxy.cs index dcc79e4..b949206 100644 --- a/SteamWare/devicesAuthProxy.cs +++ b/SteamWare/devicesAuthProxy.cs @@ -1,4 +1,5 @@ -using System; +using NLog; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -6,1106 +7,1175 @@ using System.Web; namespace SteamWare { - /// - /// classe gestione auth dispositivi (new 2014) - /// - public class devicesAuthProxy - { - #region area table adapters /// - /// TableAdapter devices + /// classe gestione auth dispositivi (new 2014) /// - public DS_AuthTableAdapters.AnagDevicesTableAdapter taAnagDev; - /// - /// TableAdapter Utenti - /// - public DS_AuthTableAdapters.UtentiTableAdapter taUtenti; - /// - /// TableAdapter Diritti - /// - public DS_AuthTableAdapters.DIRITTITableAdapter taDiritti; - /// - /// TableAdapter permessi - /// - public DS_AuthTableAdapters.PermessiTableAdapter taPermessi; - /// - /// TableAdapter funzione - /// - public DS_AuthTableAdapters.FUNZIONETableAdapter taFunzione; - /// - /// TableAdapter permessi2fuzione - /// - public DS_AuthTableAdapters.Permessi2FunzioneTableAdapter taPermessi2Funzione; - - /// - /// init dei table adapters - /// - protected void initTA() + public class devicesAuthProxy { - taAnagDev = new DS_AuthTableAdapters.AnagDevicesTableAdapter(); - taUtenti = new DS_AuthTableAdapters.UtentiTableAdapter(); - taDiritti = new DS_AuthTableAdapters.DIRITTITableAdapter(); - taPermessi = new DS_AuthTableAdapters.PermessiTableAdapter(); - taFunzione = new DS_AuthTableAdapters.FUNZIONETableAdapter(); - taPermessi2Funzione = new DS_AuthTableAdapters.Permessi2FunzioneTableAdapter(); - } - /// - /// effettua setup dei connection strings da web.config delal singola applicazione - /// - protected virtual void setupConnectionStringBase() - { - // connections del db - string connString = memLayer.ML.confReadString("DevicesAuthConnectionString"); - taAnagDev.Connection.ConnectionString = connString; - taUtenti.Connection.ConnectionString = connString; - taDiritti.Connection.ConnectionString = connString; - taPermessi.Connection.ConnectionString = connString; - taFunzione.Connection.ConnectionString = connString; - taPermessi2Funzione.Connection.ConnectionString = connString; - } + #region Public Fields + /// + /// Singleton accesso a devicesAuthProxy (static object) + /// + public static devicesAuthProxy stObj = new devicesAuthProxy(); - #endregion + /// + /// TableAdapter devices + /// + public DS_AuthTableAdapters.AnagDevicesTableAdapter taAnagDev; - /* Classe che si occupa di: - * ---------------------------------------- - * 1) gestione username - * 2) gestione ruoli da anagrafica - * 3) gestione declinazione ruoli in permessi - * - * in Standard GENERICO - */ + /// + /// TableAdapter Diritti + /// + public DS_AuthTableAdapters.DIRITTITableAdapter taDiritti; + /// + /// TableAdapter funzione + /// + public DS_AuthTableAdapters.FUNZIONETableAdapter taFunzione; + /// + /// TableAdapter permessi + /// + public DS_AuthTableAdapters.PermessiTableAdapter taPermessi; - /// - /// Initializes a new instance of the class. - /// - protected devicesAuthProxy() - { - initTA(); - setupConnectionStringBase(); - } - /// - /// Singleton accesso a devicesAuthProxy (static object) - /// - public static devicesAuthProxy stObj = new devicesAuthProxy(); + /// + /// TableAdapter permessi2fuzione + /// + public DS_AuthTableAdapters.Permessi2FunzioneTableAdapter taPermessi2Funzione; - #region metodi verifica authKey, email, ... + /// + /// TableAdapter Utenti + /// + public DS_AuthTableAdapters.UtentiTableAdapter taUtenti; - /// - /// cifra in MD5 la stringa in chiaro - /// - /// - /// - public static string encodeKey(string chiaro) - { - string answ = chiaro; - try - { - answ = SteamCrypto.EncryptString(chiaro, memLayer.ML.CRS("CodModulo")); - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// decifra la stringa MD5 in chiaro - /// - /// - /// - public static string decodeKey(string cifrato) - { - string answ = cifrato; - try - { - answ = SteamCrypto.DecryptString(cifrato, memLayer.ML.CRS("CodModulo")); - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// verifica una email per appartenenza ad un utente VALIDO dell'elenco - /// - /// - /// - public bool checkUserEmail(string email) - { - bool answ = false; - try - { - answ = taUtenti.getByEmail(email).Rows.Count > 0; - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore check user email: {0}", exc), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// verifica una email + AuthKey per appartenenza ad un utente VALIDO dell'elenco - /// - /// - /// - /// - public bool checkUserEmailAK(string email, string AuthKey) - { - bool answ = false; - int trovati = 0; - if (email != "" && AuthKey != "") - { - string md5UserAuthKey = encodeKey(AuthKey); - try + #endregion Public Fields + + #region Public Properties + + /// + /// restituisce nome cookie di auth (o default...) + /// + public static string AuthCookieName { - trovati += taUtenti.getByEmailAK(email, md5UserAuthKey).Rows.Count; - // se abilitato anche plain controlla pure li... - if (memLayer.ML.CRB("enablePlain")) - { - trovati += taUtenti.getByEmailAK(email, AuthKey).Rows.Count; - } - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - answ = trovati > 0; - } - return answ; - } - /// - /// registra su DB la richiesta di reset della auth key dell'utente ed opzionalmente invia email ad admin - /// - /// - /// opzionale, se != "" invia email all'indirizzo dell'admin x reset - public void reqResetAuthKey(string email, string adminEmail) - { - // registro richiesta di reset KEY... - taUtenti.reqAuthKeyReset(email); - - // se ho email admin... - if (adminEmail != "") - { - // mando email ad admin x reset utente... - string oggetto = string.Format("L'utente {0} ha richiesto il reset della sua AuthKey.

Seguire il link seguente per approvare o rifiutare la richiesta", email, memLayer.ML.CRS("baseUrl"), memLayer.ML.CRS("urlGestUtenti")); - gestEmail.geAuth.mandaEmail(email, adminEmail, "Richiesta reset AuthKey utente", oggetto); - } - } - /// - /// invia email ad utente con url x reset hash password - /// - /// destinatario - /// hashPasswd ATTUALE (in chiaro) - /// - public void sendEmailResetHashPassword(string email, string hashPasswd, string webAppName) - { - // se ho email admin... - if (email != "") - { - // calcolo chiave MD5... - string md5hashPasswd = encodeKey(hashPasswd); - // mando email ad admin x reset utente... - string oggetto = string.Format("Hi,

This is an automatic message generated by {3} platform on behalf of platform admin.

Please click on following link (or cut/paste to your preferred browser) to reset your password to {3} login.

Regards.", memLayer.ML.CRS("baseUrl"), HttpUtility.UrlEncode(md5hashPasswd), email, webAppName); - gestEmail.geAuth.mandaEmail(memLayer.ML.CRS("_fromEmail"), email, webAppName, oggetto); - } - } - /// - /// invia email ad utente con url x enroll - /// - /// - /// chiave (in chiaro) - /// nome del sito - public void sendEmailAuthKey(string email, string AuthKey, string SiteName) - { - string body = "Hi,

This is an automatic message generated by {3} platform on behalf of platform admin.

Please click on following link (or cut/paste to your preferred browser) to enable current device to {3} login.

Regards."; - string subject = string.Format("AUTH access to {0}", SiteName); - sendEmailAuthKey(email, AuthKey, SiteName, subject, body); - } - /// - /// invia email ad utente con url x enroll (utilizzando il parametro baseURL x il sito) - /// - /// - /// chiave (in chiaro) - /// nome del sito - /// chiave (in chiaro) - /// body (in formato da completare string.format con 4 parametri che verrano inseriti come i seguenti: - /// {0} = baseURL - memLayer.ML.CRS("baseUrl") - /// {1} = chaive encoded - HttpUtility.UrlEncode(md5UserAuthKey) - /// {2} = email destinatario - /// {3} = subject - /// {4} = site name - /// - public void sendEmailAuthKey(string email, string AuthKey, string SiteName, string subject, string body) - { - // se ho email admin... - if (email != "") - { - // calcolo chiave MD5... - string md5UserAuthKey = encodeKey(AuthKey); - // mando email ad admin x reset utente... - string oggetto = string.Format(body, memLayer.ML.CRS("baseUrl"), HttpUtility.UrlEncode(md5UserAuthKey), email, SiteName); - gestEmail.geAuth.mandaEmail(memLayer.ML.CRS("_fromEmail"), email, subject, oggetto); - } - } - /// - /// numero massimo auth concesse (se non trovo su conf prendo 1000) - /// - protected int maxAuth - { - get - { - int answ = memLayer.ML.CRI("maxAuth"); - if (answ < 0) - { - answ = 1000; - } - - return answ; - } - } - /// - /// effettua enroll del device x l'utente con l'email indicata - /// - /// - /// - /// - /// - /// - /// - public bool enrollDevice(string UserAuthKey, string IPv4, string DeviceName, string Description, string email) - { - bool fatto = false; - if (numAuth(UserAuthKey, email) > 0) - { - // calcolo il secret... - DateTime adesso = DateTime.Now; - string Secret = string.Format("{0}|{1}|{2}", email, DeviceName, adesso); - string devSecret = SteamCrypto.EncryptString(Secret, passphrase(memLayer.ML.confReadString("CodModulo"), UserAuthKey)); - try - { - // registro chiave x il device - taAnagDev.Insert(devSecret, email, DeviceName, Description, adesso, adesso, IPv4); - // se condizione NORMALE (ovvero numAuth < maxAuth, altrimenti NON consuma...) - if (numAuth(UserAuthKey, email) <= maxAuth) - { - // registro "consumo" della authKey (-1 numAuth) - taUtenti.recordAuthKeyUse(email); - } - // salvo il cookie nel browser x 2 anni - memLayer.ML.setCookieVal(AuthCookieName, devSecret, DateTime.Now.AddYears(2)); - // indico come fatto - fatto = true; - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Eccezione in fase di enroll devices: parametri{0}UserAuthKey: {1}{0}IPv4: {2}{0}DeviceName: {3}{0}devSecret: {4}{0}email: {5}{0}Description: {6}{0}adesso: {7}{0}eccezione: {8}{0}", Environment.NewLine, UserAuthKey, IPv4, DeviceName, devSecret, email, Description, adesso, exc), tipoLog.EXCEPTION); - } - } - //esce... - return fatto; - } - /// - /// restituisce nome cookie di auth (o default...) - /// - public static string AuthCookieName - { - get - { - string answ = "AuthDevice"; - try - { - answ = memLayer.ML.CRS("AuthCookieName"); - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - return answ; - } - } - /// - /// genera la passphrase utente a partire dai parametri richiesti - /// - /// - /// - /// - public string passphrase(string CodMod, string userKey) - { - return string.Format("{0}#{1}", CodMod, userKey); - } - /// - /// Restituisce il numero di attivazioni rimaste x utente dato email e key - /// - /// - /// - /// - public int numAuth(string UserAuthKey, string email) - { - DS_Auth.UtentiRow rowUtenti; - int numAuth = 0; - try - { - // decodifica al volo la cifra... - rowUtenti = taUtenti.getByEmailAK(email, UserAuthKey)[0]; - numAuth = rowUtenti.numAuth; - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - // ritorno - return numAuth; - } - /// - /// Restituisce il numero di attivazioni rimaste x utente dato email - /// - /// - /// - public int numAuth(string email) - { - DS_Auth.UtentiRow rowUtenti; - int numAuth = 0; - try - { - // decodifica al volo la cifra... - rowUtenti = taUtenti.getByEmail(email)[0]; - numAuth = rowUtenti.numAuth; - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - // ritorno - return numAuth; - } - /// - /// Generazione stringa casuale di caratteri... - /// - /// - /// - /// - public static string RandomString(int size, bool lowerCase) - { - StringBuilder builder = new StringBuilder(); - Random random = new Random(); - char ch; - for (int i = 0; i < size; i++) - { - ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); - builder.Append(ch); - } - if (lowerCase) - return builder.ToString().ToLower(); - return builder.ToString(); - } - - /// - /// verifica la presenza di un cookie VALIDO per autorizzare il device e se lo trova avvia utente IN SESSIONE... - /// - public bool checkAuthCookie() - { - bool answ = false; - try - { - HttpCookie cookie = HttpContext.Current.Request.Cookies[AuthCookieName]; - if (!(cookie == null || cookie.Value == "")) - { - // ricavo utente da cookie... - string userAgent = ""; - string postazione_IP = ""; - string devSecret = cookie.Value; - DS_Auth.AnagDevicesRow device = null; - // cerco il device...ogni dipendente può averne + di 1 registrato a suo nome... - string email = ""; - try - { - device = taAnagDev.getByDeviceSecret(devSecret)[0]; - email = device.USER_NAME; - } - catch - { } - if (email != "") - { - // aggiorno descrizione (user agent) ed IP... - userAgent = HttpContext.Current.Request.UserAgent; - postazione_IP = HttpContext.Current.Request.UserHostAddress; - // controllo IP e DeviceDescription x eventuale update - if ((device.lastIPv4 != postazione_IP) || (device.Description != userAgent)) + get { - // salvo ultimo "contatto" del device aggiornando descrizione ed IP - taAnagDev.updateIP(device.IdxDevice, DateTime.Now, postazione_IP, userAgent); + string answ = "AuthDevice"; + try + { + answ = memLayer.ML.CRS("AuthCookieName"); + } + catch (Exception exc) + { + Log.Error($"Eccezione in recupero AuthCookieName {Environment.NewLine}{exc}"); + } + return answ; } - // salvo in sessione utente - memLayer.ML.setSessionVal("email", email); - // avvio utente... - startUpUtente(email); - // salvo gruppo... - if (isAuth) + } + + /// + /// pagina correntemente visualizzata (URL in sessione) + /// + public static string pagCorrente + { + get { - // se tutto ok - memLayer.ML.setSessionVal("Gruppo", rigaUtente.CodGruppo); - answ = true; + return memLayer.ML.StringSessionObj("pagCorrente"); } - } - } - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in checkAuthCookie:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return answ; - } - - #endregion - - #region area utente - - /// - /// cancella da session l'utente - /// - public void clearAllUserData() - { - memLayer.ML.emptySessionVal("USER_NAME"); - memLayer.ML.emptySessionVal("email"); - memLayer.ML.emptySessionVal("dirittiUtente"); - memLayer.ML.emptySessionVal("permessiUtente"); - memLayer.ML.emptySessionVal("permessiUtenteWrite"); - memLayer.ML.emptySessionVal("rigaUtente"); - } - /// - /// restituisce la tabella diritti da session - /// - public DS_Auth.DIRITTIDataTable diritti - { - get - { - if (memLayer.ML.serializeSession) - { - return DataSetAdapter.convert(memLayer.ML.dsSessionObj("dirittiUtente")); - } - else - { - return (DS_Auth.DIRITTIDataTable)memLayer.ML.objSessionObj("dirittiUtente"); - } - } - set - { - if (memLayer.ML.serializeSession) - { - memLayer.ML.setSessionDataTable("dirittiUtente", value); - } - else - { - memLayer.ML.setSessionVal("dirittiUtente", value); - } - } - } - /// - /// tabella dei permessi utente - /// - public DS_Auth.PermessiDataTable permessi - { - get - { - DS_Auth.PermessiDataTable tabPermessi = null; - try - { - if (memLayer.ML.serializeSession) - { - tabPermessi = DataSetAdapter.convert(memLayer.ML.dsSessionObj("permessiUtente")); - } - else - { - tabPermessi = (DS_Auth.PermessiDataTable)memLayer.ML.objSessionObj("permessiUtente"); - } - } - catch (Exception exc) - { - logger.lg.scriviLog(String.Format("Errore recupero permessi!{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return tabPermessi; - } - set - { - if (memLayer.ML.serializeSession) - { - memLayer.ML.setSessionDataTable("permessiUtente", value); - } - else - { - memLayer.ML.setSessionVal("permessiUtente", value); - } - } - } - /// - /// tabella dei permessi utente di tipo "WRITE" enabled - /// - public DS_Auth.PermessiDataTable permessiWrite - { - get - { - if (memLayer.ML.serializeSession) - { - return DataSetAdapter.convert(memLayer.ML.dsSessionObj("permessiUtenteWrite")); - } - else - { - return (DS_Auth.PermessiDataTable)memLayer.ML.objSessionObj("permessiUtenteWrite"); - } - } - set - { - if (memLayer.ML.serializeSession) - { - memLayer.ML.setSessionDataTable("permessiUtenteWrite", value); - } - else - { - memLayer.ML.setSessionVal("permessiUtenteWrite", value); - } - } - } - /// - /// oggetto utente con metodi get/set - /// - public string utente - { - get - { - return memLayer.ML.StringSessionObj("USER_NAME"); - } - set - { - memLayer.ML.setSessionVal("USER_NAME", value, true); - } - } - /// - /// oggetto email con metodi get/set - /// - public string email - { - get - { - return memLayer.ML.StringSessionObj("email"); - } - set - { - memLayer.ML.setSessionVal("email", value, true); - } - } - /// - /// oggetto DeviceSecret IN SESSIONE con metodi get/set - /// - public string DeviceSecret - { - get - { - return memLayer.ML.getCookieVal(AuthCookieName); - } - } - /// - /// oggetto modulo IN SESSIONE con metodi get/set - /// - public string modulo - { - get - { - return memLayer.ML.CRS("CodModulo"); - } - } - /// - /// restituisce i valori della riga utente da db - /// - public DS_Auth.UtentiRow rigaUtente - { - get - { - if (memLayer.ML.serializeSession) - { - DS_Auth.UtentiDataTable table = DataSetAdapter.convert(memLayer.ML.dsSessionObj("rigaUtente")); - return table[0]; - } - else - { - return (DS_Auth.UtentiRow)memLayer.ML.objSessionObj("rigaUtente"); - } - } - set - { - if (memLayer.ML.serializeSession) - { - memLayer.ML.setSessionDataTable("rigaUtente", value.Table); - } - else - { - memLayer.ML.setSessionVal("rigaUtente", value); - } - } - } - /// - /// restituisce una stringa formattata con cognome e nome - /// - public string CognomeNome - { - get - { - string answ = ""; - if (isAuth) - { - answ = string.Format("{0} {1}", rigaUtente.cognome, rigaUtente.nome); - } - return answ; - } - } - /// - /// è un boolean che indica se in session ci siano user/email e DeviceSecret (cookie) e quindi utente autenticato in precedenza... - /// - public bool isAuth - { - get - { - return ((utente != "" || email != "") && DeviceSecret != ""); - } - } - /// - /// conta il numero di permessi utente per la pagina attuale e restituisce true se ne trova almeno 1 - /// - /// - /// - public bool isPageEnabled(string pagina) - { - bool answ = false; - try - { - if (permessi != null) - { - // verifico ANCHE se ci sia una versione ".aspx" in +... - System.Data.DataRow[] righe = permessi.Select(string.Format("URL = '{0}.aspx' OR URL = '{0}'", pagina)); - answ = (righe.Length >= 1); - } - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Verifica se l'utente sia noto al sistema... - /// - /// - /// - public bool userIsKnown(string _username) - { - bool answ = false; - try - { - answ = taUtenti.getByEmail(_username).Rows.Count > 0; - } - catch - { } - return answ; - } - /// - /// conta il numero di permessi utente per la pagina attuale e restituisce true se ne trova almeno 1 - /// - /// - /// - public bool isPageSafe(string pagina) - { - bool answ = false; - try - { - string _safePages = memLayer.ML.CRS("_safePages"); - answ = (_safePages.IndexOf(pagina) >= 0); - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - return answ; - } - - /// - /// verifica se il permesso utente per la pagina attuale sia write per almeno 1 diritto assegnato (restituisce true se ne trova almeno 1 con permessi2funzione.readwrite='S') - /// - /// - /// - public bool isPageWriteEnabled(string pagina) - { - bool answ = false; - try - { - if (permessiWrite != null) - { - System.Data.DataRow[] righe = permessiWrite.Select(string.Format("URL = '{0}.aspx' OR URL = '{0}'", pagina)); - answ = (righe.Length >= 1); - } - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - return answ; - } - /// - /// Procedura da chiamare DOPO aver messo in session i dati utente/email x caricare gli altri dati - /// - /// - /// - public bool startUpUtente(string _username) - { - bool risultato = false; - try - { - clearAllUserData(); - if (_username != "") - { - utente = _username; - email = _username; // !!!HARD CODED, user = email... - setupRiga(); - setupDirittiPermessi(); - setupMappaSito(); - setupLingua(); - risultato = true; - } - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in fase di startUpUtente:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - return risultato; - } - /// - /// costruisce la mappa del sito per l'utente - /// - protected virtual void setupMappaSito() - { - string _mappa = ""; - _mappa += ""; - try - { - // partiamo dai permessi utente di numero "0" (sono intestazioni menù...) - DS_Auth.PermessiRow[] vociMenu = (DS_Auth.PermessiRow[])permessi.Select("NUMERO ='0'", "GRUPPO"); - foreach (DS_Auth.PermessiRow voce in vociMenu) - { - _mappa += formattaNodo(voce.NOME, voce.DESCRIZIONE, voce.URL, siteNodeType.startContainer); - // per ogni livello riempiamo con i permessi figli - DS_Auth.PermessiRow[] pagine = (DS_Auth.PermessiRow[])permessi.Select(string.Format("GRUPPO ='{0}' AND NUMERO > 0", voce.GRUPPO), "NUMERO"); - foreach (DS_Auth.PermessiRow pagina in pagine) - { - _mappa += formattaNodo(pagina.NOME, pagina.DESCRIZIONE, pagina.URL, siteNodeType.leaf); - } - _mappa += formattaNodo(voce.NOME, voce.DESCRIZIONE, voce.URL, siteNodeType.endContainer); - } - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - // salva in session... - _mappa += ""; - mappaSito = _mappa; - } - /// - /// formatta un nodo in modo corretto dai dati indicati - /// - /// - /// - /// - /// - protected string formattaNodo(string titolo, string descrizione, string url, siteNodeType tipoNodo) - { - string _out = ""; - switch (tipoNodo) - { - case siteNodeType.startContainer: - _out = string.Format("", traduci(titolo), traduci(descrizione), url); - break; - case siteNodeType.endContainer: - _out = ""; - break; - case siteNodeType.leaf: - _out = string.Format("", traduci(titolo), traduci(descrizione), url); - break; - } - return _out; - } - - /// - /// ricarica e ri-traduce la mappa sito per l'utente... - /// - public void ricaricaMappaSito() - { - memLayer.ML.emptySessionVal("dirittiUtente"); - memLayer.ML.emptySessionVal("permessiUtente"); - setupDirittiPermessi(); - setupMappaSito(); - } - /// - /// wrapper traduzione - /// - /// - /// - public string traduci(object lemma) - { - string answ = ""; - if (lemma != null) - { - if (lemma.ToString() != "") - { - answ = user_std.UtSn.Traduci(lemma.ToString()); - } - } - else - { - answ = "--"; - } - return answ; - } - - /// - /// carica la riga dati utente - /// - protected virtual void setupRiga() - { - try - { - rigaUtente = ((DS_Auth.UtentiRow)taUtenti.getByEmail(email).Rows[0]); - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - } - /// - /// Carica la tabella diritti dell'utente da db e salva in session - /// - protected virtual void setupDirittiPermessi() - { - try - { - diritti = taDiritti.getByUserModulo(utente, modulo); // salvo in session i diritti.. - if (diritti.Count > 0) - { - setPermessiDaDiritti(); - } - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in fase di setupDirittiPermessi:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - } - /// - /// Effettua setup dei permessi una volta salvati i diritti - /// - protected virtual void setPermessiDaDiritti() - { - // proseguo coi permessi - DS_Auth.PermessiDataTable allPermessi = taPermessi.GetData(); - DS_Auth.Permessi2FunzioneDataTable allPerm2Funz = taPermessi2Funzione.GetData(); - DS_Auth.PermessiDataTable _permessiUtente = new DS_Auth.PermessiDataTable(); - DS_Auth.PermessiDataTable _permessiUtenteWrite = new DS_Auth.PermessiDataTable(); - string filtroFunz, filtroPerm, filtroPermWrite; - filtroPerm = " COD_PERMESSO IN ("; - filtroPermWrite = " COD_PERMESSO IN ("; - // filtro i diritti utente x non avere duplicati... - Dictionary funzioniUtente = new Dictionary(); - foreach (DS_Auth.DIRITTIRow riga in diritti) - { - try - { - funzioniUtente.Add(riga.COD_FUNZIONE, riga.COD_FUNZIONE); - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - } - foreach (KeyValuePair kvp in funzioniUtente) - { - filtroFunz = string.Format("COD_FUNZIONE='{0}'", kvp.Value); - // recupero le righe dei righe2perm - DS_Auth.Permessi2FunzioneRow[] righe_p2f = (DS_Auth.Permessi2FunzioneRow[])allPerm2Funz.Select(filtroFunz); - foreach (DS_Auth.Permessi2FunzioneRow riga_p2f in righe_p2f) - { - filtroPerm += string.Format("'{0}', ", riga_p2f.COD_PERMESSO); - // se è write metto in tab relativa... - try - { - if (riga_p2f.READWRITE == "S") + set { - filtroPermWrite += string.Format("'{0}', ", riga_p2f.COD_PERMESSO); + memLayer.ML.setSessionVal("pagCorrente", value); } - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } } - } - if (filtroPerm == " COD_PERMESSO IN (") - { - filtroPerm += "'PermessiNonTrovati' "; - } - filtroPerm = filtroPerm.Remove(filtroPerm.Length - 2); - filtroPerm += ") "; - DS_Auth.PermessiRow[] righePerm = (DS_Auth.PermessiRow[])allPermessi.Select(filtroPerm, "GRUPPO, NUMERO"); - foreach (DS_Auth.PermessiRow rigaPerm in righePerm) - { - _permessiUtente.ImportRow(rigaPerm); - } - permessi = _permessiUtente; - // salvo, se ci sono, permessi write... - if (filtroPermWrite != " COD_PERMESSO IN (") - { - filtroPermWrite = filtroPermWrite.Remove(filtroPermWrite.Length - 2); - filtroPermWrite += ") "; - DS_Auth.PermessiRow[] righePermW = (DS_Auth.PermessiRow[])allPermessi.Select(filtroPermWrite, "GRUPPO, NUMERO"); - foreach (DS_Auth.PermessiRow rigaPerm in righePermW) + + /// + /// pagina precedentemente visualizzata (URL in sessione) + /// + public static string pagPrecedente { - _permessiUtenteWrite.ImportRow(rigaPerm); + get + { + return memLayer.ML.StringSessionObj("pagPrecedente"); + } + set + { + memLayer.ML.setSessionVal("pagPrecedente", value); + } } - } - permessiWrite = _permessiUtenteWrite; - } - /// - /// verifica nella tab diritti se l'utente abbia il right richiesto e fornisce bool in risposta - /// - /// - /// - public bool userHasRight(string diritto) - { - bool _answ = false; - try - { - if (diritti != null) + + /// + /// restituisce una stringa formattata con cognome e nome + /// + public string CognomeNome { - if (diritti.Select(String.Format("COD_FUNZIONE ='{0}'", diritto)).Length > 0) - { - _answ = true; - } + get + { + string answ = ""; + if (isAuth) + { + answ = string.Format("{0} {1}", rigaUtente.cognome, rigaUtente.nome); + } + return answ; + } } - } - catch (Exception exc) - { - logger.lg.scriviLog("userHasRight " + exc.ToString(), tipoLog.EXCEPTION); - } - return _answ; - } - /// - /// imposta la lingua utente dal valore della riga DB - /// - protected virtual void setupLingua() - { - string _lingua = ""; - try - { - _lingua = rigaUtente.CodGruppo; - // se contiene "#" prendo primo dei 2 come codice... - if (_lingua.IndexOf("#") >= 0) + + /// + /// oggetto DeviceSecret IN SESSIONE con metodi get/set + /// + public string DeviceSecret { - string[] dati = _lingua.Split('#'); - _lingua = dati[0]; + get + { + return memLayer.ML.getCookieVal(AuthCookieName); + } } - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - if (string.IsNullOrEmpty(_lingua)) - { - _lingua = "EN"; - } - lingua = _lingua; + /// + /// restituisce la tabella diritti da session + /// + public DS_Auth.DIRITTIDataTable diritti + { + get + { + if (memLayer.ML.serializeSession) + { + return DataSetAdapter.convert(memLayer.ML.dsSessionObj("dirittiUtente")); + } + else + { + return (DS_Auth.DIRITTIDataTable)memLayer.ML.objSessionObj("dirittiUtente"); + } + } + set + { + if (memLayer.ML.serializeSession) + { + memLayer.ML.setSessionDataTable("dirittiUtente", value); + } + else + { + memLayer.ML.setSessionVal("dirittiUtente", value); + } + } + } + + /// + /// oggetto email con metodi get/set + /// + public string email + { + get + { + return memLayer.ML.StringSessionObj("email"); + } + set + { + memLayer.ML.setSessionVal("email", value, true); + } + } + + /// + /// è un boolean che indica se in session ci siano user/email e DeviceSecret (cookie) e + /// quindi utente autenticato in precedenza... + /// + public bool isAuth + { + get + { + return ((utente != "" || email != "") && DeviceSecret != ""); + } + } + + /// + /// oggetto lingua utente con metodi get/set + /// + public string lingua + { + get + { + return memLayer.ML.StringSessionObj("Lingua").ToUpper(); + } + set + { + memLayer.ML.setSessionVal("Lingua", value); + } + } + + /// + /// fornisce un file XML della mappa del sito abilitato per l'utente... + /// + public string mappaSito + { + get + { + return memLayer.ML.StringSessionObj("mappaSito"); + } + set + { + memLayer.ML.setSessionVal("mappaSito", value); + } + } + + /// + /// oggetto modulo IN SESSIONE con metodi get/set + /// + public string modulo + { + get + { + return memLayer.ML.CRS("CodModulo"); + } + } + + /// + /// tabella dei permessi utente + /// + public DS_Auth.PermessiDataTable permessi + { + get + { + DS_Auth.PermessiDataTable tabPermessi = null; + try + { + if (memLayer.ML.serializeSession) + { + tabPermessi = DataSetAdapter.convert(memLayer.ML.dsSessionObj("permessiUtente")); + } + else + { + tabPermessi = (DS_Auth.PermessiDataTable)memLayer.ML.objSessionObj("permessiUtente"); + } + } + catch (Exception exc) + { + Log.Error($"Errore recupero permessi!{Environment.NewLine}{exc}"); + } + return tabPermessi; + } + set + { + if (memLayer.ML.serializeSession) + { + memLayer.ML.setSessionDataTable("permessiUtente", value); + } + else + { + memLayer.ML.setSessionVal("permessiUtente", value); + } + } + } + + /// + /// tabella dei permessi utente di tipo "WRITE" enabled + /// + public DS_Auth.PermessiDataTable permessiWrite + { + get + { + if (memLayer.ML.serializeSession) + { + return DataSetAdapter.convert(memLayer.ML.dsSessionObj("permessiUtenteWrite")); + } + else + { + return (DS_Auth.PermessiDataTable)memLayer.ML.objSessionObj("permessiUtenteWrite"); + } + } + set + { + if (memLayer.ML.serializeSession) + { + memLayer.ML.setSessionDataTable("permessiUtenteWrite", value); + } + else + { + memLayer.ML.setSessionVal("permessiUtenteWrite", value); + } + } + } + + /// + /// restituisce i valori della riga utente da db + /// + public DS_Auth.UtentiRow rigaUtente + { + get + { + if (memLayer.ML.serializeSession) + { + DS_Auth.UtentiDataTable table = DataSetAdapter.convert(memLayer.ML.dsSessionObj("rigaUtente")); + return table[0]; + } + else + { + return (DS_Auth.UtentiRow)memLayer.ML.objSessionObj("rigaUtente"); + } + } + set + { + if (memLayer.ML.serializeSession) + { + memLayer.ML.setSessionDataTable("rigaUtente", value.Table); + } + else + { + memLayer.ML.setSessionVal("rigaUtente", value); + } + } + } + + /// + /// oggetto utente con metodi get/set + /// + public string utente + { + get + { + return memLayer.ML.StringSessionObj("USER_NAME"); + } + set + { + memLayer.ML.setSessionVal("USER_NAME", value, true); + } + } + + #endregion Public Properties + + #region Public Methods + + /// + /// decifra la stringa MD5 in chiaro + /// + /// + /// + public static string decodeKey(string cifrato) + { + string answ = cifrato; + try + { + answ = SteamCrypto.DecryptString(cifrato, memLayer.ML.CRS("CodModulo")); + } + catch (Exception exc) + { + Log.Error($"Eccezione decodeKey{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// cifra in MD5 la stringa in chiaro + /// + /// + /// + public static string encodeKey(string chiaro) + { + string answ = chiaro; + try + { + answ = SteamCrypto.EncryptString(chiaro, memLayer.ML.CRS("CodModulo")); + } + catch (Exception exc) + { + Log.Error($"Eccezione encodeKey{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// restituisce il nome della pagina corrente + /// + public static string getPage(Uri MyUrl) + { + string answ = ""; + try + { + answ = MyUrl.LocalPath.Split('/').Last(); + } + catch (Exception exc) + { + Log.Error($"Eccezione getPage{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// Generazione stringa casuale di caratteri... + /// + /// + /// + /// + public static string RandomString(int size, bool lowerCase) + { + StringBuilder builder = new StringBuilder(); + Random random = new Random(); + char ch; + for (int i = 0; i < size; i++) + { + ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); + builder.Append(ch); + } + if (lowerCase) + return builder.ToString().ToLower(); + return builder.ToString(); + } + + /// + /// verifica la presenza di un cookie VALIDO per autorizzare il device e se lo trova avvia + /// utente IN SESSIONE... + /// + public bool checkAuthCookie() + { + bool answ = false; + try + { + HttpCookie cookie = HttpContext.Current.Request.Cookies[AuthCookieName]; + if (!(cookie == null || cookie.Value == "")) + { + // ricavo utente da cookie... + string userAgent = ""; + string postazione_IP = ""; + string devSecret = cookie.Value; + DS_Auth.AnagDevicesRow device = null; + // cerco il device...ogni dipendente può averne + di 1 registrato a suo nome... + string email = ""; + try + { + device = taAnagDev.getByDeviceSecret(devSecret)[0]; + email = device.USER_NAME; + } + catch + { } + if (email != "") + { + // aggiorno descrizione (user agent) ed IP... + userAgent = HttpContext.Current.Request.UserAgent; + postazione_IP = HttpContext.Current.Request.UserHostAddress; + // controllo IP e DeviceDescription x eventuale update + if ((device.lastIPv4 != postazione_IP) || (device.Description != userAgent)) + { + // salvo ultimo "contatto" del device aggiornando descrizione ed IP + taAnagDev.updateIP(device.IdxDevice, DateTime.Now, postazione_IP, userAgent); + } + // salvo in sessione utente + memLayer.ML.setSessionVal("email", email); + // avvio utente... + startUpUtente(email); + // salvo gruppo... + if (isAuth) + { + // se tutto ok + memLayer.ML.setSessionVal("Gruppo", rigaUtente.CodGruppo); + answ = true; + } + } + } + } + catch (Exception exc) + { + Log.Error($"Eccezione checkAuthCookie{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// verifica una email per appartenenza ad un utente VALIDO dell'elenco + /// + /// + /// + public bool checkUserEmail(string email) + { + bool answ = false; + try + { + answ = taUtenti.getByEmail(email).Rows.Count > 0; + } + catch (Exception exc) + { + Log.Error($"Eccezione checkUserEmail{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// verifica una email + AuthKey per appartenenza ad un utente VALIDO dell'elenco + /// + /// + /// + /// + public bool checkUserEmailAK(string email, string AuthKey) + { + bool answ = false; + int trovati = 0; + if (email != "" && AuthKey != "") + { + string md5UserAuthKey = encodeKey(AuthKey); + try + { + trovati += taUtenti.getByEmailAK(email, md5UserAuthKey).Rows.Count; + // se abilitato anche plain controlla pure li... + if (memLayer.ML.CRB("enablePlain")) + { + trovati += taUtenti.getByEmailAK(email, AuthKey).Rows.Count; + } + } + catch (Exception exc) + { + Log.Error($"Eccezione checkUserEmailAK{Environment.NewLine}{exc}"); + } + answ = trovati > 0; + } + return answ; + } + + /// + /// cancella da session l'utente + /// + public void clearAllUserData() + { + memLayer.ML.emptySessionVal("USER_NAME"); + memLayer.ML.emptySessionVal("email"); + memLayer.ML.emptySessionVal("dirittiUtente"); + memLayer.ML.emptySessionVal("permessiUtente"); + memLayer.ML.emptySessionVal("permessiUtenteWrite"); + memLayer.ML.emptySessionVal("rigaUtente"); + } + + /// + /// effettua enroll del device x l'utente con l'email indicata + /// + /// + /// + /// + /// + /// + /// + public bool enrollDevice(string UserAuthKey, string IPv4, string DeviceName, string Description, string email) + { + bool fatto = false; + if (numAuth(UserAuthKey, email) > 0) + { + // calcolo il secret... + DateTime adesso = DateTime.Now; + string Secret = string.Format("{0}|{1}|{2}", email, DeviceName, adesso); + string devSecret = SteamCrypto.EncryptString(Secret, passphrase(memLayer.ML.confReadString("CodModulo"), UserAuthKey)); + try + { + // registro chiave x il device + taAnagDev.Insert(devSecret, email, DeviceName, Description, adesso, adesso, IPv4); + // se condizione NORMALE (ovvero numAuth < maxAuth, altrimenti NON consuma...) + if (numAuth(UserAuthKey, email) <= maxAuth) + { + // registro "consumo" della authKey (-1 numAuth) + taUtenti.recordAuthKeyUse(email); + } + // salvo il cookie nel browser x 2 anni + memLayer.ML.setCookieVal(AuthCookieName, devSecret, DateTime.Now.AddYears(2)); + // indico come fatto + fatto = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione enroll devices | UAK: {UserAuthKey} | IP {IPv4} | Dev {DeviceName} | Sec {devSecret} | email {email}{Environment.NewLine}{exc}"); + } + } + //esce... + return fatto; + } + + /// + /// conta il numero di permessi utente per la pagina attuale e restituisce true se ne trova + /// almeno 1 + /// + /// + /// + public bool isPageEnabled(string pagina) + { + bool answ = false; + try + { + if (permessi != null) + { + // verifico ANCHE se ci sia una versione ".aspx" in +... + System.Data.DataRow[] righe = permessi.Select(string.Format("URL = '{0}.aspx' OR URL = '{0}'", pagina)); + answ = (righe.Length >= 1); + } + } + catch (Exception exc) + { + Log.Error($"Eccezione isPageEnabled{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// conta il numero di permessi utente per la pagina attuale e restituisce true se ne trova + /// almeno 1 + /// + /// + /// + public bool isPageSafe(string pagina) + { + bool answ = false; + try + { + string _safePages = memLayer.ML.CRS("_safePages"); + answ = (_safePages.IndexOf(pagina) >= 0); + } + catch (Exception exc) + { + Log.Error($"Eccezione isPageSafe{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// verifica se il permesso utente per la pagina attuale sia write per almeno 1 diritto + /// assegnato (restituisce true se ne trova almeno 1 con permessi2funzione.readwrite='S') + /// + /// + /// + public bool isPageWriteEnabled(string pagina) + { + bool answ = false; + try + { + if (permessiWrite != null) + { + System.Data.DataRow[] righe = permessiWrite.Select(string.Format("URL = '{0}.aspx' OR URL = '{0}'", pagina)); + answ = (righe.Length >= 1); + } + } + catch (Exception exc) + { + Log.Error($"Eccezione isPageWriteEnabled{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// Restituisce il numero di attivazioni rimaste x utente dato email e key + /// + /// + /// + /// + public int numAuth(string UserAuthKey, string email) + { + DS_Auth.UtentiRow rowUtenti; + int numAuth = 0; + try + { + // decodifica al volo la cifra... + rowUtenti = taUtenti.getByEmailAK(email, UserAuthKey)[0]; + numAuth = rowUtenti.numAuth; + } + catch (Exception exc) + { + Log.Error($"Eccezione numAuth01{Environment.NewLine}{exc}"); + } + // ritorno + return numAuth; + } + + /// + /// Restituisce il numero di attivazioni rimaste x utente dato email + /// + /// + /// + public int numAuth(string email) + { + DS_Auth.UtentiRow rowUtenti; + int numAuth = 0; + try + { + // decodifica al volo la cifra... + rowUtenti = taUtenti.getByEmail(email)[0]; + numAuth = rowUtenti.numAuth; + } + catch (Exception exc) + { + Log.Error($"Eccezione numAuth02{Environment.NewLine}{exc}"); + } + // ritorno + return numAuth; + } + + /// + /// genera la passphrase utente a partire dai parametri richiesti + /// + /// + /// + /// + public string passphrase(string CodMod, string userKey) + { + return $"{CodMod}#{userKey}"; + } + + /// + /// registra su DB la richiesta di reset della auth key dell'utente ed opzionalmente invia + /// email ad admin + /// + /// + /// + /// opzionale, se != "" invia email all'indirizzo dell'admin x reset + /// + public void reqResetAuthKey(string email, string adminEmail) + { + // registro richiesta di reset KEY... + taUtenti.reqAuthKeyReset(email); + + // se ho email admin... + if (adminEmail != "") + { + // mando email ad admin x reset utente... + string oggetto = string.Format("L'utente {0} ha richiesto il reset della sua AuthKey.

Seguire il link seguente per approvare o rifiutare la richiesta", email, memLayer.ML.CRS("baseUrl"), memLayer.ML.CRS("urlGestUtenti")); + gestEmail.geAuth.mandaEmail(email, adminEmail, "Richiesta reset AuthKey utente", oggetto); + } + } + + /// + /// ricarica e ri-traduce la mappa sito per l'utente... + /// + public void ricaricaMappaSito() + { + memLayer.ML.emptySessionVal("dirittiUtente"); + memLayer.ML.emptySessionVal("permessiUtente"); + setupDirittiPermessi(); + setupMappaSito(); + } + + /// + /// invia email ad utente con url x enroll + /// + /// + /// chiave (in chiaro) + /// nome del sito + public void sendEmailAuthKey(string email, string AuthKey, string SiteName) + { + string body = "Hi,

This is an automatic message generated by {3} platform on behalf of platform admin.

Please click on following link (or cut/paste to your preferred browser) to enable current device to {3} login.

Regards."; + string subject = string.Format("AUTH access to {0}", SiteName); + sendEmailAuthKey(email, AuthKey, SiteName, subject, body); + } + + /// + /// invia email ad utente con url x enroll (utilizzando il parametro baseURL x il sito) + /// + /// + /// chiave (in chiaro) + /// nome del sito + /// chiave (in chiaro) + /// + /// body (in formato da completare string.format con 4 parametri che verrano inseriti come i + /// seguenti: {0} = baseURL - memLayer.ML.CRS("baseUrl") {1} = chaive encoded - + /// HttpUtility.UrlEncode(md5UserAuthKey) {2} = email destinatario {3} = subject {4} = site name + /// + public void sendEmailAuthKey(string email, string AuthKey, string SiteName, string subject, string body) + { + // se ho email admin... + if (email != "") + { + // calcolo chiave MD5... + string md5UserAuthKey = encodeKey(AuthKey); + // mando email ad admin x reset utente... + string oggetto = string.Format(body, memLayer.ML.CRS("baseUrl"), HttpUtility.UrlEncode(md5UserAuthKey), email, SiteName); + gestEmail.geAuth.mandaEmail(memLayer.ML.CRS("_fromEmail"), email, subject, oggetto); + } + } + + /// + /// invia email ad utente con url x reset hash password + /// + /// destinatario + /// hashPasswd ATTUALE (in chiaro) + /// + public void sendEmailResetHashPassword(string email, string hashPasswd, string webAppName) + { + // se ho email admin... + if (email != "") + { + // calcolo chiave MD5... + string md5hashPasswd = encodeKey(hashPasswd); + // mando email ad admin x reset utente... + string oggetto = string.Format("Hi,

This is an automatic message generated by {3} platform on behalf of platform admin.

Please click on following link (or cut/paste to your preferred browser) to reset your password to {3} login.

Regards.", memLayer.ML.CRS("baseUrl"), HttpUtility.UrlEncode(md5hashPasswd), email, webAppName); + gestEmail.geAuth.mandaEmail(memLayer.ML.CRS("_fromEmail"), email, webAppName, oggetto); + } + } + + /// + /// Procedura da chiamare DOPO aver messo in session i dati utente/email x caricare gli + /// altri dati + /// + /// + /// + public bool startUpUtente(string _username) + { + bool risultato = false; + try + { + clearAllUserData(); + if (_username != "") + { + utente = _username; + email = _username; // !!!HARD CODED, user = email... + setupRiga(); + setupDirittiPermessi(); + setupMappaSito(); + setupLingua(); + risultato = true; + } + } + catch (Exception exc) + { + Log.Error($"Eccezione startUpUtente{Environment.NewLine}{exc}"); + } + return risultato; + } + + /// + /// wrapper traduzione + /// + /// + /// + public string traduci(object lemma) + { + string answ = ""; + if (lemma != null) + { + if (lemma.ToString() != "") + { + answ = user_std.UtSn.Traduci(lemma.ToString()); + } + } + else + { + answ = "--"; + } + return answ; + } + + /// + /// verifica nella tab diritti se l'utente abbia il right richiesto e fornisce bool in risposta + /// + /// + /// + public bool userHasRight(string diritto) + { + bool _answ = false; + try + { + if (diritti != null) + { + if (diritti.Select(String.Format("COD_FUNZIONE ='{0}'", diritto)).Length > 0) + { + _answ = true; + } + } + } + catch (Exception exc) + { + Log.Error($"Eccezione userHasRight{Environment.NewLine}{exc}"); + } + return _answ; + } + + /// + /// Verifica se l'utente sia noto al sistema... + /// + /// + /// + public bool userIsKnown(string _username) + { + bool answ = false; + try + { + answ = taUtenti.getByEmail(_username).Rows.Count > 0; + } + catch (Exception exc) + { + Log.Error($"Eccezione userIsKnown{Environment.NewLine}{exc}"); + } + return answ; + } + + #endregion Public Methods + + #region Protected Constructors + + /// + /// Initializes a new instance of the class. + /// + protected devicesAuthProxy() + { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } + initTA(); + setupConnectionStringBase(); + } + + #endregion Protected Constructors + + #region Protected Properties + + /// + /// numero massimo auth concesse (se non trovo su conf prendo 1000) + /// + protected int maxAuth + { + get + { + int answ = memLayer.ML.CRI("maxAuth"); + if (answ < 0) + { + answ = 1000; + } + + return answ; + } + } + + #endregion Protected Properties + + #region Protected Methods + + /// + /// formatta un nodo in modo corretto dai dati indicati + /// + /// + /// + /// + /// + protected string formattaNodo(string titolo, string descrizione, string url, siteNodeType tipoNodo) + { + string _out = ""; + switch (tipoNodo) + { + case siteNodeType.startContainer: + _out = string.Format("", traduci(titolo), traduci(descrizione), url); + break; + + case siteNodeType.endContainer: + _out = ""; + break; + + case siteNodeType.leaf: + _out = string.Format("", traduci(titolo), traduci(descrizione), url); + break; + } + return _out; + } + + /// + /// init dei table adapters + /// + protected void initTA() + { + taAnagDev = new DS_AuthTableAdapters.AnagDevicesTableAdapter(); + taUtenti = new DS_AuthTableAdapters.UtentiTableAdapter(); + taDiritti = new DS_AuthTableAdapters.DIRITTITableAdapter(); + taPermessi = new DS_AuthTableAdapters.PermessiTableAdapter(); + taFunzione = new DS_AuthTableAdapters.FUNZIONETableAdapter(); + taPermessi2Funzione = new DS_AuthTableAdapters.Permessi2FunzioneTableAdapter(); + } + + /// + /// Effettua setup dei permessi una volta salvati i diritti + /// + protected virtual void setPermessiDaDiritti() + { + // proseguo coi permessi + DS_Auth.PermessiDataTable allPermessi = taPermessi.GetData(); + DS_Auth.Permessi2FunzioneDataTable allPerm2Funz = taPermessi2Funzione.GetData(); + DS_Auth.PermessiDataTable _permessiUtente = new DS_Auth.PermessiDataTable(); + DS_Auth.PermessiDataTable _permessiUtenteWrite = new DS_Auth.PermessiDataTable(); + string filtroFunz, filtroPerm, filtroPermWrite; + filtroPerm = " COD_PERMESSO IN ("; + filtroPermWrite = " COD_PERMESSO IN ("; + // filtro i diritti utente x non avere duplicati... + Dictionary funzioniUtente = new Dictionary(); + foreach (DS_Auth.DIRITTIRow riga in diritti) + { + try + { + funzioniUtente.Add(riga.COD_FUNZIONE, riga.COD_FUNZIONE); + } + catch (Exception exc) + { + Log.Error($"Eccezione setPermessiDaDiritti01{Environment.NewLine}{exc}"); + } + } + foreach (KeyValuePair kvp in funzioniUtente) + { + filtroFunz = string.Format("COD_FUNZIONE='{0}'", kvp.Value); + // recupero le righe dei righe2perm + DS_Auth.Permessi2FunzioneRow[] righe_p2f = (DS_Auth.Permessi2FunzioneRow[])allPerm2Funz.Select(filtroFunz); + foreach (DS_Auth.Permessi2FunzioneRow riga_p2f in righe_p2f) + { + filtroPerm += string.Format("'{0}', ", riga_p2f.COD_PERMESSO); + // se è write metto in tab relativa... + try + { + if (riga_p2f.READWRITE == "S") + { + filtroPermWrite += string.Format("'{0}', ", riga_p2f.COD_PERMESSO); + } + } + catch (Exception exc) + { + Log.Error($"Eccezione setPermessiDaDiritti02{Environment.NewLine}{exc}"); + } + } + } + if (filtroPerm == " COD_PERMESSO IN (") + { + filtroPerm += "'PermessiNonTrovati' "; + } + filtroPerm = filtroPerm.Remove(filtroPerm.Length - 2); + filtroPerm += ") "; + DS_Auth.PermessiRow[] righePerm = (DS_Auth.PermessiRow[])allPermessi.Select(filtroPerm, "GRUPPO, NUMERO"); + foreach (DS_Auth.PermessiRow rigaPerm in righePerm) + { + _permessiUtente.ImportRow(rigaPerm); + } + permessi = _permessiUtente; + // salvo, se ci sono, permessi write... + if (filtroPermWrite != " COD_PERMESSO IN (") + { + filtroPermWrite = filtroPermWrite.Remove(filtroPermWrite.Length - 2); + filtroPermWrite += ") "; + DS_Auth.PermessiRow[] righePermW = (DS_Auth.PermessiRow[])allPermessi.Select(filtroPermWrite, "GRUPPO, NUMERO"); + foreach (DS_Auth.PermessiRow rigaPerm in righePermW) + { + _permessiUtenteWrite.ImportRow(rigaPerm); + } + } + permessiWrite = _permessiUtenteWrite; + } + + /// + /// effettua setup dei connection strings da web.config delal singola applicazione + /// + protected virtual void setupConnectionStringBase() + { + // connections del db + string connString = memLayer.ML.confReadString("DevicesAuthConnectionString"); + taAnagDev.Connection.ConnectionString = connString; + taUtenti.Connection.ConnectionString = connString; + taDiritti.Connection.ConnectionString = connString; + taPermessi.Connection.ConnectionString = connString; + taFunzione.Connection.ConnectionString = connString; + taPermessi2Funzione.Connection.ConnectionString = connString; + } + + /* Classe che si occupa di: + * ---------------------------------------- + * 1) gestione username + * 2) gestione ruoli da anagrafica + * 3) gestione declinazione ruoli in permessi + * + * in Standard GENERICO + */ + + /// + /// Carica la tabella diritti dell'utente da db e salva in session + /// + protected virtual void setupDirittiPermessi() + { + try + { + diritti = taDiritti.getByUserModulo(utente, modulo); // salvo in session i diritti.. + if (diritti.Count > 0) + { + setPermessiDaDiritti(); + } + } + catch (Exception exc) + { + Log.Error($"Eccezione setupDirittiPermessi{Environment.NewLine}{exc}"); + } + } + + /// + /// imposta la lingua utente dal valore della riga DB + /// + protected virtual void setupLingua() + { + string _lingua = ""; + try + { + _lingua = rigaUtente.CodGruppo; + // se contiene "#" prendo primo dei 2 come codice... + if (_lingua.IndexOf("#") >= 0) + { + string[] dati = _lingua.Split('#'); + _lingua = dati[0]; + } + } + catch (Exception exc) + { + Log.Error($"Eccezione setupLingua{Environment.NewLine}{exc}"); + } + if (string.IsNullOrEmpty(_lingua)) + { + _lingua = "EN"; + } + + lingua = _lingua; + } + + /// + /// costruisce la mappa del sito per l'utente + /// + protected virtual void setupMappaSito() + { + string _mappa = ""; + _mappa += ""; + try + { + // partiamo dai permessi utente di numero "0" (sono intestazioni menù...) + DS_Auth.PermessiRow[] vociMenu = (DS_Auth.PermessiRow[])permessi.Select("NUMERO ='0'", "GRUPPO"); + foreach (DS_Auth.PermessiRow voce in vociMenu) + { + _mappa += formattaNodo(voce.NOME, voce.DESCRIZIONE, voce.URL, siteNodeType.startContainer); + // per ogni livello riempiamo con i permessi figli + DS_Auth.PermessiRow[] pagine = (DS_Auth.PermessiRow[])permessi.Select(string.Format("GRUPPO ='{0}' AND NUMERO > 0", voce.GRUPPO), "NUMERO"); + foreach (DS_Auth.PermessiRow pagina in pagine) + { + _mappa += formattaNodo(pagina.NOME, pagina.DESCRIZIONE, pagina.URL, siteNodeType.leaf); + } + _mappa += formattaNodo(voce.NOME, voce.DESCRIZIONE, voce.URL, siteNodeType.endContainer); + } + } + catch (Exception exc) + { + Log.Error($"Eccezione setupMappaSito{Environment.NewLine}{exc}"); + } + // salva in session... + _mappa += ""; + mappaSito = _mappa; + } + + /// + /// carica la riga dati utente + /// + protected virtual void setupRiga() + { + try + { + rigaUtente = ((DS_Auth.UtentiRow)taUtenti.getByEmail(email).Rows[0]); + } + catch (Exception exc) + { + Log.Error($"Eccezione setupRiga{Environment.NewLine}{exc}"); + } + } + + #endregion Protected Methods + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields } - - /// - /// oggetto lingua utente con metodi get/set - /// - public string lingua - { - get - { - return memLayer.ML.StringSessionObj("Lingua").ToUpper(); - } - set - { - memLayer.ML.setSessionVal("Lingua", value); - } - } - - /// - /// fornisce un file XML della mappa del sito abilitato per l'utente... - /// - public string mappaSito - { - get - { - return memLayer.ML.StringSessionObj("mappaSito"); - } - set - { - memLayer.ML.setSessionVal("mappaSito", value); - } - } - - #endregion - - #region gestione pagina - - /// - /// pagina correntemente visualizzata (URL in sessione) - /// - public static string pagCorrente - { - get - { - return memLayer.ML.StringSessionObj("pagCorrente"); - } - set - { - memLayer.ML.setSessionVal("pagCorrente", value); - } - } - /// - /// pagina precedentemente visualizzata (URL in sessione) - /// - public static string pagPrecedente - { - get - { - return memLayer.ML.StringSessionObj("pagPrecedente"); - } - set - { - memLayer.ML.setSessionVal("pagPrecedente", value); - } - } - /// - /// restituisce il nome della pagina corrente - /// - public static string getPage(Uri MyUrl) - { - string answ = ""; - try - { - answ = MyUrl.LocalPath.Split('/').Last(); - } - catch (Exception exc) - { - logger.lg.scriviLog(exc.ToString(), tipoLog.EXCEPTION); - } - return answ; - } - - - #endregion - - } -} +} \ No newline at end of file diff --git a/SteamWare/fileMover.cs b/SteamWare/fileMover.cs index cf35192..22774c3 100644 --- a/SteamWare/fileMover.cs +++ b/SteamWare/fileMover.cs @@ -1,4 +1,5 @@ using ICSharpCode.SharpZipLib.Zip; +using NLog; using System; using System.Diagnostics; using System.IO; @@ -11,67 +12,21 @@ namespace SteamWare ///
public class fileMover { - - #region oggetti private + #region Public Fields /// - /// path di lavoro dei metodi leggi/scrivi + /// versione statica (singleton) del'oggetto fileMover /// - protected string _workPath; - /// - /// verifica esistenza directory ed eventualmente crea restituendo nome completo di "/" finale - /// - /// - /// - protected string verDir(string _path) - { - DirectoryInfo di = getDirectoryInfo(_path, true); - if (!di.Exists) - { - di.Create(); - } - if (!_path.EndsWith("/") && !_path.EndsWith(@"\")) - { - _path += "/"; - } - return _path; - } - /// - /// restituisce una tab di files dato l'elenco dei files - /// - /// - /// - private static DataLayer_generic.filesDataTable tabellaFiles(FileInfo[] _files) - { - DataLayer_generic.filesDataTable _dsEF = new DataLayer_generic.filesDataTable(); - DataLayer_generic.filesRow _riga; - foreach (FileInfo _fi in _files) - { - _riga = _dsEF.NewfilesRow(); - _riga.dataCreaz = _fi.CreationTime; - _riga.dataMod = _fi.LastWriteTime; - _riga.Nome = _fi.Name; - _riga.size = _fi.Length / 1000; - _dsEF.AddfilesRow(_riga); - } - return _dsEF; - } - /// - /// setta le directory - /// - /// - private void setDirs(string _path) - { - _workPath = _path; - } + public static fileMover obj = new fileMover(); + /// /// oggetto WebClient /// public WebClient WebCli; - #endregion + #endregion Public Fields - #region inizializzazione + #region Public Constructors /// /// inizializza il metodo alla cartella indicata @@ -80,587 +35,135 @@ namespace SteamWare /// non serve +... x retrocompatibilità... public fileMover(string _path, string _log) { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } setDirs(_path); WebCli = new WebClient(); } + /// /// metodo di avvio empty /// public fileMover() { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } WebCli = new WebClient(); } + #endregion Public Constructors - #endregion + #region Public Methods /// - /// Recupera path correttamente (se fisico o virtuale + /// Effettua copia files da locale a rete con auth (Local 2 Network)... /// - /// + /// + /// + /// + /// + /// /// - protected string GetPath(string path) + public static bool copiaFileL2N(string pathSource, string pathDest, NetworkCredential credentialsDest, string fileSource, string fileDest) { - if (Path.IsPathRooted(path)) - { - return path; - } - // altrimenti MapPath! - return System.Web.HttpContext.Current.Server.MapPath(path); - } - - /// - /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile - /// - /// - /// - private FileInfo getFileInfoByName(string _nomeFile) - { - FileInfo _fi; + bool fatto = false; + Log.Info($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}", tipoLog.INFO); try { - _fi = new FileInfo(GetPath(_workPath + "\\" + _nomeFile)); + using (new NetworkConnection(pathDest, credentialsDest)) + { + File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); + fatto = true; + } } catch (Exception exc) { - logger.lg.scriviLog($"Errore in recupero info file: {_nomeFile}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - _fi = new FileInfo(_workPath + "\\" + _nomeFile); + Log.Error($"Eccezione copiaFileL2N | {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}"); } -#if false - // se nomefile contiene "/" --> faccio mappath altrimenti è percorso fisico... - if (_nomeFile.IndexOf("/") < 0) - { - try - { - _fi = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(_workPath + "\\" + _nomeFile)); - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in recupero info file{_nomeFile}:{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - _fi = new FileInfo(_workPath + "\\" + _nomeFile); - } - } - else - { - try - { - _fi = new FileInfo(_nomeFile); - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in recupero info file{_nomeFile}:{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - _fi = new FileInfo(_workPath + "\\" + _nomeFile); - } - } -#endif - return _fi; + return fatto; } + /// - /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile + /// Effettua copia files via rete con auth (Net 2 Net)... /// - /// The _path. - /// The _nome file. + /// + /// + /// + /// + /// + /// /// - private FileInfo getFileInfoByName(string _path, string _nomeFile) + public static bool copiaFileN2N(string pathSource, string pathDest, NetworkCredential credentialsSource, NetworkCredential credentialsDest, string fileSource, string fileDest) { - FileInfo _fi; + bool fatto = false; + Log.Info($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}", tipoLog.INFO); try { - _fi = new FileInfo(GetPath(_path + _nomeFile)); - + using (new NetworkConnection(pathSource, credentialsSource)) + using (new NetworkConnection(pathDest, credentialsDest)) + { + File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); + fatto = true; + } } catch (Exception exc) { - logger.lg.scriviLog($"Errore in recupero info path: {_path} | file: {_nomeFile}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - _fi = new FileInfo(_path + "\\" + _nomeFile); + Log.Error($"Eccezione copiaFileN2N | {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}"); } -#if false - try - { - _fi = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(_path + _nomeFile)); + return fatto; + } - } - catch - { - _fi = new FileInfo(_path + "\\" + _nomeFile); - } -#endif - return _fi; - } /// - /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile + /// elimina la folder indicata /// - /// cartella file - /// nome file - /// indica se il path sia assoluto + /// Path della fodler da eliminare + /// Indica se cancellare in modo ricorsivo /// - private FileInfo getFileInfoByName(string _path, string _nomeFile, bool absPath) + public static bool deleteDir(string PathOfDir2Delete, bool recursive = true) { - FileInfo _fi; - if (absPath) - { - _fi = new FileInfo(_path + "\\" + _nomeFile); - } - else - { - _fi = getFileInfoByName(_path, _nomeFile); - } - return _fi; - } - /// - /// cerca di caricare la directoryInfo o da httpcontext-application re-position o direttamente come workpath - /// - /// - private DirectoryInfo getDirectoryInfo() - { - DirectoryInfo _di; + bool ret = true; try { - _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(_workPath)); - } - catch - { - _di = new DirectoryInfo(_workPath); - } - return _di; - } - /// - /// imposta la directory richiesta... - /// - /// - private DirectoryInfo getDirectoryInfo(string path, bool absPath) - { - DirectoryInfo _di; - if (absPath) - { - _di = new DirectoryInfo(path); - } - else - { - - try + if (Directory.Exists(PathOfDir2Delete)) { - _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(path)); - } - catch - { - _di = new DirectoryInfo(path); + Directory.Delete(PathOfDir2Delete, recursive); } } - return _di; - } - - #region oggetti public - - /// - /// Legge i dati da uno stream fino a quando arriva alla fine. - /// I dati sono restituiti come un byte[] array. un eccezione IOException è - /// sollevata se una delle chiamate IO sottostanti fallisce. - /// - /// Lo stream da cui leggere - /// Lunghezza buffer iniziale (-1 = default 32k) - public static byte[] ReadFully(Stream stream, int initialLength) - { - // If we've been passed an unhelpful initial length, just - // use 32K. - if (initialLength < 1) + catch (Exception exc) { - initialLength = 32768; + ret = false; + Log.Error($"Eccezione deleteDir | {PathOfDir2Delete}{Environment.NewLine}{exc}"); } - - byte[] buffer = new byte[initialLength]; - int read = 0; - - int chunk; - while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0) - { - read += chunk; - - // If we've reached the end of our buffer, check to see if there's - // any more information - if (read == buffer.Length) - { - int nextByte = stream.ReadByte(); - - // End of stream? If so, we're done - if (nextByte == -1) - { - return buffer; - } - - // Nope. Resize the buffer, put in the byte we've just - // read, and continue - byte[] newBuffer = new byte[buffer.Length * 2]; - Array.Copy(buffer, newBuffer, buffer.Length); - newBuffer[read] = (byte)nextByte; - buffer = newBuffer; - read++; - } - } - // Buffer is now too big. Shrink it. - byte[] ret = new byte[read]; - Array.Copy(buffer, ret, read); return ret; } /// - /// verifica esistenza directory, eventualmente crea e restituisce controllo DirectoryInfo + /// elimina il file indicato /// + /// /// - public DirectoryInfo checkDir() + public static bool deleteFile(string PathOfFile2Delete) { - DirectoryInfo _di = getDirectoryInfo(); - if (!_di.Exists) - { - _di.Create(); - } - return _di; - } - - /// - /// ottiene il dataset dei files presenti nella directory indicata esplicitamente - /// - /// dir da indicizzare... già mappata! ( es SteamwareStrings.getFilePath(...) ) - /// - public DataLayer_generic.filesDataTable elencoFilesDir(string directory) - { - _workPath = directory; - return elencoFiles(); - } - - /// - /// ottiene il dataset dei files presenti nella directory indicata all'istanziazione dell'oggetto - /// - /// - public DataLayer_generic.filesDataTable elencoFiles() - { - DirectoryInfo _di = checkDir(); - FileInfo[] _files = _di.GetFiles(); - DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); - return _dsEF; - } - /// - /// ottiene il dataset dei files DEL TIPO "like {param}" presenti nella directory indicata all'istanziazione dell'oggetto - /// - /// - public DataLayer_generic.filesDataTable elencoFiles(string _param) - { - DirectoryInfo _di = checkDir(); - FileInfo[] _files = _di.GetFiles(_param); - DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); - return _dsEF; - } - /// - /// elenco dei files come array di oggetti FileInfo - /// - /// - public FileInfo[] elencoFiles_FI() - { - DirectoryInfo _di = checkDir(); - return _di.GetFiles(); - } - /// - /// elenco dei files come array di oggetti FileInfo filtrati per parametro - /// - /// - /// - public FileInfo[] elencoFiles_FI(string _param) - { - DirectoryInfo _di = checkDir(); - return _di.GetFiles(_param); - } - /// - /// elenco sub-directory array di oggetti FileInfo filtrati per parametro - /// - /// - public DirectoryInfo[] elencoSubdir_DI() - { - DirectoryInfo _di = checkDir(); - return _di.GetDirectories(); - } - /// - /// elenco sub-directory array di oggetti FileInfo filtrati per parametro - /// - /// - /// - public DirectoryInfo[] elencoSubdir_DI(string _param) - { - DirectoryInfo _di = checkDir(); - return _di.GetDirectories(_param); - } - /// - /// elimina la directory di lavoro se è dir virtuale mappata - /// - /// - public bool eliminaDir() - { - DirectoryInfo _di = checkDir(); - bool fatto = false; + bool ret = true; try { - _di.Delete(true); - fatto = true; + if (File.Exists(PathOfFile2Delete)) + { + File.Delete(PathOfFile2Delete); + } } - catch + catch (Exception exc) { + ret = false; + Log.Error($"Eccezione deleteFile | {PathOfFile2Delete}{Environment.NewLine}{exc}"); } - return fatto; + return ret; } - /// - /// elimina tutti i files con la regexp indicata da una directory, true se cancellato almeno uno - /// - /// regexp selezione files in dir (* = tutti!!!) - /// - public bool svuotaDir(string nomeCercato) - { - bool answ = false; - FileInfo[] _fis = elencoFiles_FI(nomeCercato); - foreach (FileInfo _file in _fis) - { - eliminaFile(_file.Name); - answ = true; - } - return answ; - } - - /// - /// verifica se il file indicato esista in workDir - /// - /// - /// - public bool fileExist(string _nomeFile) - { - bool answ = false; - FileInfo _fi = getFileInfoByName(_nomeFile); - answ = _fi.Exists; - if (!answ) - { - // registro che non ho trovaot il file: path e nome file! - logger.lg.scriviLog(string.Format("Attenzione: non e' stato possibile trovare il file!{0}wrkDir:{1}{0}file:{2}", Environment.NewLine, _workPath, _nomeFile), tipoLog.INFO); - } - return answ; - } - /// - /// verifica se il file indicato esista in _path - /// - /// - /// - /// - public bool fileExist(string _path, string _nomeFile) - { - bool answ = false; - FileInfo _fi = getFileInfoByName(_path, _nomeFile); - answ = _fi.Exists; - if (!answ) - { - // registro che non ho trovaot il file: path e nome file! - logger.lg.scriviLog(string.Format("Attenzione: non e' stato possibile trovare il file!{0}path:{1}{0}file:{2}", Environment.NewLine, _path, _nomeFile), tipoLog.INFO); - } - return answ; - } - /// - /// elimina il file indicato dalla directory di lavoro - /// - /// - /// - public bool eliminaFile(string _nomeFile) - { - FileInfo _fi = getFileInfoByName(_nomeFile); - bool fatto = false; - try - { - _fi.Delete(); - fatto = true; - } - catch - { } - if (fatto) - { - logger.lg.scriviLog($"Eliminazione file {_nomeFile} eseguita"); - } - else - { - logger.lg.scriviLog($"impossibile Eliminare il file {_nomeFile}"); - } - return fatto; - } - /// - /// elimina il file indicato dalla directory di lavoro - /// - /// The _fi. - /// - public bool eliminaFile(FileInfo _fi) - { - bool fatto = false; - try - { - _fi.Delete(); - fatto = true; - } - catch - { - } - return fatto; - } - /// - /// restituisce lo stream del file richiesto - /// - /// - /// - public byte[] scaricaFile(string _nomeFile) - { - FileInfo _fi = getFileInfoByName(_nomeFile); - // verifica ci siano attach... - if (_fi.Exists) - { - Stream _stream = _fi.OpenRead(); - byte[] _risposta = ReadFully(_stream, -1); - _stream.Close(); - return _risposta; - } - else - { - return null; - } - } - /// - /// restituisce la stringa letta dal file richiesto - /// - /// - /// - public string scaricaFileString(string _nomeFile) - { - return byteToStr(scaricaFile(_nomeFile)); - } - /// - /// scrive il file dallo stream byte[] inviato - /// - /// - /// - /// - /// - public bool salvaFileBuffer(string _path, string _nomeFile, byte[] _fileBuffer) - { - _workPath = _path; - DirectoryInfo _di = getDirectoryInfo(_path, true); - if (!_di.Exists) - { - _di.Create(); - } - FileInfo _fi = getFileInfoByName(_path, _nomeFile); - Stream _stream; - if (!_fi.Exists) - { - _stream = _fi.Create(); - } - else - { - _stream = _fi.OpenWrite(); - } - _stream.Write(_fileBuffer, 0, _fileBuffer.Length); - _stream.Flush(); - _stream.Close(); - - return true; - } - /// - /// scrive il file dallo stream byte[] inviato - /// - /// - /// - /// - public bool salvaFileBuffer(string _nomeFile, byte[] _fileBuffer) - { - DirectoryInfo _di = getDirectoryInfo(); - if (!_di.Exists) - { - _di.Create(); - } - FileInfo _fi = getFileInfoByName(_nomeFile); - Stream _stream; - if (!_fi.Exists) - { - _stream = _fi.Create(); - } - else - { - _stream = _fi.OpenWrite(); - } - _stream.Write(_fileBuffer, 0, _fileBuffer.Length); - _stream.Flush(); - _stream.Close(); - - return true; - } - /// - /// scrive il file dalla stringa inviata - /// - /// - /// - /// - /// - public bool salvaFileString(string _path, string _nomeFile, string _fileString) - { - return salvaFileBuffer(_path, _nomeFile, strToByte(_fileString)); - } - /// - /// scrive il file dalla stringa inviata - /// - /// - /// - /// - public bool salvaFileString(string _nomeFile, string _fileString) - { - return salvaFileBuffer(_nomeFile, strToByte(_fileString)); - } - /// - /// converte una string in un byte[] - /// - /// - /// - protected byte[] strToByte(string _val) - { - System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); - return encod.GetBytes(_val); - } - /// - /// converte un byte[] in una string - /// - /// - /// - protected string byteToStr(byte[] _array) - { - System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); - return encod.GetString(_array); - } - - /// - /// sposta il file da From a To... - /// - /// - /// - /// - /// - public bool muoviFile(string _pathFrom, string _pathTo, string _nomeFile) - { - bool fatto = false; - // verifica directory - _pathTo = verDir(_pathTo); - _pathFrom = verDir(_pathFrom); - FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile, true); - try - { - _fi.CopyTo(_pathTo + _nomeFile, true); - _fi.Delete(); - fatto = true; - } - catch (Exception e) - { - Console.WriteLine("{0} Exception caught.", e); - } - return fatto; - } /// /// Copia il contenuto directory da From a To (opzionalmente in modo ricorsivo)... /// @@ -707,169 +210,6 @@ namespace SteamWare } } - /// - /// copia il file da From a To... - /// - /// - /// - /// - /// - public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFile) - { - bool fatto = false; - // verifica directory - _pathFrom = verDir(_pathFrom); - _pathTo = verDir(_pathTo); - FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile); - try - { - _fi.CopyTo(_pathTo + _nomeFile, true); - fatto = true; - } - catch (Exception e) - { - Console.WriteLine("{0} Exception caught.", e); - } - return fatto; - } - /// - /// copia il file da From a To... - /// - /// - /// - /// - /// - /// - public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFileOrig, string _nomeFileDest) - { - bool fatto = false; - // verifica directory - _pathFrom = verDir(_pathFrom); - _pathTo = verDir(_pathTo); - FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFileOrig); - try - { - _fi.CopyTo(System.Web.HttpContext.Current.Server.MapPath(_pathTo) + _nomeFileDest, true); - fatto = true; - } - catch (Exception e) - { - Console.WriteLine("{0} Exception caught.", e); - _fi.CopyTo(_pathTo + _nomeFileDest, true); - fatto = true; - } - return fatto; - } - /// - /// Effettua copia files da locale a rete con auth (Local 2 Network)... - /// - /// - /// - /// - /// - /// - /// - /// - public static bool copiaFileL2N(string pathSource, string pathDest, NetworkCredential credentialsDest, string fileSource, string fileDest) - { - bool fatto = false; - logger.lg.scriviLog($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}", tipoLog.INFO); - try - { - using (new NetworkConnection(pathDest, credentialsDest)) - { - File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); - fatto = true; - } - } - catch (Exception exc) - { - logger.lg.scriviLog($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - } - return fatto; - } - /// - /// Effettua copia files via rete con auth (Net 2 Net)... - /// - /// - /// - /// - /// - /// - /// - /// - public static bool copiaFileN2N(string pathSource, string pathDest, NetworkCredential credentialsSource, NetworkCredential credentialsDest, string fileSource, string fileDest) - { - bool fatto = false; - logger.lg.scriviLog($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}", tipoLog.INFO); - try - { - using (new NetworkConnection(pathSource, credentialsSource)) - using (new NetworkConnection(pathDest, credentialsDest)) - { - File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); - fatto = true; - } - } - catch (Exception exc) - { - logger.lg.scriviLog($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - } - return fatto; - } - - /// - /// imposta la dir di lavoro - /// - /// - public void setDirectory(string _path) - { - setDirs(_path); - } - /// - /// imposta la dir di lavoro - /// - /// - /// non serve +... x retrocompatibilità... - public void setDirectory(string _path, string _log) - { - setDirs(_path); - } - /// - /// imposta la dir di lavoro impostandola dal mapPath corretto della web app... (come subfolder della web app) - /// - /// - public void setDirectoryMapPath(string _path) - { - setDirs(System.Web.HttpContext.Current.Server.MapPath(_path)); - } - /// - /// restituisce la stringa completa e corretta del filepath del server (anche con vDir) - /// - /// path relativo alla cartella iis dell'applicativo - /// path fisico tradotto - public static string getFilePath(string pathRel) - { - string answ = ""; - if (System.Web.HttpContext.Current != null) - { - try - { - answ = System.Web.HttpContext.Current.Server.MapPath(pathRel); - } - catch - { } - } - else if(Path.IsPathRooted(pathRel)) - { - answ = pathRel; - } - else - { - answ = Path.GetFullPath(pathRel); - } - return answ; - } /// /// esegue un comando in shell /// @@ -897,6 +237,37 @@ namespace SteamWare return ExitCode; } + + /// + /// restituisce la stringa completa e corretta del filepath del server (anche con vDir) + /// + /// path relativo alla cartella iis dell'applicativo + /// path fisico tradotto + public static string getFilePath(string pathRel) + { + string answ = ""; + if (System.Web.HttpContext.Current != null) + { + try + { + answ = System.Web.HttpContext.Current.Server.MapPath(pathRel); + } + catch (Exception exc) + { + Log.Error($"Eccezione getFilePath | {pathRel}{Environment.NewLine}{exc}"); + } + } + else if (Path.IsPathRooted(pathRel)) + { + answ = pathRel; + } + else + { + answ = Path.GetFullPath(pathRel); + } + return answ; + } + /// /// esegue un comando in shell /// @@ -922,155 +293,55 @@ namespace SteamWare //ExitCode = Process.ExitCode; //Process.Close(); } - /// - /// Scarica un file dall'url fornito nella directory indicata x il filemover col nome richiesto - /// - /// url del file - /// nome con cui salvare il file - /// - public void scaricaFileFromWeb(string urlFile, string nomeDest) - { - // utilizzo l'oggetto webCli... - - WebCli.Credentials = System.Net.CredentialCache.DefaultCredentials; - WebCli.DownloadFile(urlFile, string.Format("{0}\\{1}", _workPath, nomeDest)); - } - /// - /// comprime zip il file indicato - /// - /// - /// - public bool zippaSingoloFile(string _nomeFile) - { - bool fatto = false; - FileInfo _fi = getFileInfoByName(_nomeFile); - // calcolo il nome del file zip... - string nomeZip = string.Format("{0}.zip", _fi.FullName); - try - { - using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) - { - s.SetLevel(5); - byte[] buffer = new byte[4096]; - ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); - // Could also use the last write time or similar for the file. - entry.DateTime = DateTime.Now; - s.PutNextEntry(entry); - using (FileStream fs = File.OpenRead(_fi.FullName)) - { - // Using a fixed size buffer here makes no noticeable difference for output - // but keeps a lid on memory usage. - int sourceBytes; - do - { - sourceBytes = fs.Read(buffer, 0, buffer.Length); - s.Write(buffer, 0, sourceBytes); - } while (sourceBytes > 0); - } - s.Finish(); - s.Close(); - } - fatto = true; - } - catch - { - } - return fatto; - } /// - /// comprime zip il file indicato + /// Legge i dati da uno stream fino a quando arriva alla fine. I dati sono restituiti come + /// un byte[] array. un eccezione IOException è sollevata se una delle chiamate IO + /// sottostanti fallisce. /// - /// File in formato FileInfo - /// - public bool zippaSingoloFile(FileInfo _fi) + /// Lo stream da cui leggere + /// Lunghezza buffer iniziale (-1 = default 32k) + public static byte[] ReadFully(Stream stream, int initialLength) { - bool fatto = false; - // calcolo il nome del file zip... - string nomeZip = string.Format("{0}.zip", _fi.FullName); - try + // If we've been passed an unhelpful initial length, just use 32K. + if (initialLength < 1) { - using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) + initialLength = 32768; + } + + byte[] buffer = new byte[initialLength]; + int read = 0; + + int chunk; + while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0) + { + read += chunk; + + // If we've reached the end of our buffer, check to see if there's any more information + if (read == buffer.Length) { - s.SetLevel(5); - byte[] buffer = new byte[4096]; - ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); - // Could also use the last write time or similar for the file. - entry.DateTime = DateTime.Now; - s.PutNextEntry(entry); - using (FileStream fs = File.OpenRead(_fi.FullName)) + int nextByte = stream.ReadByte(); + + // End of stream? If so, we're done + if (nextByte == -1) { - // Using a fixed size buffer here makes no noticeable difference for output - // but keeps a lid on memory usage. - int sourceBytes; - do - { - sourceBytes = fs.Read(buffer, 0, buffer.Length); - s.Write(buffer, 0, sourceBytes); - } while (sourceBytes > 0); + return buffer; } - s.Finish(); - s.Close(); + + // Nope. Resize the buffer, put in the byte we've just read, and continue + byte[] newBuffer = new byte[buffer.Length * 2]; + Array.Copy(buffer, newBuffer, buffer.Length); + newBuffer[read] = (byte)nextByte; + buffer = newBuffer; + read++; } - fatto = true; } - catch - { - } - return fatto; - } - /// - /// comprime zip i files corrispondenti alla RegExp indicata nella dir corrente - /// - /// Espressione ricerca, come *.txt - /// Nome del file zip da creare - /// - public bool zippaFilesByRegExp(string regExp, string outZipFileName) - { - bool fatto = false; - // inizializzo il file zip... - DirectoryInfo _di = checkDir(); - // calcolo il nome del file zip... - string nomeZip = string.Format("{0}/{1}.zip", _di.FullName, outZipFileName.Replace(".zip", "")); - // inizio a inserire dati - try - { - using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) - { - s.SetLevel(5); - byte[] buffer = new byte[4096]; - // effettuo una ricerca dei files corrispondenti al criterio regexp, e per ognuno effettuo inserimento in zipfile... - FileInfo[] filesTrovati = elencoFiles_FI(regExp); - ZipEntry entry; - foreach (FileInfo _fi in filesTrovati) - { - // calcolo la nuova entry nel file zip... - entry = new ZipEntry(Path.GetFileName(_fi.FullName)); - // Could also use the last write time or similar for the file. - entry.DateTime = DateTime.Now; - s.PutNextEntry(entry); - using (FileStream fs = File.OpenRead(_fi.FullName)) - { - // Using a fixed size buffer here makes no noticeable difference for output but keeps a lid on memory usage. - int sourceBytes; - do - { - sourceBytes = fs.Read(buffer, 0, buffer.Length); - s.Write(buffer, 0, sourceBytes); - } while (sourceBytes > 0); - } - } - s.Finish(); - s.Close(); - } - fatto = true; - } - catch (Exception e) - { - logger.lg.scriviLog(string.Format("Errore in creazione file zip con parametri {0} e {1}: {2}", regExp, outZipFileName, e)); - } - return fatto; + // Buffer is now too big. Shrink it. + byte[] ret = new byte[read]; + Array.Copy(buffer, ret, read); + return ret; } + /// /// scompatta tutto il contenuto di un file zip /// @@ -1133,13 +404,14 @@ namespace SteamWare } } } - catch (Exception ex) + catch (Exception exc) { ret = false; - logger.lg.scriviLog(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex), tipoLog.EXCEPTION); + Log.Error($"Eccezione UnZipFile{Environment.NewLine}{exc}"); } return ret; } + /// /// scompatta uno specifico file contenuto in un file zip /// @@ -1203,75 +475,83 @@ namespace SteamWare } } } - catch (Exception ex) + catch (Exception exc) { ret = false; - logger.lg.scriviLog(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex), tipoLog.EXCEPTION); - } - return ret; - } - /// - /// elimina il file indicato - /// - /// - /// - public static bool deleteFile(string PathOfFile2Delete) - { - bool ret = true; - try - { - if (File.Exists(PathOfFile2Delete)) - { - File.Delete(PathOfFile2Delete); - } - } - catch (Exception ex) - { - ret = false; - logger.lg.scriviLog(string.Format("Non sono riuscito ad eliminare file: eccezione {0}", ex), tipoLog.EXCEPTION); - } - return ret; - } - /// - /// elimina la folder indicata - /// - /// Path della fodler da eliminare - /// Indica se cancellare in modo ricorsivo - /// - public static bool deleteDir(string PathOfDir2Delete, bool recursive = true) - { - bool ret = true; - try - { - if (Directory.Exists(PathOfDir2Delete)) - { - Directory.Delete(PathOfDir2Delete, recursive); - } - } - catch (Exception ex) - { - ret = false; - logger.lg.scriviLog($"Non sono riuscito ad eliminare la directory {PathOfDir2Delete} richiesta: eccezione {ex}", tipoLog.EXCEPTION); + Log.Error($"Eccezione UnZipSingleFile{Environment.NewLine}{exc}"); } return ret; } - /// - /// calcola la dim della directory corrente... + /// verifica esistenza directory, eventualmente crea e restituisce controllo DirectoryInfo /// /// - public float totalMb() + public DirectoryInfo checkDir() { - DirectoryInfo _di = checkDir(); - FileInfo[] _fis = _di.GetFiles(); - float _byte = 0; - foreach (FileInfo _file in _fis) + DirectoryInfo _di = getDirectoryInfo(); + if (!_di.Exists) { - _byte += _file.Length; + _di.Create(); } - return _byte / 1000000; + return _di; } + + /// + /// copia il file da From a To... + /// + /// + /// + /// + /// + public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFile) + { + bool fatto = false; + // verifica directory + _pathFrom = verDir(_pathFrom); + _pathTo = verDir(_pathTo); + FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile); + try + { + _fi.CopyTo(_pathTo + _nomeFile, true); + fatto = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione copiaFile{Environment.NewLine}{exc}"); + } + return fatto; + } + + /// + /// copia il file da From a To... + /// + /// + /// + /// + /// + /// + public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFileOrig, string _nomeFileDest) + { + bool fatto = false; + // verifica directory + _pathFrom = verDir(_pathFrom); + _pathTo = verDir(_pathTo); + FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFileOrig); + try + { + _fi.CopyTo(System.Web.HttpContext.Current.Server.MapPath(_pathTo) + _nomeFileDest, true); + fatto = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione copiaFile con Server.MapPath | uso path assoluti{Environment.NewLine}{exc}"); + _fi.CopyTo(_pathTo + _nomeFileDest, true); + fatto = true; + } + return fatto; + } + /// /// elimina il file + vecchio /// @@ -1292,12 +572,772 @@ namespace SteamWare eliminaFile(_nome); } - #endregion + /// + /// ottiene il dataset dei files presenti nella directory indicata all'istanziazione dell'oggetto + /// + /// + public DataLayer_generic.filesDataTable elencoFiles() + { + DirectoryInfo _di = checkDir(); + FileInfo[] _files = _di.GetFiles(); + DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); + return _dsEF; + } /// - /// versione statica (singleton) del'oggetto fileMover + /// ottiene il dataset dei files DEL TIPO "like {param}" presenti nella directory indicata + /// all'istanziazione dell'oggetto /// - public static fileMover obj = new fileMover(); + /// + public DataLayer_generic.filesDataTable elencoFiles(string _param) + { + DirectoryInfo _di = checkDir(); + FileInfo[] _files = _di.GetFiles(_param); + DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); + return _dsEF; + } + /// + /// elenco dei files come array di oggetti FileInfo + /// + /// + public FileInfo[] elencoFiles_FI() + { + DirectoryInfo _di = checkDir(); + return _di.GetFiles(); + } + + /// + /// elenco dei files come array di oggetti FileInfo filtrati per parametro + /// + /// + /// + public FileInfo[] elencoFiles_FI(string _param) + { + DirectoryInfo _di = checkDir(); + return _di.GetFiles(_param); + } + + /// + /// ottiene il dataset dei files presenti nella directory indicata esplicitamente + /// + /// + /// dir da indicizzare... già mappata! ( es SteamwareStrings.getFilePath(...) ) + /// + /// + public DataLayer_generic.filesDataTable elencoFilesDir(string directory) + { + _workPath = directory; + return elencoFiles(); + } + + /// + /// elenco sub-directory array di oggetti FileInfo filtrati per parametro + /// + /// + public DirectoryInfo[] elencoSubdir_DI() + { + DirectoryInfo _di = checkDir(); + return _di.GetDirectories(); + } + + /// + /// elenco sub-directory array di oggetti FileInfo filtrati per parametro + /// + /// + /// + public DirectoryInfo[] elencoSubdir_DI(string _param) + { + DirectoryInfo _di = checkDir(); + return _di.GetDirectories(_param); + } + + /// + /// elimina la directory di lavoro se è dir virtuale mappata + /// + /// + public bool eliminaDir() + { + DirectoryInfo _di = checkDir(); + bool fatto = false; + try + { + _di.Delete(true); + fatto = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione eliminaDir{Environment.NewLine}{exc}"); + } + return fatto; + } + + /// + /// elimina il file indicato dalla directory di lavoro + /// + /// + /// + public bool eliminaFile(string _nomeFile) + { + FileInfo _fi = getFileInfoByName(_nomeFile); + bool fatto = false; + try + { + _fi.Delete(); + fatto = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione eliminaFile01{Environment.NewLine}{exc}"); + } + if (fatto) + { + Log.Info($"Eliminazione file {_nomeFile} eseguita"); + } + else + { + Log.Info($"impossibile Eliminare il file {_nomeFile}"); + } + return fatto; + } + + /// + /// elimina il file indicato dalla directory di lavoro + /// + /// The _fi. + /// + public bool eliminaFile(FileInfo _fi) + { + bool fatto = false; + try + { + _fi.Delete(); + fatto = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione eliminaFile02{Environment.NewLine}{exc}"); + } + return fatto; + } + + /// + /// verifica se il file indicato esista in workDir + /// + /// + /// + public bool fileExist(string _nomeFile) + { + bool answ = false; + FileInfo _fi = getFileInfoByName(_nomeFile); + answ = _fi.Exists; + if (!answ) + { + // registro che non ho trovaot il file: path e nome file! + Log.Info(string.Format("Attenzione: non e' stato possibile trovare il file!{0}wrkDir:{1}{0}file:{2}", Environment.NewLine, _workPath, _nomeFile), tipoLog.INFO); + } + return answ; + } + + /// + /// verifica se il file indicato esista in _path + /// + /// + /// + /// + public bool fileExist(string _path, string _nomeFile) + { + bool answ = false; + FileInfo _fi = getFileInfoByName(_path, _nomeFile); + answ = _fi.Exists; + if (!answ) + { + // registro che non ho trovaot il file: path e nome file! + Log.Info(string.Format("Attenzione: non e' stato possibile trovare il file!{0}path:{1}{0}file:{2}", Environment.NewLine, _path, _nomeFile), tipoLog.INFO); + } + return answ; + } + + /// + /// sposta il file da From a To... + /// + /// + /// + /// + /// + public bool muoviFile(string _pathFrom, string _pathTo, string _nomeFile) + { + bool fatto = false; + // verifica directory + _pathTo = verDir(_pathTo); + _pathFrom = verDir(_pathFrom); + FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile, true); + try + { + _fi.CopyTo(_pathTo + _nomeFile, true); + _fi.Delete(); + fatto = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione muoviFile{Environment.NewLine}{exc}"); + } + return fatto; + } + + /// + /// scrive il file dallo stream byte[] inviato + /// + /// + /// + /// + /// + public bool salvaFileBuffer(string _path, string _nomeFile, byte[] _fileBuffer) + { + _workPath = _path; + DirectoryInfo _di = getDirectoryInfo(_path, true); + if (!_di.Exists) + { + _di.Create(); + } + FileInfo _fi = getFileInfoByName(_path, _nomeFile); + Stream _stream; + if (!_fi.Exists) + { + _stream = _fi.Create(); + } + else + { + _stream = _fi.OpenWrite(); + } + _stream.Write(_fileBuffer, 0, _fileBuffer.Length); + _stream.Flush(); + _stream.Close(); + + return true; + } + + /// + /// scrive il file dallo stream byte[] inviato + /// + /// + /// + /// + public bool salvaFileBuffer(string _nomeFile, byte[] _fileBuffer) + { + DirectoryInfo _di = getDirectoryInfo(); + if (!_di.Exists) + { + _di.Create(); + } + FileInfo _fi = getFileInfoByName(_nomeFile); + Stream _stream; + if (!_fi.Exists) + { + _stream = _fi.Create(); + } + else + { + _stream = _fi.OpenWrite(); + } + _stream.Write(_fileBuffer, 0, _fileBuffer.Length); + _stream.Flush(); + _stream.Close(); + + return true; + } + + /// + /// scrive il file dalla stringa inviata + /// + /// + /// + /// + /// + public bool salvaFileString(string _path, string _nomeFile, string _fileString) + { + return salvaFileBuffer(_path, _nomeFile, strToByte(_fileString)); + } + + /// + /// scrive il file dalla stringa inviata + /// + /// + /// + /// + public bool salvaFileString(string _nomeFile, string _fileString) + { + return salvaFileBuffer(_nomeFile, strToByte(_fileString)); + } + + /// + /// restituisce lo stream del file richiesto + /// + /// + /// + public byte[] scaricaFile(string _nomeFile) + { + FileInfo _fi = getFileInfoByName(_nomeFile); + // verifica ci siano attach... + if (_fi.Exists) + { + Stream _stream = _fi.OpenRead(); + byte[] _risposta = ReadFully(_stream, -1); + _stream.Close(); + return _risposta; + } + else + { + return null; + } + } + + /// + /// Scarica un file dall'url fornito nella directory indicata x il filemover col nome richiesto + /// + /// url del file + /// nome con cui salvare il file + /// + public void scaricaFileFromWeb(string urlFile, string nomeDest) + { + // utilizzo l'oggetto webCli... + + WebCli.Credentials = System.Net.CredentialCache.DefaultCredentials; + WebCli.DownloadFile(urlFile, string.Format("{0}\\{1}", _workPath, nomeDest)); + } + + /// + /// restituisce la stringa letta dal file richiesto + /// + /// + /// + public string scaricaFileString(string _nomeFile) + { + return byteToStr(scaricaFile(_nomeFile)); + } + + /// + /// imposta la dir di lavoro + /// + /// + public void setDirectory(string _path) + { + setDirs(_path); + } + + /// + /// imposta la dir di lavoro + /// + /// + /// non serve +... x retrocompatibilità... + public void setDirectory(string _path, string _log) + { + setDirs(_path); + } + + /// + /// imposta la dir di lavoro impostandola dal mapPath corretto della web app... (come + /// subfolder della web app) + /// + /// + public void setDirectoryMapPath(string _path) + { + setDirs(System.Web.HttpContext.Current.Server.MapPath(_path)); + } + + /// + /// elimina tutti i files con la regexp indicata da una directory, true se cancellato almeno uno + /// + /// regexp selezione files in dir (* = tutti!!!) + /// + public bool svuotaDir(string nomeCercato) + { + bool answ = false; + FileInfo[] _fis = elencoFiles_FI(nomeCercato); + foreach (FileInfo _file in _fis) + { + eliminaFile(_file.Name); + answ = true; + } + return answ; + } + + /// + /// calcola la dim della directory corrente... + /// + /// + public float totalMb() + { + DirectoryInfo _di = checkDir(); + FileInfo[] _fis = _di.GetFiles(); + float _byte = 0; + foreach (FileInfo _file in _fis) + { + _byte += _file.Length; + } + return _byte / 1000000; + } + + /// + /// comprime zip i files corrispondenti alla RegExp indicata nella dir corrente + /// + /// Espressione ricerca, come *.txt + /// Nome del file zip da creare + /// + public bool zippaFilesByRegExp(string regExp, string outZipFileName) + { + bool fatto = false; + // inizializzo il file zip... + DirectoryInfo _di = checkDir(); + // calcolo il nome del file zip... + string nomeZip = string.Format("{0}/{1}.zip", _di.FullName, outZipFileName.Replace(".zip", "")); + // inizio a inserire dati + try + { + using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) + { + s.SetLevel(5); + byte[] buffer = new byte[4096]; + // effettuo una ricerca dei files corrispondenti al criterio regexp, e per + // ognuno effettuo inserimento in zipfile... + FileInfo[] filesTrovati = elencoFiles_FI(regExp); + ZipEntry entry; + foreach (FileInfo _fi in filesTrovati) + { + // calcolo la nuova entry nel file zip... + entry = new ZipEntry(Path.GetFileName(_fi.FullName)); + // Could also use the last write time or similar for the file. + entry.DateTime = DateTime.Now; + s.PutNextEntry(entry); + using (FileStream fs = File.OpenRead(_fi.FullName)) + { + // Using a fixed size buffer here makes no noticeable difference for + // output but keeps a lid on memory usage. + int sourceBytes; + do + { + sourceBytes = fs.Read(buffer, 0, buffer.Length); + s.Write(buffer, 0, sourceBytes); + } while (sourceBytes > 0); + } + } + s.Finish(); + s.Close(); + } + fatto = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione zippaFilesByRegExp | regExp {regExp} | outZipFileName {outZipFileName}{Environment.NewLine}{exc}"); + } + return fatto; + } + + /// + /// comprime zip il file indicato + /// + /// + /// + public bool zippaSingoloFile(string _nomeFile) + { + bool fatto = false; + FileInfo _fi = getFileInfoByName(_nomeFile); + // calcolo il nome del file zip... + string nomeZip = string.Format("{0}.zip", _fi.FullName); + try + { + using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) + { + s.SetLevel(5); + byte[] buffer = new byte[4096]; + ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); + // Could also use the last write time or similar for the file. + entry.DateTime = DateTime.Now; + s.PutNextEntry(entry); + using (FileStream fs = File.OpenRead(_fi.FullName)) + { + // Using a fixed size buffer here makes no noticeable difference for output + // but keeps a lid on memory usage. + int sourceBytes; + do + { + sourceBytes = fs.Read(buffer, 0, buffer.Length); + s.Write(buffer, 0, sourceBytes); + } while (sourceBytes > 0); + } + s.Finish(); + s.Close(); + } + fatto = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione zippaSingoloFile01 | _nomeFile {_nomeFile}{Environment.NewLine}{exc}"); + } + return fatto; + } + + /// + /// comprime zip il file indicato + /// + /// File in formato FileInfo + /// + public bool zippaSingoloFile(FileInfo _fi) + { + bool fatto = false; + // calcolo il nome del file zip... + string nomeZip = string.Format("{0}.zip", _fi.FullName); + try + { + using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) + { + s.SetLevel(5); + byte[] buffer = new byte[4096]; + ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); + // Could also use the last write time or similar for the file. + entry.DateTime = DateTime.Now; + s.PutNextEntry(entry); + using (FileStream fs = File.OpenRead(_fi.FullName)) + { + // Using a fixed size buffer here makes no noticeable difference for output + // but keeps a lid on memory usage. + int sourceBytes; + do + { + sourceBytes = fs.Read(buffer, 0, buffer.Length); + s.Write(buffer, 0, sourceBytes); + } while (sourceBytes > 0); + } + s.Finish(); + s.Close(); + } + fatto = true; + } + catch (Exception exc) + { + Log.Error($"Eccezione zippaSingoloFile02 | _fi {_fi.FullName}{Environment.NewLine}{exc}"); + } + return fatto; + } + + #endregion Public Methods + + #region Protected Fields + + /// + /// path di lavoro dei metodi leggi/scrivi + /// + protected string _workPath; + + #endregion Protected Fields + + #region Protected Methods + + /// + /// converte un byte[] in una string + /// + /// + /// + protected string byteToStr(byte[] _array) + { + System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); + return encod.GetString(_array); + } + + /// + /// Recupera path correttamente (se fisico o virtuale + /// + /// + /// + protected string GetPath(string path) + { + if (Path.IsPathRooted(path)) + { + return path; + } + // altrimenti MapPath! + return System.Web.HttpContext.Current.Server.MapPath(path); + } + + /// + /// converte una string in un byte[] + /// + /// + /// + protected byte[] strToByte(string _val) + { + System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); + return encod.GetBytes(_val); + } + + /// + /// verifica esistenza directory ed eventualmente crea restituendo nome completo di "/" finale + /// + /// + /// + protected string verDir(string _path) + { + DirectoryInfo di = getDirectoryInfo(_path, true); + if (!di.Exists) + { + di.Create(); + } + if (!_path.EndsWith("/") && !_path.EndsWith(@"\")) + { + _path += "/"; + } + return _path; + } + + #endregion Protected Methods + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields + + #region Private Methods + + /// + /// restituisce una tab di files dato l'elenco dei files + /// + /// + /// + private static DataLayer_generic.filesDataTable tabellaFiles(FileInfo[] _files) + { + DataLayer_generic.filesDataTable _dsEF = new DataLayer_generic.filesDataTable(); + DataLayer_generic.filesRow _riga; + foreach (FileInfo _fi in _files) + { + _riga = _dsEF.NewfilesRow(); + _riga.dataCreaz = _fi.CreationTime; + _riga.dataMod = _fi.LastWriteTime; + _riga.Nome = _fi.Name; + _riga.size = _fi.Length / 1000; + _dsEF.AddfilesRow(_riga); + } + return _dsEF; + } + + /// + /// cerca di caricare la directoryInfo o da httpcontext-application re-position o + /// direttamente come workpath + /// + /// + private DirectoryInfo getDirectoryInfo() + { + DirectoryInfo _di; + try + { + _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(_workPath)); + } + catch + { + _di = new DirectoryInfo(_workPath); + } + return _di; + } + + /// + /// imposta la directory richiesta... + /// + /// + private DirectoryInfo getDirectoryInfo(string path, bool absPath) + { + DirectoryInfo _di; + if (absPath) + { + _di = new DirectoryInfo(path); + } + else + { + try + { + _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(path)); + } + catch + { + _di = new DirectoryInfo(path); + } + } + return _di; + } + + /// + /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente + /// come workpath + nomefile + /// + /// + /// + private FileInfo getFileInfoByName(string _nomeFile) + { + FileInfo _fi; + try + { + _fi = new FileInfo(GetPath(_workPath + "\\" + _nomeFile)); + } + catch (Exception exc) + { + Log.Error($"Eccezione getFileInfoByName tramite getPath | {_nomeFile} | riprovo senza getPath{Environment.NewLine}{exc}"); + _fi = new FileInfo(_workPath + "\\" + _nomeFile); + } + return _fi; + } + + /// + /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente + /// come workpath + nomefile + /// + /// The _path. + /// The _nome file. + /// + private FileInfo getFileInfoByName(string _path, string _nomeFile) + { + FileInfo _fi; + try + { + _fi = new FileInfo(GetPath(_path + _nomeFile)); + } + catch (Exception exc) + { + Log.Error($"Eccezione getFileInfoByName tramite getPath | {_nomeFile} | riprovo senza getPath{Environment.NewLine}{exc}"); + _fi = new FileInfo(_path + "\\" + _nomeFile); + } + return _fi; + } + + /// + /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente + /// come workpath + nomefile + /// + /// cartella file + /// nome file + /// indica se il path sia assoluto + /// + private FileInfo getFileInfoByName(string _path, string _nomeFile, bool absPath) + { + FileInfo _fi; + if (absPath) + { + _fi = new FileInfo(_path + "\\" + _nomeFile); + } + else + { + _fi = getFileInfoByName(_path, _nomeFile); + } + return _fi; + } + + /// + /// setta le directory + /// + /// + private void setDirs(string _path) + { + _workPath = _path; + } + + #endregion Private Methods } -} +} \ No newline at end of file diff --git a/SteamWare/licenseMan.cs b/SteamWare/licenseMan.cs index cd318a5..815de13 100644 --- a/SteamWare/licenseMan.cs +++ b/SteamWare/licenseMan.cs @@ -1,89 +1,117 @@ -using System; +using NLog; +using System; namespace SteamWare { - /// - /// gestione licenze applicativi - /// - public class licenseMan - { /// - /// numero di licenze attive per cliente/applicativo + /// gestione licenze applicativi /// - /// - /// - /// - public static int getLicenseNum(string cliente, string applicativo) + public class licenseMan { - // !!!FARE!!! chiamata a webservice 1/mese - int answ = 1; - // molto hard-coded e discutibile... licenze "perenni" - switch (cliente) - { - case "SteamWare": - answ = 50; - break; - case "ETS": - if (applicativo == "GPW") - { - answ = 35; - } - break; - case "SPS": - if (applicativo == "GPW") - { - answ = 11; - } - break; - default: - answ = 1; - break; - } + #region Public Constructors - return answ; - } - /// - /// Fornisce chiave MD5 x un cliente/applicativo/expiryDate - /// - /// - /// - /// - /// - /// - public static string getAuthKey(string cliente, string applicativo, int licenze, DateTime expiryDate) - { - string answ = ""; - // algoritmo MD5 formato cliente#applicativo#expDate, via SQLdiventa - // SELECT CONVERT(VARCHAR(32), HashBytes('MD5', 'ETS#GPW#2013/12/31'), 2) - string plainAuthKey = string.Format("{0}#{1}-{2}%{3}%", cliente, applicativo.PadLeft(20, '-'), expiryDate.ToString("yyyy/MM/dd"), licenze); - string passPhrase = string.Format("{0}|{1}", cliente.PadLeft(50, ':'), applicativo); - answ = SteamCrypto.EncryptString(plainAuthKey, passPhrase); // uso combinazione cliente+applicativo come passphrase! - return answ; - } - /// - /// restituisce data decodificata da authKey + applicazione + cliente... - /// - /// The cliente. - /// The applicativo. - /// The licenze. - /// The authentication key. - /// - public static DateTime expiryDateByAuthKey(string cliente, string applicativo, int licenze, string authKey) - { - DateTime answ = DateTime.Today.AddYears(-10); + public licenseMan() + { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } + } - string plainAuthKey = ""; - try - { - string passPhrase = string.Format("{0}|{1}", cliente.PadLeft(50, ':'), applicativo); - plainAuthKey = SteamCrypto.DecryptString(authKey, passPhrase); // uso combinazione cliente+applicativo come passphrase! - answ = Convert.ToDateTime(plainAuthKey.Replace(string.Format("{0}#{1}-", cliente, applicativo.PadLeft(20, '-')), "").Replace(string.Format("%{0}%", licenze), "")); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore decodifica auth key:{0}AuthKey: {1}{0}cliente:{2}{0}applicativo:{3}{0}errore:{4}", Environment.NewLine, authKey, cliente, applicativo, exc), tipoLog.EXCEPTION); - } - return answ; + #endregion Public Constructors + + #region Public Methods + + /// + /// restituisce data decodificata da authKey + applicazione + cliente... + /// + /// The cliente. + /// The applicativo. + /// The licenze. + /// The authentication key. + /// + public static DateTime expiryDateByAuthKey(string cliente, string applicativo, int licenze, string authKey) + { + DateTime answ = DateTime.Today.AddYears(-10); + + string plainAuthKey = ""; + try + { + string passPhrase = string.Format("{0}|{1}", cliente.PadLeft(50, ':'), applicativo); + plainAuthKey = SteamCrypto.DecryptString(authKey, passPhrase); // uso combinazione cliente+applicativo come passphrase! + answ = Convert.ToDateTime(plainAuthKey.Replace(string.Format("{0}#{1}-", cliente, applicativo.PadLeft(20, '-')), "").Replace(string.Format("%{0}%", licenze), "")); + } + catch (Exception exc) + { + Log.Error($"Eccezione expiryDateByAuthKey | AuthKey: {authKey} | cliente:{cliente} | applicativo: {applicativo}{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// Fornisce chiave MD5 x un cliente/applicativo/expiryDate + /// + /// + /// + /// + /// + /// + public static string getAuthKey(string cliente, string applicativo, int licenze, DateTime expiryDate) + { + string answ = ""; + // algoritmo MD5 formato cliente#applicativo#expDate, via SQLdiventa SELECT + // CONVERT(VARCHAR(32), HashBytes('MD5', 'ETS#GPW#2013/12/31'), 2) + string plainAuthKey = string.Format("{0}#{1}-{2}%{3}%", cliente, applicativo.PadLeft(20, '-'), expiryDate.ToString("yyyy/MM/dd"), licenze); + string passPhrase = string.Format("{0}|{1}", cliente.PadLeft(50, ':'), applicativo); + answ = SteamCrypto.EncryptString(plainAuthKey, passPhrase); // uso combinazione cliente+applicativo come passphrase! + return answ; + } + + /// + /// numero di licenze attive per cliente/applicativo + /// + /// + /// + /// + public static int getLicenseNum(string cliente, string applicativo) + { + // !!!FARE!!! chiamata a webservice 1/mese + int answ = 1; + // molto hard-coded e discutibile... licenze "perenni" + switch (cliente) + { + case "SteamWare": + answ = 50; + break; + + case "ETS": + if (applicativo == "GPW") + { + answ = 35; + } + break; + + case "SPS": + if (applicativo == "GPW") + { + answ = 11; + } + break; + + default: + answ = 1; + break; + } + + return answ; + } + + #endregion Public Methods + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields } - } -} +} \ No newline at end of file diff --git a/SteamWare/packages.config b/SteamWare/packages.config index 51150d1..fc15aa2 100644 --- a/SteamWare/packages.config +++ b/SteamWare/packages.config @@ -17,7 +17,6 @@ - diff --git a/SteamWare/utils.cs b/SteamWare/utils.cs index d17037c..fcfae70 100644 --- a/SteamWare/utils.cs +++ b/SteamWare/utils.cs @@ -1,5 +1,5 @@ using AegisImplicitMail; -using System.Net.Mail; +using NLog; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,6 +8,7 @@ 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; @@ -39,20 +40,6 @@ namespace SteamWare /// 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 /// @@ -65,74 +52,6 @@ namespace SteamWare #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 /// @@ -140,9 +59,12 @@ namespace SteamWare /// /// stringa da splittare /// delimitatore ricercato - /// true=il delimiter � un blocco unico, false=qualsiasi oggetto del delimiter fa split (come split base) + /// + /// true=il delimiter � un blocco unico, false=qualsiasi oggetto del delimiter fa split + /// (come split base) + /// /// - /// 0 -> Binary=CaseSensitive, 1 -> Text=case insensitive + /// 0 -> Binary=CaseSensitive, 1 -> Text=case insensitive /// public static string[] Split(string Expression, string Delimiter, bool SingleSeparator, int Count, ComparisonMethod Compare) { @@ -270,6 +192,88 @@ namespace SteamWare } #endregion Public Methods + + #region Private Fields + + /// + /// Delimiter con cui splittare + /// + private static string m_Delimiter; + + /// + /// stringa da splittare + /// + private static string m_Expression; + + #endregion Private Fields + + #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 } } @@ -296,7 +300,7 @@ namespace SteamWare #region Public Properties /// - /// indica se sia valido il dato, ovvero inizio e fine > 0 e FINE >= INIZIO + /// indica se sia valido il dato, ovvero inizio e fine > 0 e FINE >= INIZIO /// public bool isValid { @@ -360,49 +364,37 @@ namespace SteamWare /// /// Gets or sets the cod turno. /// - /// - /// The cod turno. - /// + /// The cod turno. public string codTurno { get; set; } /// /// Gets or sets the durata minuti. /// - /// - /// The durata minuti. - /// + /// The durata minuti. public int durataMinuti { get; set; } /// /// Gets or sets the fine. /// - /// - /// The fine. - /// + /// The fine. public DateTime fine { get; set; } /// /// Gets or sets the inizio. /// - /// - /// The inizio. - /// + /// The inizio. public DateTime inizio { get; set; } /// /// Gets or sets the periodo. /// - /// - /// The periodo. - /// + /// The periodo. public intervalloDate periodo { get; set; } /// /// Gets or sets the t number. /// - /// - /// The t number. - /// + /// The t number. public int TNum { get; set; } #endregion Public Properties @@ -411,8 +403,8 @@ namespace SteamWare /// /// 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. + /// + /// A strongly type DataTable. A DataTable of type T will be returned from the DataSet. /// public static class DataSetAdapter where T : DataTable, new() @@ -420,8 +412,7 @@ namespace SteamWare #region Public Methods /// - /// Convert the first DataTable from a DataSet to a - /// strongly-typed data table. + /// Convert the first DataTable from a DataSet to a strongly-typed data table. /// public static T convert(DataSet dataSet) { @@ -440,8 +431,7 @@ namespace SteamWare } /// - /// Convert an ordinary DataTable to a strongly-typed - /// data table. + /// Convert an ordinary DataTable to a strongly-typed data table. /// public static T convert(DataTable dataTable) { @@ -451,8 +441,7 @@ namespace SteamWare } T stronglyTyped = new T(); - // add data from the regular DataTable to the - // strongly typed DataTable. + // add data from the regular DataTable to the strongly typed DataTable. stronglyTyped.Merge(dataTable, true, MissingSchemaAction.Ignore); return stronglyTyped; } @@ -528,6 +517,10 @@ namespace SteamWare /// public datario() { + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } } #endregion Public Constructors @@ -578,14 +571,14 @@ namespace SteamWare CultureInfo cInfo = new CultureInfo(culture); if (doLog) { - logger.lg.scriviLog(string.Format("Valore txt:{1}", Environment.NewLine, dataOra), tipoLog.INFO); + Log.Info(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); + Log.Info(string.Format("{0}Valore txt:{1}{0}Valore conv:{2}", Environment.NewLine, dataOra, answ), tipoLog.INFO); } if (!fatto) @@ -594,7 +587,7 @@ namespace SteamWare } if (doLog) { - logger.lg.scriviLog(string.Format("{0}Valore txt:{1}{0}Valore conv BIS:{2}", Environment.NewLine, dataOra, answ), tipoLog.INFO); + Log.Info(string.Format("{0}Valore txt:{1}{0}Valore conv BIS:{2}", Environment.NewLine, dataOra, answ), tipoLog.INFO); } return answ; @@ -677,7 +670,8 @@ namespace SteamWare } /// - /// 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 + /// 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 /// /// /// @@ -793,7 +787,8 @@ namespace SteamWare } /// - /// restituisce l'intervallo dell'anno corrente per la data indicata (dal giorno 1 all'indomani della data indicata) + /// restituisce l'intervallo dell'anno corrente per la data indicata (dal giorno 1 + /// all'indomani della data indicata) /// /// /// @@ -806,7 +801,8 @@ namespace SteamWare } /// - /// restituisce l'intervallo del mese corrente per la data indicata (dal giorno 1 all'indomani della data indicata) + /// restituisce l'intervallo del mese corrente per la data indicata (dal giorno 1 + /// all'indomani della data indicata) /// /// /// @@ -877,6 +873,12 @@ namespace SteamWare } #endregion Public Methods + + #region Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields } /// @@ -985,25 +987,6 @@ namespace SteamWare /// 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 /// @@ -1026,7 +1009,11 @@ namespace SteamWare /// public gestEmail(string smtpCli) { - logger.lg.scriviLog(string.Format("[Modulo gestEmail]: avviato con parametro smtp {0} - SENZA USER/PWD", smtpCli), tipoLog.STARTUP); + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } + Log.Info($"[Modulo gestEmail]: avviato con parametro smtp {smtpCli} - SENZA USER/PWD"); _smtpCli = smtpCli; _username = ""; _password = ""; @@ -1040,7 +1027,11 @@ namespace SteamWare /// 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); + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } + Log.Info($"[Modulo gestEmail]: avviato con parametro smtp {smtpCli} ed utente {user}"); _smtpCli = smtpCli; _username = user; _password = pwd; @@ -1053,7 +1044,11 @@ namespace SteamWare /// public gestEmail(string smtpCli, string logDir) { - logger.lg.scriviLog(string.Format("[Modulo gestEmail]: avviato con parametro smtp {0} e logdir", smtpCli), tipoLog.STARTUP); + if (Log == null) + { + Log = LogManager.GetCurrentClassLogger(); + } + Log.Info($"[Modulo gestEmail]: avviato con parametro smtp {smtpCli} e logdir {logDir}"); _smtpCli = smtpCli; _username = ""; _password = ""; @@ -1061,6 +1056,168 @@ namespace SteamWare #endregion Public Constructors + #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); + Log.Info(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) + { + Log.Info(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; + // setup numero tentativi (default 3) + var reqRetry = memLayer.ML.CRI("_smtpMaxRetry"); + int numTry = reqRetry > 0 ? reqRetry : 3; + // ciclo fino a che non viene inviato con successo... + while (!fatto || numTry > 0) + { + numTry--; + //manda email... + try + { + fatto = mandaEmailNoLog(_mailFrom, _mailTo, _oggetto, _corpo, _allegati); + Log.Info(string.Format("Email inviata: oggetto: {0}, corpo:{1}{1}{2}", _oggetto, Environment.NewLine, _corpo), tipoLog.INFO); + } + catch (Exception e) + { + Log.Info(string.Format("ERRORE! Email NON INVIATA!oggetto: {0} corpo: {1} eccezione:{2}{3}", _oggetto, _corpo, Environment.NewLine, e), tipoLog.EXCEPTION); + fatto = false; + } + // se non inviato pausa 250-750 msec... + if (!fatto) + { + Random rnd = new Random(); + int nextWait = 250 + rnd.Next(500); + Log.Info($"Errore email non inviata, attesa di {nextWait}ms prima di riprovare, restano {numTry} tentativi"); + Thread.Sleep(nextWait); + } + } + 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 + + #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 Private Fields + + private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); + + #endregion Private Fields + #region Private Methods /// @@ -1072,24 +1229,23 @@ namespace SteamWare { if (e.UserState != null) { - logger.lg.scriviLog(e.UserState.ToString()); + Log.Info(e.UserState.ToString()); } if (e.Cancelled) { - logger.lg.scriviLog("Invio cancellato"); + Log.Info("Invio cancellato"); } Console.Out.WriteLine("is it canceled? " + e.Cancelled); if (e.Error != null) { - logger.lg.scriviLog("Invio con errori: " + e.Error.Message); + Log.Info("Invio con errori: " + e.Error.Message); } } /// - /// Invia con metodo del client AIM x compatilbiiltà SSL implicito and co - /// https://sourceforge.net/projects/netimplicitssl/ + /// Invia con metodo del client AIM x compatilbiiltà SSL implicito and co https://sourceforge.net/projects/netimplicitssl/ /// /// email mittente /// email destinatario @@ -1220,149 +1376,12 @@ namespace SteamWare 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); + Log.Info(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; - // setup numero tentativi (default 3) - var reqRetry = memLayer.ML.CRI("_smtpMaxRetry"); - int numTry = reqRetry > 0 ? reqRetry : 3; - // ciclo fino a che non viene inviato con successo... - while (!fatto || numTry > 0) - { - numTry--; - //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); - fatto = false; - } - // se non inviato pausa 250-750 msec... - if (!fatto) - { - Random rnd = new Random(); - int nextWait = 250 + rnd.Next(500); - logger.lg.scriviLog($"Errore email non inviata, attesa di {nextWait}ms prima di riprovare, restano {numTry} tentativi"); - Thread.Sleep(nextWait); - } - } - 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 } /// @@ -1373,7 +1392,8 @@ namespace SteamWare #region Public Methods /// - /// restituisce la stringa di codice javascript x conferma client comprensiva di messaggio tradotto specifico + /// restituisce la stringa di codice javascript x conferma client comprensiva di messaggio + /// tradotto specifico /// /// /// @@ -1383,7 +1403,8 @@ namespace SteamWare } /// - /// restituisce la stringa di codice javascript x conferma client comprensiva di messaggio tradotto specifico + /// restituisce la stringa di codice javascript x conferma client comprensiva di messaggio + /// tradotto specifico /// /// /// @@ -1414,7 +1435,7 @@ namespace SteamWare #region Public Methods /// - /// converte da numero a percentuale (es 0.053 --> 5,3%) + /// converte da numero a percentuale (es 0.053 --> 5,3%) /// /// /// @@ -1434,7 +1455,7 @@ namespace SteamWare } /// - /// converte da percentuale a numero (es 5,3% --> 0.053) + /// converte da percentuale a numero (es 5,3% --> 0.053) /// /// /// @@ -1466,7 +1487,8 @@ namespace SteamWare #region Public Methods /// - /// Effettua il calcolo del rapporto numeratore/denominatore come DECIMAL con gestione denominatore != 0 + /// Effettua il calcolo del rapporto numeratore/denominatore come DECIMAL con gestione + /// denominatore != 0 /// /// numeratore /// denominatore @@ -1506,9 +1528,8 @@ namespace SteamWare 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 + // 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)); @@ -1560,9 +1581,8 @@ namespace SteamWare 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 + // 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)); @@ -1621,12 +1641,10 @@ namespace SteamWare // 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. + // 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. + // 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")); @@ -1672,7 +1690,7 @@ namespace SteamWare #region Public Methods /// - /// conversione da tempo minuti centesimali a minuti/secondi + /// conversione da tempo minuti centesimali a minuti/secondi /// /// /// @@ -1737,7 +1755,7 @@ namespace SteamWare } /// - /// classi helper gestione URL + /// classi helper gestione URL /// public class urlUtils {