From 593b2ff3483cc814258cdb51bbc1741731a7294d Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 14 Feb 2020 09:17:44 +0100 Subject: [PATCH 1/8] Riorganizzaizone interna metodi + avanzamento con gestione code --- LPA/App.config | 1 - LPA/LPA.csproj | 5 +- LPA/MainForm.Designer.cs | 137 ++++++--- LPA/MainForm.cs | 328 ++++++++++++++------- LPA/MainForm.resx | 3 + LPA/{queueSetup.json => conf/.placeholder} | 0 LPA/conf/queueSetup.json | 1 + 7 files changed, 315 insertions(+), 160 deletions(-) rename LPA/{queueSetup.json => conf/.placeholder} (100%) create mode 100644 LPA/conf/queueSetup.json diff --git a/LPA/App.config b/LPA/App.config index cbd9126..48337e1 100644 --- a/LPA/App.config +++ b/LPA/App.config @@ -7,7 +7,6 @@ - diff --git a/LPA/LPA.csproj b/LPA/LPA.csproj index b9c0e8c..3b3d516 100644 --- a/LPA/LPA.csproj +++ b/LPA/LPA.csproj @@ -181,7 +181,10 @@ True Resources.resx - + + Always + + Always diff --git a/LPA/MainForm.Designer.cs b/LPA/MainForm.Designer.cs index 286b115..af0efda 100644 --- a/LPA/MainForm.Designer.cs +++ b/LPA/MainForm.Designer.cs @@ -45,30 +45,32 @@ this.tabSetup = new System.Windows.Forms.TabPage(); this.btnStart = new System.Windows.Forms.Button(); this.btnStop = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.lblQueueCount = new System.Windows.Forms.Label(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.longTimer = new System.Windows.Forms.Timer(this.components); this.statusStrip1.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabStatus.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvQueueStatus)).BeginInit(); this.tabSetup.SuspendLayout(); + this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // lbPrinters // this.lbPrinters.FormattingEnabled = true; - this.lbPrinters.ItemHeight = 16; - this.lbPrinters.Location = new System.Drawing.Point(337, 43); - this.lbPrinters.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.lbPrinters.Location = new System.Drawing.Point(253, 35); this.lbPrinters.Name = "lbPrinters"; - this.lbPrinters.Size = new System.Drawing.Size(291, 196); + this.lbPrinters.Size = new System.Drawing.Size(219, 160); this.lbPrinters.TabIndex = 1; this.lbPrinters.SelectedIndexChanged += new System.EventHandler(this.lbPrinters_SelectedIndexChanged); // // btnSetQueuePrinter // - this.btnSetQueuePrinter.Location = new System.Drawing.Point(337, 7); - this.btnSetQueuePrinter.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.btnSetQueuePrinter.Location = new System.Drawing.Point(253, 6); this.btnSetQueuePrinter.Name = "btnSetQueuePrinter"; - this.btnSetQueuePrinter.Size = new System.Drawing.Size(292, 28); + this.btnSetQueuePrinter.Size = new System.Drawing.Size(219, 23); this.btnSetQueuePrinter.TabIndex = 2; this.btnSetQueuePrinter.Text = "Save Queue+Printer"; this.btnSetQueuePrinter.UseVisualStyleBackColor = true; @@ -81,10 +83,9 @@ this.lblAppName, this.progBar, this.lblStatus}); - this.statusStrip1.Location = new System.Drawing.Point(0, 600); + this.statusStrip1.Location = new System.Drawing.Point(0, 487); this.statusStrip1.Name = "statusStrip1"; - this.statusStrip1.Padding = new System.Windows.Forms.Padding(1, 0, 19, 0); - this.statusStrip1.Size = new System.Drawing.Size(1047, 26); + this.statusStrip1.Size = new System.Drawing.Size(785, 22); this.statusStrip1.TabIndex = 6; this.statusStrip1.Text = "statusStrip1"; // @@ -92,19 +93,19 @@ // this.lblAppName.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold); this.lblAppName.Name = "lblAppName"; - this.lblAppName.Size = new System.Drawing.Size(80, 20); + this.lblAppName.Size = new System.Drawing.Size(62, 17); this.lblAppName.Text = "AppName"; // // progBar // this.progBar.Name = "progBar"; - this.progBar.Size = new System.Drawing.Size(133, 18); + this.progBar.Size = new System.Drawing.Size(100, 16); this.progBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous; // // lblStatus // this.lblStatus.Name = "lblStatus"; - this.lblStatus.Size = new System.Drawing.Size(27, 20); + this.lblStatus.Size = new System.Drawing.Size(22, 17); this.lblStatus.Text = "---"; // // uiTimer @@ -114,20 +115,17 @@ // lbPrintQueue // this.lbPrintQueue.FormattingEnabled = true; - this.lbPrintQueue.ItemHeight = 16; - this.lbPrintQueue.Location = new System.Drawing.Point(8, 43); - this.lbPrintQueue.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.lbPrintQueue.Location = new System.Drawing.Point(6, 35); this.lbPrintQueue.Name = "lbPrintQueue"; - this.lbPrintQueue.Size = new System.Drawing.Size(307, 196); + this.lbPrintQueue.Size = new System.Drawing.Size(231, 160); this.lbPrintQueue.TabIndex = 8; this.lbPrintQueue.SelectedIndexChanged += new System.EventHandler(this.lbPrintQueue_SelectedIndexChanged); // // lbtgetPrintQueue // - this.lbtgetPrintQueue.Location = new System.Drawing.Point(8, 7); - this.lbtgetPrintQueue.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.lbtgetPrintQueue.Location = new System.Drawing.Point(6, 6); this.lbtgetPrintQueue.Name = "lbtgetPrintQueue"; - this.lbtgetPrintQueue.Size = new System.Drawing.Size(308, 28); + this.lbtgetPrintQueue.Size = new System.Drawing.Size(231, 23); this.lbtgetPrintQueue.TabIndex = 9; this.lbtgetPrintQueue.Text = "Update Print Queue"; this.lbtgetPrintQueue.UseVisualStyleBackColor = true; @@ -140,21 +138,19 @@ | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.tabStatus); this.tabControl1.Controls.Add(this.tabSetup); - this.tabControl1.Location = new System.Drawing.Point(16, 73); - this.tabControl1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.tabControl1.Location = new System.Drawing.Point(12, 59); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; - this.tabControl1.Size = new System.Drawing.Size(1015, 523); + this.tabControl1.Size = new System.Drawing.Size(761, 425); this.tabControl1.TabIndex = 10; // // tabStatus // this.tabStatus.Controls.Add(this.dgvQueueStatus); - this.tabStatus.Location = new System.Drawing.Point(4, 25); - this.tabStatus.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.tabStatus.Location = new System.Drawing.Point(4, 22); this.tabStatus.Name = "tabStatus"; - this.tabStatus.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); - this.tabStatus.Size = new System.Drawing.Size(1007, 494); + this.tabStatus.Padding = new System.Windows.Forms.Padding(3, 3, 3, 3); + this.tabStatus.Size = new System.Drawing.Size(753, 399); this.tabStatus.TabIndex = 0; this.tabStatus.Text = "Status"; this.tabStatus.UseVisualStyleBackColor = true; @@ -164,11 +160,10 @@ this.dgvQueueStatus.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dgvQueueStatus.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvQueueStatus.Dock = System.Windows.Forms.DockStyle.Fill; - this.dgvQueueStatus.Location = new System.Drawing.Point(4, 4); - this.dgvQueueStatus.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.dgvQueueStatus.Location = new System.Drawing.Point(3, 3); this.dgvQueueStatus.Name = "dgvQueueStatus"; this.dgvQueueStatus.RowHeadersWidth = 51; - this.dgvQueueStatus.Size = new System.Drawing.Size(999, 486); + this.dgvQueueStatus.Size = new System.Drawing.Size(747, 393); this.dgvQueueStatus.TabIndex = 0; // // tabSetup @@ -177,11 +172,10 @@ this.tabSetup.Controls.Add(this.lbtgetPrintQueue); this.tabSetup.Controls.Add(this.lbPrinters); this.tabSetup.Controls.Add(this.lbPrintQueue); - this.tabSetup.Location = new System.Drawing.Point(4, 25); - this.tabSetup.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.tabSetup.Location = new System.Drawing.Point(4, 22); this.tabSetup.Name = "tabSetup"; - this.tabSetup.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); - this.tabSetup.Size = new System.Drawing.Size(1007, 494); + this.tabSetup.Padding = new System.Windows.Forms.Padding(3, 3, 3, 3); + this.tabSetup.Size = new System.Drawing.Size(753, 399); this.tabSetup.TabIndex = 1; this.tabSetup.Text = "Setup"; this.tabSetup.UseVisualStyleBackColor = true; @@ -189,10 +183,9 @@ // btnStart // this.btnStart.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.btnStart.Location = new System.Drawing.Point(16, 16); - this.btnStart.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.btnStart.Location = new System.Drawing.Point(3, 3); this.btnStart.Name = "btnStart"; - this.btnStart.Size = new System.Drawing.Size(125, 49); + this.btnStart.Size = new System.Drawing.Size(94, 38); this.btnStart.TabIndex = 11; this.btnStart.Text = "Start"; this.btnStart.UseVisualStyleBackColor = true; @@ -201,25 +194,71 @@ // btnStop // this.btnStop.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.btnStop.Location = new System.Drawing.Point(167, 16); - this.btnStop.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.btnStop.Location = new System.Drawing.Point(103, 3); this.btnStop.Name = "btnStop"; - this.btnStop.Size = new System.Drawing.Size(125, 49); + this.btnStop.Size = new System.Drawing.Size(94, 38); this.btnStop.TabIndex = 12; this.btnStop.Text = "Stop"; this.btnStop.UseVisualStyleBackColor = true; this.btnStop.Click += new System.EventHandler(this.btnStop_Click); // + // label1 + // + this.label1.AutoSize = true; + this.label1.Dock = System.Windows.Forms.DockStyle.Right; + this.label1.Location = new System.Drawing.Point(633, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(50, 44); + this.label1.TabIndex = 13; + this.label1.Text = "Tot code"; + this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + // + // lblQueueCount + // + this.lblQueueCount.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Right))); + this.lblQueueCount.AutoSize = true; + this.lblQueueCount.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblQueueCount.Location = new System.Drawing.Point(720, 0); + this.lblQueueCount.Name = "lblQueueCount"; + this.lblQueueCount.Size = new System.Drawing.Size(38, 44); + this.lblQueueCount.TabIndex = 14; + this.lblQueueCount.Text = "00"; + this.lblQueueCount.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel1.ColumnCount = 5; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 75F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 75F)); + this.tableLayoutPanel1.Controls.Add(this.btnStart, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.btnStop, 1, 0); + this.tableLayoutPanel1.Controls.Add(this.label1, 3, 0); + this.tableLayoutPanel1.Controls.Add(this.lblQueueCount, 4, 0); + this.tableLayoutPanel1.Location = new System.Drawing.Point(12, 9); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 1; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(761, 44); + this.tableLayoutPanel1.TabIndex = 15; + // + // longTimer + // + this.longTimer.Interval = 60000; + // // MainForm // - this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1047, 626); - this.Controls.Add(this.btnStop); - this.Controls.Add(this.btnStart); + this.ClientSize = new System.Drawing.Size(785, 509); + this.Controls.Add(this.tableLayoutPanel1); this.Controls.Add(this.tabControl1); this.Controls.Add(this.statusStrip1); - this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.Name = "MainForm"; this.Text = "Steamware LPA"; this.statusStrip1.ResumeLayout(false); @@ -228,6 +267,8 @@ this.tabStatus.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgvQueueStatus)).EndInit(); this.tabSetup.ResumeLayout(false); + this.tableLayoutPanel1.ResumeLayout(false); + this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); @@ -250,6 +291,10 @@ private System.Windows.Forms.Button btnStop; private System.Windows.Forms.ToolStripStatusLabel lblStatus; private System.Windows.Forms.DataGridView dgvQueueStatus; - } + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Label lblQueueCount; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.Timer longTimer; + } } diff --git a/LPA/MainForm.cs b/LPA/MainForm.cs index bd72e53..06211dc 100644 --- a/LPA/MainForm.cs +++ b/LPA/MainForm.cs @@ -15,6 +15,8 @@ namespace LPA { public partial class MainForm : Form { + #region variabili di base + /// /// Lista delle code di stampa da gestire /// @@ -38,7 +40,7 @@ namespace LPA /// /// File conf x setup code /// - protected string queueSetupFile; + protected string queueSetupFile = "queueSetup.json"; /// /// Configurazione CORRENTE delle code di stampa (coda --> printer disponibile) /// @@ -48,6 +50,10 @@ namespace LPA /// private BindingSource pqBindSource = new BindingSource(); + #endregion + + #region init form + /// /// Classe apertura /// @@ -72,13 +78,183 @@ namespace LPA setupQueue(); setupDGV(); } - + /// + /// Setup parametri base di configurazione + /// + private void setupConf() + { + baseDir = AppDomain.CurrentDomain.BaseDirectory; + serverBaseAddr = memLayer.ML.CRS("serverBaseAddr"); + localReportPath = $"{AppDomain.CurrentDomain.BaseDirectory}\\{memLayer.ML.CRS("localReportPath")}\\"; + } + /// + /// Fix timers + /// + private void setupTimers() + { + uiTimer.Interval = 50; + mainTimer.Interval = 900; + longTimer.Interval = 60000; + uiTimer.Tick += UiTimer_Tick; + mainTimer.Tick += MainTimer_Tick; + longTimer.Tick += LongTimer_Tick; + uiTimer.Start(); + mainTimer.Start(); + longTimer.Start(); + } + /// + /// Setup code di stampa disponibili da server + /// + private void setupQueuePrinter() + { + queueSetupConf = queueSetupJson; + //printQueue currPrintQueue; + //// init oggetto code... + //foreach (var item in queueSetupConf) + //{ + // currPrintQueue = new printQueue() + // { + // QueueName = item.Key, + // Printer = item.Value, + // isRunning = spoolerRun, + // startTime = DateTime.Now + // }; + // queueStatus.Add(currPrintQueue); + //} + } + /// + /// Setup dei bottoni stato start/stop + /// + private void setupButtons() + { + btnStart.Enabled = !spoolerRun; + btnStop.Enabled = spoolerRun; + lblStatus.ForeColor = spoolerRun ? Color.Green : Color.OrangeRed; + lblStatus.Text = spoolerRun ? "Running" : "Stopped"; + } + /// + /// Setup oggetto DGV + /// private void setupDGV() { // gestione eventi binding source pqBindSource.AddingNew += qpBSList_AddingNew; pqBindSource.ListChanged += qpBSList_ListChanged; } + + + #endregion + + #region metodi interni ed helpers + + /// + /// Chiamata async URL + /// + /// + /// + protected string callUrl(string url2call) + { + string result = ""; + // recupero dati + var taskRes = Task.Run(() => utils.getPageAsync(url2call)); + taskRes.Wait(); + result = taskRes.Result; + return result; + } + /// + /// Configurazione coda stampa da json file + /// + protected Dictionary queueSetupJson + { + get + { + Dictionary answ = new Dictionary(); + string fullPath = $"{baseDir}conf\\{queueSetupFile}"; + // cerco file x leggere conf... + if (File.Exists(fullPath)) + { + try + { + string rawData = File.ReadAllText(fullPath); + if (!string.IsNullOrEmpty(rawData)) + { + answ = JsonConvert.DeserializeObject>(rawData); + } + } + catch (Exception exc) + { + Log.Instance.Error(exc, "Errore in decodifica file queueSetup"); + } + } + return answ; + } + set + { + string fullPath = $"{baseDir}conf\\{queueSetupFile}"; + string rawData = JsonConvert.SerializeObject(value); + File.WriteAllText(fullPath, rawData); + } + } + + #endregion + + #region gestione cicli di esecuzione + + /// + /// Timer principale di refresh + /// + /// + /// + private void MainTimer_Tick(object sender, EventArgs e) + { + // effettuo chiamata coda stampa... + refreshQueueStsatus(); + // aggiorno visualizzazione + updateDGV(); + } + /// + /// Timer lungo periodo (salvataggi) + /// + /// + /// + private void LongTimer_Tick(object sender, EventArgs e) + { + // salvo conf ... + queueSetupJson = queueSetupConf; + // salvo + } + /// + /// Rrefresh interfaccia + /// + /// + /// + private void UiTimer_Tick(object sender, EventArgs e) + { + progBar.Increment(1); + if (progBar.Value >= 100) + { + progBar.Value = 0; + } + } + + #endregion + + #region interazione (buttons & co) + + private void btnStart_Click(object sender, EventArgs e) + { + spoolerRun = true; + setupButtons(); + } + + private void btnStop_Click(object sender, EventArgs e) + { + spoolerRun = false; + setupButtons(); + } + + #endregion + /// /// Evento cambio /// @@ -107,76 +283,7 @@ namespace LPA dgvQueueStatus.DataSource = elencoCode; dgvQueueStatus.Invalidate(); } - /// - /// Setup parametri base du configurazione - /// - private void setupConf() - { - baseDir = AppDomain.CurrentDomain.BaseDirectory; - queueSetupFile = memLayer.ML.CRS("queueSetupFile"); - serverBaseAddr = memLayer.ML.CRS("serverBaseAddr"); - localReportPath = $"{AppDomain.CurrentDomain.BaseDirectory}\\{memLayer.ML.CRS("localReportPath")}\\"; - } - private void setupQueuePrinter() - { - queueSetupConf = queueSetupJson; - //printQueue currPrintQueue; - //// init oggetto code... - //foreach (var item in queueSetupConf) - //{ - // currPrintQueue = new printQueue() - // { - // QueueName = item.Key, - // Printer = item.Value, - // isRunning = spoolerRun, - // startTime = DateTime.Now - // }; - // queueStatus.Add(currPrintQueue); - //} - } - /// - /// Configurazione coda stampa da json file - /// - protected Dictionary queueSetupJson - { - get - { - Dictionary answ = new Dictionary(); - string fullPath = $"{baseDir}{queueSetupFile}"; - // cerco file x leggere conf... - if (File.Exists(fullPath)) - { - try - { - string rawData = File.ReadAllText(fullPath); - if (!string.IsNullOrEmpty(rawData)) - { - answ = JsonConvert.DeserializeObject>(rawData); - } - } - catch (Exception exc) - { - Log.Instance.Error(exc, "Errore in decodifica file queueSetup"); - } - } - return answ; - } - set - { - string fullPath = $"{baseDir}{queueSetupFile}"; - string rawData = JsonConvert.SerializeObject(value); - File.WriteAllText(fullPath, rawData); - } - } - - private void setupButtons() - { - btnStart.Enabled = !spoolerRun; - btnStop.Enabled = spoolerRun; - lblStatus.ForeColor = spoolerRun ? Color.Green : Color.OrangeRed; - lblStatus.Text = spoolerRun ? "Running" : "Stopped"; - } /// /// Aggiornamento code stampa disponibili @@ -187,13 +294,8 @@ namespace LPA lbPrintQueue.Items.Clear(); // scarico TUTTI i report definiti List listQueue = new List(); - string rawData = ""; string url2call = $"{serverBaseAddr}/api/PrintQueueConf"; - // recupero dati - var taskRes = Task.Run(() => utils.getPageAsync(url2call)); - taskRes.Wait(); - - rawData = taskRes.Result; + string rawData = callUrl(url2call); if (!string.IsNullOrEmpty(rawData)) { // deserializzo @@ -218,37 +320,49 @@ namespace LPA } showPrinterList(); } - /// - /// Fix timers - /// - private void setupTimers() - { - uiTimer.Interval = 50; - mainTimer.Interval = 500; - uiTimer.Tick += UiTimer_Tick; - mainTimer.Tick += MainTimer_Tick; - uiTimer.Start(); - mainTimer.Start(); - } - private void MainTimer_Tick(object sender, EventArgs e) + private void refreshQueueStsatus() { - // effettuo chiamata coda stampa... - - // aggiorno visualizzazione - updateDGV(); - } - - private void UiTimer_Tick(object sender, EventArgs e) - { - progBar.Increment(1); - if (progBar.Value >= 100) + // verifico ed aggiorno quantità coda + int numTot = 0; + string url2call = $"{serverBaseAddr}/api/PrintQueue"; + string rawData = callUrl(url2call); + if (!string.IsNullOrEmpty(rawData)) { - progBar.Value = 0; + // deserializzo + int.TryParse(rawData, out numTot); + lblQueueCount.Text = numTot.ToString("000"); + if (numTot > 0) + { + // se ho stampe in coda --> verifico code gestite + foreach (var coda in queueSetupConf) + { + url2call = $"{serverBaseAddr}/api/PrintQueue/{coda.Key}"; + rawData = callUrl(url2call); + if (!string.IsNullOrEmpty(rawData)) + { + // deserializzo + List printList = JsonConvert.DeserializeObject>(rawData); + if (printList != null) + { + // aggiorno contatore... + coda.Value.NumWaiting = printList.Count; + if (printList.Count > 0) + { + + // se ho almeno 1 stampa --> lancio! + + // fatta stampa aggiorno server con indicazione ceh ho stampato + } + } + } + } + } } } + /// /// Effettua download dei template report in locale /// @@ -322,17 +436,6 @@ namespace LPA refreshQueueAvail(); } - private void btnStart_Click(object sender, EventArgs e) - { - spoolerRun = true; - setupButtons(); - } - - private void btnStop_Click(object sender, EventArgs e) - { - spoolerRun = false; - setupButtons(); - } private void lbPrintQueue_SelectedIndexChanged(object sender, EventArgs e) { @@ -413,5 +516,6 @@ namespace LPA btnSetQueuePrinter.Visible = doShow; } } + } } diff --git a/LPA/MainForm.resx b/LPA/MainForm.resx index 325c220..6402115 100644 --- a/LPA/MainForm.resx +++ b/LPA/MainForm.resx @@ -126,4 +126,7 @@ 242, 17 + + 334, 17 + \ No newline at end of file diff --git a/LPA/queueSetup.json b/LPA/conf/.placeholder similarity index 100% rename from LPA/queueSetup.json rename to LPA/conf/.placeholder diff --git a/LPA/conf/queueSetup.json b/LPA/conf/queueSetup.json new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/LPA/conf/queueSetup.json @@ -0,0 +1 @@ + \ No newline at end of file From 2b0f141a35457bdd7d5da113e7f72c0c8ad21aea Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 14 Feb 2020 09:42:18 +0100 Subject: [PATCH 2/8] Continuo riorganizzazione interna metodi avvio/stop code --- LPA/MainForm.Designer.cs | 15 +- LPA/MainForm.cs | 288 +++++++++++++++++++++------------------ 2 files changed, 166 insertions(+), 137 deletions(-) diff --git a/LPA/MainForm.Designer.cs b/LPA/MainForm.Designer.cs index af0efda..179a042 100644 --- a/LPA/MainForm.Designer.cs +++ b/LPA/MainForm.Designer.cs @@ -49,6 +49,7 @@ this.lblQueueCount = new System.Windows.Forms.Label(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.longTimer = new System.Windows.Forms.Timer(this.components); + this.lblUptime = new System.Windows.Forms.ToolStripStatusLabel(); this.statusStrip1.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabStatus.SuspendLayout(); @@ -82,7 +83,8 @@ this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.lblAppName, this.progBar, - this.lblStatus}); + this.lblStatus, + this.lblUptime}); this.statusStrip1.Location = new System.Drawing.Point(0, 487); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(785, 22); @@ -149,7 +151,7 @@ this.tabStatus.Controls.Add(this.dgvQueueStatus); this.tabStatus.Location = new System.Drawing.Point(4, 22); this.tabStatus.Name = "tabStatus"; - this.tabStatus.Padding = new System.Windows.Forms.Padding(3, 3, 3, 3); + this.tabStatus.Padding = new System.Windows.Forms.Padding(3); this.tabStatus.Size = new System.Drawing.Size(753, 399); this.tabStatus.TabIndex = 0; this.tabStatus.Text = "Status"; @@ -174,7 +176,7 @@ this.tabSetup.Controls.Add(this.lbPrintQueue); this.tabSetup.Location = new System.Drawing.Point(4, 22); this.tabSetup.Name = "tabSetup"; - this.tabSetup.Padding = new System.Windows.Forms.Padding(3, 3, 3, 3); + this.tabSetup.Padding = new System.Windows.Forms.Padding(3); this.tabSetup.Size = new System.Drawing.Size(753, 399); this.tabSetup.TabIndex = 1; this.tabSetup.Text = "Setup"; @@ -251,6 +253,12 @@ // this.longTimer.Interval = 60000; // + // lblUptime + // + this.lblUptime.Name = "lblUptime"; + this.lblUptime.Size = new System.Drawing.Size(16, 17); + this.lblUptime.Text = "..."; + // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); @@ -295,6 +303,7 @@ private System.Windows.Forms.Label lblQueueCount; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Timer longTimer; + private System.Windows.Forms.ToolStripStatusLabel lblUptime; } } diff --git a/LPA/MainForm.cs b/LPA/MainForm.cs index 06211dc..3ef7d24 100644 --- a/LPA/MainForm.cs +++ b/LPA/MainForm.cs @@ -40,7 +40,7 @@ namespace LPA /// /// File conf x setup code /// - protected string queueSetupFile = "queueSetup.json"; + protected string qSetFilePath = "queueSetup.json"; /// /// Configurazione CORRENTE delle code di stampa (coda --> printer disponibile) /// @@ -49,6 +49,10 @@ namespace LPA /// Binding source degli elementi di print queue gestiti.. /// private BindingSource pqBindSource = new BindingSource(); + /// + /// Uptime globale applicazione + /// + protected DateTime appStart = DateTime.Now; #endregion @@ -75,7 +79,6 @@ namespace LPA setupPrintersList(); refreshLocaltemplate(); refreshQueueAvail(); - setupQueue(); setupDGV(); } /// @@ -94,7 +97,7 @@ namespace LPA { uiTimer.Interval = 50; mainTimer.Interval = 900; - longTimer.Interval = 60000; + longTimer.Interval = 6000; uiTimer.Tick += UiTimer_Tick; mainTimer.Tick += MainTimer_Tick; longTimer.Tick += LongTimer_Tick; @@ -108,19 +111,13 @@ namespace LPA private void setupQueuePrinter() { queueSetupConf = queueSetupJson; - //printQueue currPrintQueue; - //// init oggetto code... - //foreach (var item in queueSetupConf) - //{ - // currPrintQueue = new printQueue() - // { - // QueueName = item.Key, - // Printer = item.Value, - // isRunning = spoolerRun, - // startTime = DateTime.Now - // }; - // queueStatus.Add(currPrintQueue); - //} + // cambio data/ora stared di ogni elemento... + foreach (var item in queueSetupConf) + { + item.Value.startTime = DateTime.Now; + } + // salvo valore aggiornato... + queueSetupJson = queueSetupConf; } /// /// Setup dei bottoni stato start/stop @@ -141,7 +138,17 @@ namespace LPA pqBindSource.AddingNew += qpBSList_AddingNew; pqBindSource.ListChanged += qpBSList_ListChanged; } - + /// + /// Setup elenco stampanti da disponibili su PC + /// + private void setupPrintersList() + { + lbPrinters.Items.Clear(); + foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters) + { + lbPrinters.Items.Add(printer); + } + } #endregion @@ -169,7 +176,7 @@ namespace LPA get { Dictionary answ = new Dictionary(); - string fullPath = $"{baseDir}conf\\{queueSetupFile}"; + string fullPath = $"{baseDir}conf\\{qSetFilePath}"; // cerco file x leggere conf... if (File.Exists(fullPath)) { @@ -190,7 +197,7 @@ namespace LPA } set { - string fullPath = $"{baseDir}conf\\{queueSetupFile}"; + string fullPath = $"{baseDir}conf\\{qSetFilePath}"; string rawData = JsonConvert.SerializeObject(value); File.WriteAllText(fullPath, rawData); } @@ -221,7 +228,18 @@ namespace LPA { // salvo conf ... queueSetupJson = queueSetupConf; - // salvo + // salvo 1/mese backup + string shortMonth = DateTime.Now.ToString("yyyy-MM"); + string bckDir = $"{baseDir}conf\\bck\\{shortMonth}"; + string fullPath = $"{bckDir}\\{qSetFilePath}"; + // cerco file x leggere conf... + if (!File.Exists(fullPath)) + { + Directory.CreateDirectory(bckDir); + string rawData = JsonConvert.SerializeObject(queueSetupConf); + File.WriteAllText(fullPath, rawData); + } + } /// /// Rrefresh interfaccia @@ -235,22 +253,137 @@ namespace LPA { progBar.Value = 0; } + // aggiorno uptime... + DateTime adesso = DateTime.Now; + TimeSpan uptime = adesso.Subtract(appStart); + lblUptime.Text= $"Uptime: {utils.FormatTimeSpan(uptime, true)}"; } #endregion #region interazione (buttons & co) + /// + /// Avvio processo gestione code + /// + /// + /// private void btnStart_Click(object sender, EventArgs e) { spoolerRun = true; setupButtons(); + // resetto data avvio delle code... + foreach (var item in queueSetupConf) + { + item.Value.startTime = DateTime.Now; + item.Value.isRunning = true; + } } - + /// + /// stop processo gestione code + /// + /// + /// private void btnStop_Click(object sender, EventArgs e) { spoolerRun = false; setupButtons(); + // resetto data avvio delle code... + foreach (var item in queueSetupConf) + { + item.Value.isRunning = false; + } + } + + private void btnReloadPrinters_Click(object sender, EventArgs e) + { + setupPrintersList(); + } + + private void lbtgetPrintQueue_Click(object sender, EventArgs e) + { + refreshQueueAvail(); + } + + + private void lbPrintQueue_SelectedIndexChanged(object sender, EventArgs e) + { + showPrinterList(); + } + /// + /// Sistema visibilità elenco printers + /// + private void showPrinterList() + { + bool doShow = lbPrintQueue.SelectedIndex >= 0; + lbPrinters.Visible = doShow; + btnSetQueuePrinter.Visible = false; + if (doShow) + { + setupPrintersList(); + // provo a selezionare... + string currQueue = lbPrintQueue.SelectedItem.ToString(); + if (queueSetupConf.ContainsKey(currQueue)) + { + try + { + lbPrinters.SelectedItem = queueSetupConf[currQueue].Printer; + } + catch (Exception exc) + { + Log.Instance.Error(exc, $"Impossibile associare alla coda {currQueue} la stampante richiesta: {queueSetupConf[currQueue]}"); + } + } + } + } + + private void btnSetQueuePrinter_Click(object sender, EventArgs e) + { + string currQueue = lbPrintQueue.SelectedItem.ToString(); + string currPrinter = lbPrinters.SelectedItem.ToString(); + // salvo associazione coda/printer (SE non ci fosse) + if (queueSetupConf.ContainsKey(currQueue)) + { + queueSetupConf[currQueue].Printer = currPrinter; + queueSetupConf[currQueue].startTime = DateTime.Now; + } + else + { + printQueue newQueue = new printQueue() + { + QueueName = currQueue, + Printer = currPrinter, + isRunning = spoolerRun, + startTime = DateTime.Now + }; + queueSetupConf.Add(currQueue, newQueue); + } + // salvo! + queueSetupJson = queueSetupConf; + btnSetQueuePrinter.Visible = false; + Log.Instance.Info("Salvata nuova conf stampanti"); + updateDGV(); + } + + private void lbPrinters_SelectedIndexChanged(object sender, EventArgs e) + { + bool printerSel = lbPrinters.SelectedIndex >= 0; + if (printerSel) + { + string currQueue = lbPrintQueue.SelectedItem.ToString(); + bool doShow = true; + if (queueSetupConf.ContainsKey(currQueue)) + { + string currPrinter = lbPrinters.SelectedItem.ToString(); + try + { + doShow = (queueSetupConf[currQueue].Printer != currPrinter); + } + catch + { } + } + btnSetQueuePrinter.Visible = doShow; + } } #endregion @@ -402,120 +535,7 @@ namespace LPA } } - private void setupQueue() - { - // fare leggere conf da json locale... - pqList = new List(); - pqList.Add("default"); -#if false - // ciclo su IOB configurati - foreach (var currIob in printQueue) - { - } -#endif - } - - private void setupPrintersList() - { - lbPrinters.Items.Clear(); - foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters) - { - lbPrinters.Items.Add(printer); - } - } - - private void btnReloadPrinters_Click(object sender, EventArgs e) - { - setupPrintersList(); - } - - private void lbtgetPrintQueue_Click(object sender, EventArgs e) - { - refreshQueueAvail(); - } - - - private void lbPrintQueue_SelectedIndexChanged(object sender, EventArgs e) - { - showPrinterList(); - } - /// - /// Sistema visibilità elenco printers - /// - private void showPrinterList() - { - bool doShow = lbPrintQueue.SelectedIndex >= 0; - lbPrinters.Visible = doShow; - btnSetQueuePrinter.Visible = false; - if (doShow) - { - setupPrintersList(); - // provo a selezionare... - string currQueue = lbPrintQueue.SelectedItem.ToString(); - if (queueSetupConf.ContainsKey(currQueue)) - { - try - { - lbPrinters.SelectedItem = queueSetupConf[currQueue].Printer; - } - catch (Exception exc) - { - Log.Instance.Error(exc, $"Impossibile associare alla coda {currQueue} la stampante richiesta: {queueSetupConf[currQueue]}"); - } - } - } - } - - private void btnSetQueuePrinter_Click(object sender, EventArgs e) - { - string currQueue = lbPrintQueue.SelectedItem.ToString(); - string currPrinter = lbPrinters.SelectedItem.ToString(); - // salvo associazione coda/printer (SE non ci fosse) - if (queueSetupConf.ContainsKey(currQueue)) - { - queueSetupConf[currQueue].Printer = currPrinter; - queueSetupConf[currQueue].startTime = DateTime.Now; - } - else - { - printQueue newQueue = new printQueue() - { - QueueName = currQueue, - Printer = currPrinter, - isRunning = spoolerRun, - startTime = DateTime.Now - }; - queueSetupConf.Add(currQueue, newQueue); - } - // salvo! - queueSetupJson = queueSetupConf; - btnSetQueuePrinter.Visible = false; - Log.Instance.Info("Salvata nuova conf stampanti"); - updateDGV(); - } - - private void lbPrinters_SelectedIndexChanged(object sender, EventArgs e) - { - bool printerSel = lbPrinters.SelectedIndex >= 0; - if (printerSel) - { - string currQueue = lbPrintQueue.SelectedItem.ToString(); - bool doShow = true; - if (queueSetupConf.ContainsKey(currQueue)) - { - string currPrinter = lbPrinters.SelectedItem.ToString(); - try - { - doShow = (queueSetupConf[currQueue].Printer != currPrinter); - } - catch - { } - } - btnSetQueuePrinter.Visible = doShow; - } - } - } } From 06aba216685ff014fef68eb653885059d655ee25 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 14 Feb 2020 09:44:34 +0100 Subject: [PATCH 3/8] Ancora code reshape --- LPA/MainForm.cs | 136 ++++++++++++++++++++++++------------------------ 1 file changed, 69 insertions(+), 67 deletions(-) diff --git a/LPA/MainForm.cs b/LPA/MainForm.cs index 3ef7d24..952c143 100644 --- a/LPA/MainForm.cs +++ b/LPA/MainForm.cs @@ -202,6 +202,37 @@ namespace LPA File.WriteAllText(fullPath, rawData); } } + /// + /// Evento cambio + /// + /// + /// + private void qpBSList_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + { + updateDGV(); + } + /// + /// Evento aggiunta + /// + /// + /// + private void qpBSList_AddingNew(object sender, System.ComponentModel.AddingNewEventArgs e) + { + updateDGV(); + } + /// + /// aggiorna elemento DGV + /// + private void updateDGV() + { + List elencoCode = new List(); + foreach (var item in queueSetupConf) + { + elencoCode.Add(item.Value); + } + dgvQueueStatus.DataSource = elencoCode; + dgvQueueStatus.Invalidate(); + } #endregion @@ -388,36 +419,46 @@ namespace LPA #endregion + #region metodi di chiamata a server + /// - /// Evento cambio + /// Effettua download dei template report in locale /// - /// - /// - private void qpBSList_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + private void refreshLocaltemplate() { - updateDGV(); - } - /// - /// Evento aggiunta - /// - /// - /// - private void qpBSList_AddingNew(object sender, System.ComponentModel.AddingNewEventArgs e) - { - updateDGV(); - } - private void updateDGV() - { - List elencoCode = new List(); - foreach (var item in queueSetupConf) + // scarico TUTTI i report definiti + filePack objFiles = new filePack(); + string rawData = ""; + string url2call = $"{serverBaseAddr}/api/Report"; + // recupero dati + var taskRes = Task.Run(() => utils.getPageAsync(url2call)); + taskRes.Wait(); + + rawData = taskRes.Result; + if (!string.IsNullOrEmpty(rawData)) { - elencoCode.Add(item.Value); + // deserializzo + objFiles = JsonConvert.DeserializeObject(rawData); + if (objFiles != null) + { + // salvo! + foreach (var item in objFiles.fileList) + { + string fullPath = $"{localReportPath}{item.fileName}"; + File.WriteAllText(fullPath, item.content); + } + Log.Instance.Info("Download template files aggiornati"); + } + else + { + Log.Instance.Error($"Error: invalid file data received, deserialized to null ({rawData})"); + } + } + else + { + Log.Instance.Error("Error: no file data downloaded"); } - dgvQueueStatus.DataSource = elencoCode; - dgvQueueStatus.Invalidate(); } - - /// /// Aggiornamento code stampa disponibili /// @@ -453,7 +494,9 @@ namespace LPA } showPrinterList(); } - + /// + /// Aggiorna stato code + /// private void refreshQueueStsatus() { // verifico ed aggiorno quantità coda @@ -494,48 +537,7 @@ namespace LPA } } - - - /// - /// Effettua download dei template report in locale - /// - private void refreshLocaltemplate() - { - // scarico TUTTI i report definiti - filePack objFiles = new filePack(); - string rawData = ""; - string url2call = $"{serverBaseAddr}/api/Report"; - // recupero dati - var taskRes = Task.Run(() => utils.getPageAsync(url2call)); - taskRes.Wait(); - - rawData = taskRes.Result; - if (!string.IsNullOrEmpty(rawData)) - { - // deserializzo - objFiles = JsonConvert.DeserializeObject(rawData); - if (objFiles != null) - { - // salvo! - foreach (var item in objFiles.fileList) - { - string fullPath = $"{localReportPath}{item.fileName}"; - File.WriteAllText(fullPath, item.content); - } - Log.Instance.Info("Download template files aggiornati"); - } - else - { - Log.Instance.Error($"Error: invalid file data received, deserialized to null ({rawData})"); - } - } - else - { - Log.Instance.Error("Error: no file data downloaded"); - } - } - - + #endregion } } From 5869e400ed1b4c47c4ada0cd724864e7128c5848 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 14 Feb 2020 10:29:53 +0100 Subject: [PATCH 4/8] Abbozzata tutta la classe di print (da portare fuori main!!!) --- LPA/LPA.csproj | 3 + LPA/MainForm.cs | 196 ++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 193 insertions(+), 6 deletions(-) diff --git a/LPA/LPA.csproj b/LPA/LPA.csproj index 3b3d516..e98f45f 100644 --- a/LPA/LPA.csproj +++ b/LPA/LPA.csproj @@ -232,6 +232,9 @@ + + + diff --git a/LPA/MainForm.cs b/LPA/MainForm.cs index 952c143..557469c 100644 --- a/LPA/MainForm.cs +++ b/LPA/MainForm.cs @@ -3,11 +3,14 @@ using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; +using System.Drawing.Imaging; +using System.Drawing.Printing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Reporting.WinForms; using Newtonsoft.Json; using SteamWare; @@ -53,6 +56,10 @@ namespace LPA /// Uptime globale applicazione /// protected DateTime appStart = DateTime.Now; + /// + /// Code di stampa disponibili (da server) + /// + protected List listQueue = new List(); #endregion @@ -467,7 +474,6 @@ namespace LPA // svuoto lbPrintQueue.Items.Clear(); // scarico TUTTI i report definiti - List listQueue = new List(); string url2call = $"{serverBaseAddr}/api/PrintQueueConf"; string rawData = callUrl(url2call); if (!string.IsNullOrEmpty(rawData)) @@ -518,15 +524,20 @@ namespace LPA if (!string.IsNullOrEmpty(rawData)) { // deserializzo - List printList = JsonConvert.DeserializeObject>(rawData); - if (printList != null) + List report2print = JsonConvert.DeserializeObject>(rawData); + if (report2print != null) { // aggiorno contatore... - coda.Value.NumWaiting = printList.Count; - if (printList.Count > 0) + coda.Value.NumWaiting = report2print.Count; + foreach (var item in report2print) { - + bool fatto = false; // se ho almeno 1 stampa --> lancio! + queueConf confCoda = listQueue.Find(conf => conf.name == coda.Key); + if(confCoda!=null) + { + fatto= printReport(confCoda.rdsName, coda.Value.Printer, item.rdsTable, confCoda.deviceInfoParam, true); + } // fatta stampa aggiorno server con indicazione ceh ho stampato } @@ -539,5 +550,178 @@ namespace LPA #endregion + #region metodi stampa effettiva report + + /// + /// Indice pagina corrente x stampa ogni report + /// + private int m_currentPageIndex; + /// + /// stream del report... + /// + private IList m_streams; + /// + /// Crea un report locale da file rdlc, carica i dati, esporta report come EMF file e quindi lo invia alla stampante + eventuale backup pdf + /// + /// Nome report + /// nome completo stampante (rispetto al server) + /// tabella dati da caricare nel report + /// parametri "device input" + /// effettua ANCHE copia pdf + public bool printReport(string rdsName, string printerName, DataTable tabDati, devInfoParam deviceInfoParam, bool doPdfCopy) + { + bool answ = false; + LocalReport report = new LocalReport(); + report.EnableExternalImages = true; + string deviceInfo = ""; + report.ReportPath = $"{localReportPath}\\{rdsName}"; + report.DataSources.Add(new ReportDataSource(rdsName, tabDati)); + deviceInfo = deviceInfoParam.xmlParam; + // stampa da EMF + doEmfPrint(printerName, report, deviceInfo); + // controllo se devo fare copia PDF... stampiamo ANCHE su pdf su una folder locale + if (doPdfCopy) + { + deviceInfoParam.OutputFormat = "PDF"; + deviceInfo = deviceInfoParam.xmlParam; + // salva ANCHE pdf + doLocalPdfPrint(report, deviceInfo); + } + return answ; + } + /// + /// esegue print vero e proprio + /// + /// + /// + /// + private void doEmfPrint(string printerName, LocalReport report, string deviceInfo) + { + // export in EMF + Export(report, deviceInfo); + m_currentPageIndex = 0; + // stampo + Print(printerName); + // do dispose? + Dispose(); + } + /// + /// effettua stampa in PDF dei vari report in una cartella Anno/Mese/Giorno + /// + /// + /// + private void doLocalPdfPrint(LocalReport report, string deviceInfo) + { + // export in PDF + ExportPDF(report, deviceInfo); + m_currentPageIndex = 0; + // do dispose? + Dispose(); + } + /// + /// Export del report come EMF (Enhanced Metafile) file. + /// + /// + private void Export(LocalReport report, string deviceInfo) + { + Warning[] warnings; + m_streams = new List(); + report.Render("Image", deviceInfo, CreateStream, out warnings); + foreach (Stream stream in m_streams) stream.Position = 0; + } + /// + /// Export del report come PDF file. + /// + /// + private void ExportPDF(LocalReport report, string deviceInfo) + { + Warning[] warnings; + m_streams = new List(); + report.Render("PDF", deviceInfo, CreateStreamPdf, out warnings); + foreach (Stream stream in m_streams) stream.Position = 0; + } + /// + /// dispone l'applicazione e rilascia le risorse + /// + public void Dispose() + { + if (m_streams != null) + { + foreach (Stream stream in m_streams) + stream.Close(); + m_streams = null; + } + } + /// + /// ciclo da fornire al renderizzatore dei report, per salvare 1 immagine da ogni pagina del report + /// + /// + /// + /// + /// + /// + /// + private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) + { + // creo files con nomi univoci... + string filePathName = string.Format(@"~\temp\{0}_{1:HHmmss}_{1:ffff}.{2}", name, DateTime.Now, fileNameExtension); + Stream stream = new FileStream(SteamwareStrings.getFilePath(filePathName), FileMode.Create); + m_streams.Add(stream); + return stream; + } + /// + /// ciclo da fornire al renderizzatore dei report, per salvare 1 pdf da ogni pagina del report + /// + /// + /// + /// + /// + /// + /// + private Stream CreateStreamPdf(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) + { + // creo Directory se non c'è + fileMover fm = new fileMover(string.Format(@"{0}\{1:yyyy}\{1:MM}\{1:dd}\", memLayer.ML.confReadString("PdfFolder"), DateTime.Now), ""); + fm.checkDir(); + string pdfPathName = string.Format(@"{0}\{1:yyyy}\{1:MM}\{1:dd}\{2}_{1:HHmmss}_{1:ffff}.{3}", memLayer.ML.confReadString("PdfFolder"), DateTime.Now, name, fileNameExtension); + Stream stream = new FileStream(SteamwareStrings.getFilePath(pdfPathName), FileMode.Create); + m_streams.Add(stream); + return stream; + } + /// + /// Handler per PrintPageEvents + /// + /// + /// + private void PrintPage(object sender, PrintPageEventArgs ev) + { + Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); + ev.Graphics.DrawImage(pageImage, ev.PageBounds); + m_currentPageIndex++; + ev.HasMorePages = (m_currentPageIndex < m_streams.Count); + } + /// + /// funzione di stampa... + /// + private void Print(string printerName) + { + //const string printerName = "Microsoft Office Document Image Writer"; + //const string printerName = "Brother HL-2170W series"; + if (m_streams == null || m_streams.Count == 0) + return; + PrintDocument printDoc = new PrintDocument(); + printDoc.PrinterSettings.PrinterName = printerName; + if (!printDoc.PrinterSettings.IsValid) + { + logger.lg.scriviLog(String.Format("Impostazioni non valide per la stampante \"{0}\".", printerName), tipoLog.ERROR); + return; + } + printDoc.PrintPage += new PrintPageEventHandler(PrintPage); + printDoc.Print(); + } + + #endregion + + } } From cbb8538be26f268937d11777ef3c469cc38878b4 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 14 Feb 2020 10:56:43 +0100 Subject: [PATCH 5/8] Prima bozza stampa.... --- LPA/App.config | 1 + LPA/LPA.csproj | 10 +- LPA/MainForm.cs | 235 ++++----------- LPA/{temp => pdf}/.placeholder | 0 LPA/pdf/temp/.placeholder | 1 + LPA/reportPrinter.cs | 531 ++++++++------------------------- 6 files changed, 185 insertions(+), 593 deletions(-) rename LPA/{temp => pdf}/.placeholder (100%) create mode 100644 LPA/pdf/temp/.placeholder diff --git a/LPA/App.config b/LPA/App.config index 48337e1..e6d5006 100644 --- a/LPA/App.config +++ b/LPA/App.config @@ -7,6 +7,7 @@ + diff --git a/LPA/LPA.csproj b/LPA/LPA.csproj index e98f45f..f50cfb2 100644 --- a/LPA/LPA.csproj +++ b/LPA/LPA.csproj @@ -168,6 +168,7 @@ + MainForm.cs @@ -196,6 +197,9 @@ Always + + Always + SettingsSingleFileGenerator Settings.Designer.cs @@ -208,7 +212,7 @@ Always - + Always @@ -232,9 +236,7 @@ - - - + diff --git a/LPA/MainForm.cs b/LPA/MainForm.cs index 557469c..5192205 100644 --- a/LPA/MainForm.cs +++ b/LPA/MainForm.cs @@ -1,18 +1,13 @@ -using System; +using Newtonsoft.Json; +using SteamWare; +using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; -using System.Drawing.Imaging; -using System.Drawing.Printing; using System.IO; -using System.Linq; +using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -using Microsoft.Reporting.WinForms; -using Newtonsoft.Json; -using SteamWare; namespace LPA { @@ -60,6 +55,10 @@ namespace LPA /// Code di stampa disponibili (da server) /// protected List listQueue = new List(); + /// + /// Classe gestioen stampa report + /// + protected reportPrinter rPrint; #endregion @@ -87,7 +86,16 @@ namespace LPA refreshLocaltemplate(); refreshQueueAvail(); setupDGV(); + setupReportPrinter(); } + /// + /// Setup istanza classe stampa report + /// + private void setupReportPrinter() + { + rPrint = new reportPrinter(); + } + /// /// Setup parametri base di configurazione /// @@ -176,6 +184,24 @@ namespace LPA return result; } /// + /// Chiamata PUT async URL + /// + /// + /// + /// + protected string postUrl(string url2call, string payload) + { + string result = ""; + // fix contenuto + Uri callUri = new Uri(url2call); + HttpContent callCont = new StringContent(payload, Encoding.UTF8, "application/json"); + // chiamo! + var taskRes = Task.Run(() => utils.putAsync(callUri, callCont, "")); + taskRes.Wait(); + result = taskRes.Result; + return result; + } + /// /// Configurazione coda stampa da json file /// protected Dictionary queueSetupJson @@ -294,7 +320,7 @@ namespace LPA // aggiorno uptime... DateTime adesso = DateTime.Now; TimeSpan uptime = adesso.Subtract(appStart); - lblUptime.Text= $"Uptime: {utils.FormatTimeSpan(uptime, true)}"; + lblUptime.Text = $"Uptime: {utils.FormatTimeSpan(uptime, true)}"; } #endregion @@ -534,12 +560,24 @@ namespace LPA bool fatto = false; // se ho almeno 1 stampa --> lancio! queueConf confCoda = listQueue.Find(conf => conf.name == coda.Key); - if(confCoda!=null) + if (confCoda != null) { - fatto= printReport(confCoda.rdsName, coda.Value.Printer, item.rdsTable, confCoda.deviceInfoParam, true); + fatto = rPrint.printReport(confCoda.rdsName, localReportPath, coda.Value.Printer, item.rdsTable, confCoda.deviceInfoParam, true); } - // fatta stampa aggiorno server con indicazione ceh ho stampato + if (fatto) + { + // compongo payload... + printTask printResult = new printTask() + { + ticketNum = item.ticketNum, + newStatus = 1, + message = "" + }; + string payload = JsonConvert.SerializeObject(printResult); + // chiamo in put print result! + + } } } } @@ -550,177 +588,6 @@ namespace LPA #endregion - #region metodi stampa effettiva report - - /// - /// Indice pagina corrente x stampa ogni report - /// - private int m_currentPageIndex; - /// - /// stream del report... - /// - private IList m_streams; - /// - /// Crea un report locale da file rdlc, carica i dati, esporta report come EMF file e quindi lo invia alla stampante + eventuale backup pdf - /// - /// Nome report - /// nome completo stampante (rispetto al server) - /// tabella dati da caricare nel report - /// parametri "device input" - /// effettua ANCHE copia pdf - public bool printReport(string rdsName, string printerName, DataTable tabDati, devInfoParam deviceInfoParam, bool doPdfCopy) - { - bool answ = false; - LocalReport report = new LocalReport(); - report.EnableExternalImages = true; - string deviceInfo = ""; - report.ReportPath = $"{localReportPath}\\{rdsName}"; - report.DataSources.Add(new ReportDataSource(rdsName, tabDati)); - deviceInfo = deviceInfoParam.xmlParam; - // stampa da EMF - doEmfPrint(printerName, report, deviceInfo); - // controllo se devo fare copia PDF... stampiamo ANCHE su pdf su una folder locale - if (doPdfCopy) - { - deviceInfoParam.OutputFormat = "PDF"; - deviceInfo = deviceInfoParam.xmlParam; - // salva ANCHE pdf - doLocalPdfPrint(report, deviceInfo); - } - return answ; - } - /// - /// esegue print vero e proprio - /// - /// - /// - /// - private void doEmfPrint(string printerName, LocalReport report, string deviceInfo) - { - // export in EMF - Export(report, deviceInfo); - m_currentPageIndex = 0; - // stampo - Print(printerName); - // do dispose? - Dispose(); - } - /// - /// effettua stampa in PDF dei vari report in una cartella Anno/Mese/Giorno - /// - /// - /// - private void doLocalPdfPrint(LocalReport report, string deviceInfo) - { - // export in PDF - ExportPDF(report, deviceInfo); - m_currentPageIndex = 0; - // do dispose? - Dispose(); - } - /// - /// Export del report come EMF (Enhanced Metafile) file. - /// - /// - private void Export(LocalReport report, string deviceInfo) - { - Warning[] warnings; - m_streams = new List(); - report.Render("Image", deviceInfo, CreateStream, out warnings); - foreach (Stream stream in m_streams) stream.Position = 0; - } - /// - /// Export del report come PDF file. - /// - /// - private void ExportPDF(LocalReport report, string deviceInfo) - { - Warning[] warnings; - m_streams = new List(); - report.Render("PDF", deviceInfo, CreateStreamPdf, out warnings); - foreach (Stream stream in m_streams) stream.Position = 0; - } - /// - /// dispone l'applicazione e rilascia le risorse - /// - public void Dispose() - { - if (m_streams != null) - { - foreach (Stream stream in m_streams) - stream.Close(); - m_streams = null; - } - } - /// - /// ciclo da fornire al renderizzatore dei report, per salvare 1 immagine da ogni pagina del report - /// - /// - /// - /// - /// - /// - /// - private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) - { - // creo files con nomi univoci... - string filePathName = string.Format(@"~\temp\{0}_{1:HHmmss}_{1:ffff}.{2}", name, DateTime.Now, fileNameExtension); - Stream stream = new FileStream(SteamwareStrings.getFilePath(filePathName), FileMode.Create); - m_streams.Add(stream); - return stream; - } - /// - /// ciclo da fornire al renderizzatore dei report, per salvare 1 pdf da ogni pagina del report - /// - /// - /// - /// - /// - /// - /// - private Stream CreateStreamPdf(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) - { - // creo Directory se non c'è - fileMover fm = new fileMover(string.Format(@"{0}\{1:yyyy}\{1:MM}\{1:dd}\", memLayer.ML.confReadString("PdfFolder"), DateTime.Now), ""); - fm.checkDir(); - string pdfPathName = string.Format(@"{0}\{1:yyyy}\{1:MM}\{1:dd}\{2}_{1:HHmmss}_{1:ffff}.{3}", memLayer.ML.confReadString("PdfFolder"), DateTime.Now, name, fileNameExtension); - Stream stream = new FileStream(SteamwareStrings.getFilePath(pdfPathName), FileMode.Create); - m_streams.Add(stream); - return stream; - } - /// - /// Handler per PrintPageEvents - /// - /// - /// - private void PrintPage(object sender, PrintPageEventArgs ev) - { - Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); - ev.Graphics.DrawImage(pageImage, ev.PageBounds); - m_currentPageIndex++; - ev.HasMorePages = (m_currentPageIndex < m_streams.Count); - } - /// - /// funzione di stampa... - /// - private void Print(string printerName) - { - //const string printerName = "Microsoft Office Document Image Writer"; - //const string printerName = "Brother HL-2170W series"; - if (m_streams == null || m_streams.Count == 0) - return; - PrintDocument printDoc = new PrintDocument(); - printDoc.PrinterSettings.PrinterName = printerName; - if (!printDoc.PrinterSettings.IsValid) - { - logger.lg.scriviLog(String.Format("Impostazioni non valide per la stampante \"{0}\".", printerName), tipoLog.ERROR); - return; - } - printDoc.PrintPage += new PrintPageEventHandler(PrintPage); - printDoc.Print(); - } - - #endregion } diff --git a/LPA/temp/.placeholder b/LPA/pdf/.placeholder similarity index 100% rename from LPA/temp/.placeholder rename to LPA/pdf/.placeholder diff --git a/LPA/pdf/temp/.placeholder b/LPA/pdf/temp/.placeholder new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/LPA/pdf/temp/.placeholder @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/LPA/reportPrinter.cs b/LPA/reportPrinter.cs index d7d7565..769f080 100644 --- a/LPA/reportPrinter.cs +++ b/LPA/reportPrinter.cs @@ -1,99 +1,99 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.Reporting.WinForms; +using Microsoft.Reporting.WinForms; using SteamWare; +using System; +using System.Collections.Generic; using System.Data; using System.Drawing.Imaging; using System.Drawing.Printing; using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; namespace LPA { - /// - /// Classe che si occupa di stampare report da reportViewer via printer locale/remota - /// public class reportPrinter { - #region area codice da non modificare + /// + /// Path x salvataggio locale pdf + /// + protected string localPdfPath = "pdf"; + /// + /// Classe reportprinter + /// + public reportPrinter() + { + localPdfPath = memLayer.ML.confReadString("localPdfPath"); + } + #region metodi stampa effettiva report + + /// + /// Indice pagina corrente x stampa ogni report + /// private int m_currentPageIndex; - protected int logLevel = 0; - protected bool doPdfCopy = false; /// /// stream del report... /// private IList m_streams; /// - /// ciclo da fornire al renderizzatore dei report, per salvare 1 immagine da ogni pagina del report + /// Crea un report locale da file rdlc, carica i dati, esporta report come EMF file e quindi lo invia alla stampante + eventuale backup pdf /// - /// - /// - /// - /// - /// - /// - private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) + /// Nome report + /// Cartella locale dei report + /// nome completo stampante (rispetto al server) + /// tabella dati da caricare nel report + /// parametri "device input" + /// effettua ANCHE copia pdf + public bool printReport(string rdsName, string localReportPath, string printerName, DataTable tabDati, devInfoParam deviceInfoParam, bool doPdfCopy) { - // creo files con nomi univoci... - string filePathName = string.Format(@"~\temp\{0}_{1:HHmmss}_{1:ffff}.{2}", name, DateTime.Now, fileNameExtension); - Stream stream = new FileStream(SteamWare.SteamwareStrings.getFilePath(filePathName), FileMode.Create); - //Stream stream = new FileStream(SteamWare.SteamwareStrings.getFilePath(@"~\temp\" + name + "." + fileNameExtension), FileMode.Create); - m_streams.Add(stream); - return stream; - } - /// - /// ciclo da fornire al renderizzatore dei report, per salvare 1 pdf da ogni pagina del report - /// - /// - /// - /// - /// - /// - /// - private Stream CreateStreamPdf(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) - { - // creo Directory se non c'è - SteamWare.fileMover fm = new fileMover(string.Format(@"{0}\{1:yyyy}\{1:MM}\{1:dd}\", memLayer.ML.confReadString("PdfFolder"), DateTime.Now), ""); - fm.checkDir(); - string pdfPathName = string.Format(@"{0}\{1:yyyy}\{1:MM}\{1:dd}\{2}_{1:HHmmss}_{1:ffff}.{3}", memLayer.ML.confReadString("PdfFolder"), DateTime.Now, name, fileNameExtension); - //Stream stream = new FileStream(SteamWare.SteamwareStrings.getFilePath(@"~\temp\" + name + "." + fileNameExtension), FileMode.Create); - Stream stream = new FileStream(SteamWare.SteamwareStrings.getFilePath(pdfPathName), FileMode.Create); - m_streams.Add(stream); - return stream; - } - /// - /// Handler per PrintPageEvents - /// - /// - /// - private void PrintPage(object sender, PrintPageEventArgs ev) - { - Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); - ev.Graphics.DrawImage(pageImage, ev.PageBounds); - m_currentPageIndex++; - ev.HasMorePages = (m_currentPageIndex < m_streams.Count); - } - /// - /// funzione di stampa... - /// - private void Print(string printerName) - { - //const string printerName = "Microsoft Office Document Image Writer"; - //const string printerName = "Brother HL-2170W series"; - if (m_streams == null || m_streams.Count == 0) - return; - PrintDocument printDoc = new PrintDocument(); - printDoc.PrinterSettings.PrinterName = printerName; - if (!printDoc.PrinterSettings.IsValid) + bool answ = false; + LocalReport report = new LocalReport(); + report.EnableExternalImages = true; + string deviceInfo = ""; + report.ReportPath = $"{localReportPath}\\{rdsName}"; + report.DataSources.Add(new ReportDataSource(rdsName, tabDati)); + deviceInfo = deviceInfoParam.xmlParam; + // stampa da EMF + doEmfPrint(printerName, report, deviceInfo); + // controllo se devo fare copia PDF... stampiamo ANCHE su pdf su una folder locale + if (doPdfCopy) { - logger.lg.scriviLog(String.Format("Impostazioni non valide per la stampante \"{0}\".", printerName), tipoLog.ERROR); - return; + deviceInfoParam.OutputFormat = "PDF"; + deviceInfo = deviceInfoParam.xmlParam; + // salva ANCHE pdf + doLocalPdfPrint(report, deviceInfo); } - printDoc.PrintPage += new PrintPageEventHandler(PrintPage); - printDoc.Print(); + return answ; + } + /// + /// esegue print vero e proprio + /// + /// + /// + /// + private void doEmfPrint(string printerName, LocalReport report, string deviceInfo) + { + // export in EMF + Export(report, deviceInfo); + m_currentPageIndex = 0; + // stampo + Print(printerName); + // do dispose? + Dispose(); + } + /// + /// effettua stampa in PDF dei vari report in una cartella Anno/Mese/Giorno + /// + /// + /// + private void doLocalPdfPrint(LocalReport report, string deviceInfo) + { + // export in PDF + ExportPDF(report, deviceInfo); + m_currentPageIndex = 0; + // do dispose? + Dispose(); } /// /// Export del report come EMF (Enhanced Metafile) file. @@ -129,355 +129,76 @@ namespace LPA m_streams = null; } } - - #endregion - - #region area codice da modificare - /// - /// carica i dati richiesti dal report dalla StoredProcedure (filtrando quindi...) + /// ciclo da fornire al renderizzatore dei report, per salvare 1 immagine da ogni pagina del report /// - /// - /// cod UDC - /// tabella dati - private DataTable caricaDati(reportRichiesto tipoReport, string keyParam) - { - int intIdx = 0; - DataTable tab = new DataTable(); - switch (tipoReport) - { - case reportRichiesto.cartLabel: - // int.TryParse(keyParam, out intIdx); - // tab = (DataTable)DataLayer.man.taRepStack.GetData(intIdx); - break; - case reportRichiesto.paintLabelPre: - // int.TryParse(keyParam, out intIdx); - // tab = (DataTable)DataLayer.man.taRepStack.GetData(intIdx); - break; - case reportRichiesto.paintLabelPost: - // int.TryParse(keyParam, out intIdx); - // tab = (DataTable)DataLayer.man.taRepStack.GetData(intIdx); - break; - case reportRichiesto.partLabel: - int.TryParse(keyParam, out intIdx); - tab = (DataTable)DataLayer.man.taIL.getByKey(intIdx); - break; - case reportRichiesto.stackLabel: - int.TryParse(keyParam, out intIdx); - tab = (DataTable)DataLayer.man.taRepStack.GetData(intIdx); - break; - default: - break; - } - return tab; - } - /// - /// Crea un report locale da file rdlc, carica i dati, esporta report come EMF file e quindi lo invia alla stampante - /// - /// report ammessi: ElencoMacchine / RichiestaIntervento - /// nome completo stampante (rispetto al server) - /// cod UDC - /// parametri "device input" - public void printReport(reportRichiesto tipoReport, string printerName, string keyParam, devInfoParam deviceInfoParam) - { - LocalReport report = new LocalReport(); - report.EnableExternalImages = true; - string deviceInfo = ""; - string repoBasePath = utils.getPath(memLayer.ML.cdv("ReportBasePath")); - repoBasePath = repoBasePath.Replace("\\site", ""); - switch (tipoReport) - { - case reportRichiesto.cartLabel: - report.ReportPath = string.Format(@"{0}\CartLabel.rdlc", repoBasePath); - report.DataSources.Add(new ReportDataSource(memLayer.ML.cdv("ReportDS_DocCart"), caricaDati(tipoReport, keyParam))); - break; - case reportRichiesto.paintLabelPre: - report.ReportPath = string.Format(@"{0}\PaintPreLabel.rdlc", repoBasePath); - report.DataSources.Add(new ReportDataSource(memLayer.ML.cdv("ReportDS_DocPaintPre"), caricaDati(tipoReport, keyParam))); - break; - case reportRichiesto.paintLabelPost: - report.ReportPath = string.Format(@"{0}\PaintPreLabel.rdlc", repoBasePath); - report.DataSources.Add(new ReportDataSource(memLayer.ML.cdv("ReportDS_DocPaintPre"), caricaDati(tipoReport, keyParam))); - break; - case reportRichiesto.partLabel: - report.ReportPath = string.Format(@"{0}\PartLabel.rdlc", repoBasePath); - report.DataSources.Add(new ReportDataSource(memLayer.ML.cdv("ReportDS_DocPart"), caricaDati(tipoReport, keyParam))); - break; - case reportRichiesto.stackLabel: - report.ReportPath = string.Format(@"{0}\StackLabel.rdlc", repoBasePath); - report.DataSources.Add(new ReportDataSource(memLayer.ML.cdv("ReportDS_DocStack"), caricaDati(tipoReport, keyParam))); - break; - } - deviceInfo = deviceInfoParam.xmlParam; - doEmfPrint(printerName, report, deviceInfo); - // controllo se devo fare copia PDF... stampiamo ANCHE su pdf su una folder locale - if (doPdfCopy) - { - deviceInfoParam.OutputFormat = "PDF"; - deviceInfo = deviceInfoParam.xmlParam; - doLocalPdfPrint(report, deviceInfo); - } - } - /// - /// esegue print vero e proprio - /// - /// - /// - /// - private void doEmfPrint(string printerName, LocalReport report, string deviceInfo) - { - // export in EMF - Export(report, deviceInfo); - m_currentPageIndex = 0; - // stampo - Print(printerName); - // do dispose? - Dispose(); - } - /// - /// effettua stampa in PDF dei vari report in una cartella Anno/Mese/Giorno - /// - /// - /// - private void doLocalPdfPrint(LocalReport report, string deviceInfo) - { - // export in PDF - ExportPDF(report, deviceInfo); - m_currentPageIndex = 0; - // do dispose? - Dispose(); - } - /// - /// effettua la stampa del cartellino indicato - /// - /// - /// - /// indirizzo di rete completo stampante del tipo \\nomePc\nomeStampante, oppure "" x default + /// + /// + /// + /// + /// /// - public bool stampaCartellino(tipoDocumento documento, string keyParam, string printerName) + private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) { - bool answ = false; - int idxPrintJob = 0; - DataLayer dtProx = new DataLayer(); - // gestione coda stampa... - - // incomincio con gestione della coda di stampa... inserisco in tab la richiesta di stampa... - if (memLayer.ML.CRB("disable_singleton")) - { - dtProx.taPJQ.insertQuery(documento.ToString(), keyParam, printerName); - } - else - { - DataLayer.man.taPJQ.insertQuery(documento.ToString(), keyParam, printerName); - } - // faccio un ciclo while... finchè non sono "in testa" alla coda delle esecuzioni aspetto... - string nextJob = "ND"; - try - { - if (memLayer.ML.CRB("disable_singleton")) - { - nextJob = dtProx.taPJQ.getNext()[0].KeyParam; - } - else - { - nextJob = DataLayer.man.taPJQ.getNext()[0].KeyParam; - } - } - catch - { - nextJob = "ND"; - } - // verifico eventuali processi zombie: quelli in stato 0 con LastTry superiore a data attuale meno zombieMsTime - if (memLayer.ML.CRB("disable_singleton")) - { - dtProx.taPJQ.chiudiZoombie(DateTime.Now.AddMilliseconds(-memLayer.ML.CRI("zombieMsTime"))); - } - else - { - DataLayer.man.taPJQ.chiudiZoombie(DateTime.Now.AddMilliseconds(-memLayer.ML.CRI("zombieMsTime"))); - } - // ora inizio a fare le mie stampe... - Random rand = new Random(); - int msWait = 200; - while (nextJob != keyParam) - { - // indico che ho fatto un tentativo di stampa aggiornando dtLastTry - if (memLayer.ML.CRB("disable_singleton")) - { - dtProx.taPJQ.updateLastTry(keyParam); - } - else - { - DataLayer.man.taPJQ.updateLastTry(keyParam); - } - // aspetto... - msWait = rand.Next(memLayer.ML.confReadInt("minWait"), memLayer.ML.confReadInt("maxWait")); - System.Threading.Thread.Sleep(msWait); - // leggo prox record da coda - if (memLayer.ML.CRB("disable_singleton")) - { - nextJob = dtProx.taPJQ.getNext()[0].KeyParam; - } - else - { - nextJob = DataLayer.man.taPJQ.getNext()[0].KeyParam; - } - } - // salvo idx job... - try - { - if (memLayer.ML.CRB("disable_singleton")) - { - idxPrintJob = dtProx.taPJQ.getNext()[0].IdxPrintJob; - } - else - { - idxPrintJob = DataLayer.man.taPJQ.getNext()[0].IdxPrintJob; - } - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in recupero IdxPrint Job:{exc}", tipoLog.EXCEPTION); - } - - // dimensioni pagina - string outForm = ""; - string pagWidth = ""; - string pagHeigth = ""; - string margin = ""; - reportRichiesto report = reportRichiesto.stackLabel; - string tipo = ""; - - switch (documento) - { - case tipoDocumento.docBinPre: - tipo = "DocPaint"; - report = reportRichiesto.paintLabelPre; - break; - case tipoDocumento.docBinPost: - tipo = "DocPaintPost"; - report = reportRichiesto.paintLabelPost; - break; - case tipoDocumento.docCart: - tipo = "DocCart"; - report = reportRichiesto.cartLabel; - break; - case tipoDocumento.docPart: - tipo = "DocPart"; - report = reportRichiesto.partLabel; - break; - case tipoDocumento.docStack: - tipo = "DocStack"; - report = reportRichiesto.stackLabel; - break; - default: - break; - } - // carico di dati con lettura da web.config parametrica - if (string.IsNullOrEmpty(printerName)) - { - printerName = memLayer.ML.cdv(string.Format("printer{0}", tipo)); - } - outForm = "EMF"; - pagWidth = memLayer.ML.cdv(string.Format("PageWidth{0}", tipo)); - pagHeigth = memLayer.ML.cdv(string.Format("PageHeight{0}", tipo)); - margin = memLayer.ML.cdv(string.Format("Margin{0}", tipo)); - // compongo parametri stampa - devInfoParam deviceInfo = new devInfoParam(outForm, pagHeigth, pagWidth, margin, margin, margin, margin); - answ = printAndLog(keyParam, printerName, answ, report, deviceInfo); - if (answ) - { - // registro stampato in tabella queue... - if (memLayer.ML.CRB("disable_singleton")) - { - dtProx.taPJQ.updateStato(idxPrintJob, 1); - } - else - { - DataLayer.man.taPJQ.updateStato(idxPrintJob, 1); - } - } - else - { - // registro annullato in tab queue... - if (memLayer.ML.CRB("disable_singleton")) - { - dtProx.taPJQ.updateStato(idxPrintJob, -1); - } - else - { - DataLayer.man.taPJQ.updateStato(idxPrintJob, -1); - } - - } - return answ; + // compongo stringhe x file con nomi univoci + DateTime adesso = DateTime.Now; + string filePathName = $"{localPdfPath}\\temp\\{name}_{adesso:HHmmss}_{adesso:ffff}.{fileNameExtension}"; + Stream stream = new FileStream(SteamwareStrings.getFilePath(filePathName), FileMode.Create); + m_streams.Add(stream); + return stream; } /// - /// effettua la vera e propria fase di stampa + /// ciclo da fornire al renderizzatore dei report, per salvare 1 pdf da ogni pagina del report /// - /// - /// - /// - /// - /// + /// + /// + /// + /// + /// /// - private bool printAndLog(string keyParam, string printerName, bool answ, reportRichiesto report, devInfoParam deviceInfo) + private Stream CreateStreamPdf(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) { - try - { - if (logLevel > 5) logger.lg.scriviLog(String.Format("Sto per inviare un report alla stampante {0}", printerName), tipoLog.INFO); - reportPrinter.obj.printReport(report, printerName, keyParam, deviceInfo); - if (logLevel > 5) logger.lg.scriviLog(String.Format("inviato comando print alla stampante {0}", printerName), tipoLog.INFO); - answ = true; - } - catch (Exception e) - { - logger.lg.scriviLog(String.Format("Errore in fase di creazione e stampa report: stampante {0}, errore riscontrato {1}", printerName, e), tipoLog.EXCEPTION); - } - return answ; + // compongo stringhe + DateTime adesso = DateTime.Now; + string dailyDir = $"{localPdfPath}\\{adesso:yyyy}\\{adesso:MM}\\{adesso:dd}\\"; + string pdfPathName = $"{dailyDir}\\{name}_{adesso:HHmmss}_{adesso:ffff}.{fileNameExtension}"; + // creo Directory se non c'è + fileMover fm = new fileMover(dailyDir, ""); + fm.checkDir(); + Stream stream = new FileStream(SteamwareStrings.getFilePath(pdfPathName), FileMode.Create); + m_streams.Add(stream); + return stream; } /// - /// oggetto protected + /// Handler per PrintPageEvents /// - /// - protected reportPrinter() + /// + /// + private void PrintPage(object sender, PrintPageEventArgs ev) { - logLevel = memLayer.ML.CRI("_logLevel"); - doPdfCopy = memLayer.ML.CRB("doPdfCopy"); + Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); + ev.Graphics.DrawImage(pageImage, ev.PageBounds); + m_currentPageIndex++; + ev.HasMorePages = (m_currentPageIndex < m_streams.Count); } /// - /// singleton pubblico + /// funzione di stampa... /// - public static reportPrinter obj = new reportPrinter(); - /// - /// effettua pulizia della cartella temp x i files più vecchi di X ore (web.config) - /// - public void pulisciDir() + private void Print(string printerName) { - // num max ore di età x files "vecchi" da tenere in temp area... - int maxOre = memLayer.ML.CRI("maxAgeTempAreaHours"); - int eliminati = 0; - // ottengo elenco files *.emf - fileMover.obj.setDirectory(@"~\temp\"); - FileInfo[] _fis = fileMover.obj.elencoFiles_FI("*.emf"); - bool fatto = false; - foreach (FileInfo _file in _fis) + //const string printerName = "Microsoft Office Document Image Writer"; + //const string printerName = "Brother HL-2170W series"; + if (m_streams == null || m_streams.Count == 0) + return; + PrintDocument printDoc = new PrintDocument(); + printDoc.PrinterSettings.PrinterName = printerName; + if (!printDoc.PrinterSettings.IsValid) { - if (_file.CreationTime < DateTime.Now.AddHours(-maxOre)) // elimino files vecchi... - { - fatto = fileMover.obj.eliminaFile(_file); - if (fatto) - { - logger.lg.scriviLog(String.Format("Eliminato file {0}", _file.Name), tipoLog.INFO); - eliminati++; - } - } - } - // salvo il log degli update - if (eliminati > 0) - { - logger.lg.scriviLog(String.Format("Eliminati {0} files temporanei da area temp", eliminati), tipoLog.INFO); + Log.Instance.Error($"Impostazioni non valide per la stampante {printerName}"); + return; } + printDoc.PrintPage += new PrintPageEventHandler(PrintPage); + printDoc.Print(); } #endregion From 63f9d788a210b40a1a6e17522126e6cbeb190640 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 14 Feb 2020 11:49:57 +0100 Subject: [PATCH 6/8] Ok prototipo stampa ma riparte troppo velocemente.. --- LPA/MainForm.cs | 8 ++++---- LPA/reportPrinter.cs | 18 ++++++++++++------ 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/LPA/MainForm.cs b/LPA/MainForm.cs index 5192205..103bdb8 100644 --- a/LPA/MainForm.cs +++ b/LPA/MainForm.cs @@ -103,7 +103,7 @@ namespace LPA { baseDir = AppDomain.CurrentDomain.BaseDirectory; serverBaseAddr = memLayer.ML.CRS("serverBaseAddr"); - localReportPath = $"{AppDomain.CurrentDomain.BaseDirectory}\\{memLayer.ML.CRS("localReportPath")}\\"; + localReportPath = $"{AppDomain.CurrentDomain.BaseDirectory}{memLayer.ML.CRS("localReportPath")}\\"; } /// /// Fix timers @@ -189,7 +189,7 @@ namespace LPA /// /// /// - protected string postUrl(string url2call, string payload) + protected string putUrl(string url2call, string payload) { string result = ""; // fix contenuto @@ -562,7 +562,7 @@ namespace LPA queueConf confCoda = listQueue.Find(conf => conf.name == coda.Key); if (confCoda != null) { - fatto = rPrint.printReport(confCoda.rdsName, localReportPath, coda.Value.Printer, item.rdsTable, confCoda.deviceInfoParam, true); + fatto = rPrint.printReport(confCoda.template,confCoda.rdsName, localReportPath, coda.Value.Printer, item.rdsTable, confCoda.deviceInfoParam, true); } // fatta stampa aggiorno server con indicazione ceh ho stampato if (fatto) @@ -576,7 +576,7 @@ namespace LPA }; string payload = JsonConvert.SerializeObject(printResult); // chiamo in put print result! - + putUrl(url2call, payload); } } } diff --git a/LPA/reportPrinter.cs b/LPA/reportPrinter.cs index 769f080..dac4751 100644 --- a/LPA/reportPrinter.cs +++ b/LPA/reportPrinter.cs @@ -14,6 +14,10 @@ namespace LPA { public class reportPrinter { + /// + /// Directory di abse applicazione + /// + protected string baseDir; /// /// Path x salvataggio locale pdf /// @@ -23,6 +27,7 @@ namespace LPA /// public reportPrinter() { + baseDir = AppDomain.CurrentDomain.BaseDirectory; localPdfPath = memLayer.ML.confReadString("localPdfPath"); } @@ -39,19 +44,20 @@ namespace LPA /// /// Crea un report locale da file rdlc, carica i dati, esporta report come EMF file e quindi lo invia alla stampante + eventuale backup pdf /// + /// Nome report (file) /// Nome report /// Cartella locale dei report /// nome completo stampante (rispetto al server) /// tabella dati da caricare nel report /// parametri "device input" /// effettua ANCHE copia pdf - public bool printReport(string rdsName, string localReportPath, string printerName, DataTable tabDati, devInfoParam deviceInfoParam, bool doPdfCopy) + public bool printReport(string reportTemplate, string rdsName, string localReportPath, string printerName, DataTable tabDati, devInfoParam deviceInfoParam, bool doPdfCopy) { bool answ = false; LocalReport report = new LocalReport(); report.EnableExternalImages = true; string deviceInfo = ""; - report.ReportPath = $"{localReportPath}\\{rdsName}"; + report.ReportPath = $"{localReportPath}\\{reportTemplate}"; report.DataSources.Add(new ReportDataSource(rdsName, tabDati)); deviceInfo = deviceInfoParam.xmlParam; // stampa da EMF @@ -142,8 +148,8 @@ namespace LPA { // compongo stringhe x file con nomi univoci DateTime adesso = DateTime.Now; - string filePathName = $"{localPdfPath}\\temp\\{name}_{adesso:HHmmss}_{adesso:ffff}.{fileNameExtension}"; - Stream stream = new FileStream(SteamwareStrings.getFilePath(filePathName), FileMode.Create); + string filePathName = $"{baseDir}{localPdfPath}\\temp\\{name}_{adesso:HHmmss}_{adesso:ffff}.{fileNameExtension}"; + Stream stream = new FileStream(filePathName, FileMode.Create); m_streams.Add(stream); return stream; } @@ -160,12 +166,12 @@ namespace LPA { // compongo stringhe DateTime adesso = DateTime.Now; - string dailyDir = $"{localPdfPath}\\{adesso:yyyy}\\{adesso:MM}\\{adesso:dd}\\"; + string dailyDir = $"{baseDir}{localPdfPath}\\{adesso:yyyy}\\{adesso:MM}\\{adesso:dd}\\"; string pdfPathName = $"{dailyDir}\\{name}_{adesso:HHmmss}_{adesso:ffff}.{fileNameExtension}"; // creo Directory se non c'è fileMover fm = new fileMover(dailyDir, ""); fm.checkDir(); - Stream stream = new FileStream(SteamwareStrings.getFilePath(pdfPathName), FileMode.Create); + Stream stream = new FileStream(pdfPathName, FileMode.Create); m_streams.Add(stream); return stream; } From b03469459930e9f9e2ec13e19f1265a784e2a3ae Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 14 Feb 2020 13:00:08 +0100 Subject: [PATCH 7/8] INserito veto print + try/catch x evitare blocco --- LPA/App.config | 1 + LPA/MainForm.cs | 53 ++++++++++++++++++++++++++------------------ LPA/reportPrinter.cs | 51 +++++++++++++++++++++++++++++++++++++----- 3 files changed, 79 insertions(+), 26 deletions(-) diff --git a/LPA/App.config b/LPA/App.config index e6d5006..e58f1cb 100644 --- a/LPA/App.config +++ b/LPA/App.config @@ -9,6 +9,7 @@ + diff --git a/LPA/MainForm.cs b/LPA/MainForm.cs index 103bdb8..9834166 100644 --- a/LPA/MainForm.cs +++ b/LPA/MainForm.cs @@ -59,6 +59,10 @@ namespace LPA /// Classe gestioen stampa report /// protected reportPrinter rPrint; + /// + /// Variabile appoggio semaforo divieto print x evitare accodamenti... 15 sec da last check... + /// + protected DateTime vetoPrint; #endregion @@ -104,6 +108,7 @@ namespace LPA baseDir = AppDomain.CurrentDomain.BaseDirectory; serverBaseAddr = memLayer.ML.CRS("serverBaseAddr"); localReportPath = $"{AppDomain.CurrentDomain.BaseDirectory}{memLayer.ML.CRS("localReportPath")}\\"; + vetoPrint = DateTime.Now; } /// /// Fix timers @@ -555,29 +560,37 @@ namespace LPA { // aggiorno contatore... coda.Value.NumWaiting = report2print.Count; - foreach (var item in report2print) + + // verifico non ci sia veto print.. + DateTime adesso = DateTime.Now; + if (vetoPrint < adesso) { - bool fatto = false; - // se ho almeno 1 stampa --> lancio! - queueConf confCoda = listQueue.Find(conf => conf.name == coda.Key); - if (confCoda != null) + vetoPrint = adesso.AddSeconds(30); + foreach (var item in report2print) { - fatto = rPrint.printReport(confCoda.template,confCoda.rdsName, localReportPath, coda.Value.Printer, item.rdsTable, confCoda.deviceInfoParam, true); - } - // fatta stampa aggiorno server con indicazione ceh ho stampato - if (fatto) - { - // compongo payload... - printTask printResult = new printTask() + bool fatto = false; + // se ho almeno 1 stampa --> lancio! + queueConf confCoda = listQueue.Find(conf => conf.name == coda.Key); + if (confCoda != null) { - ticketNum = item.ticketNum, - newStatus = 1, - message = "" - }; - string payload = JsonConvert.SerializeObject(printResult); - // chiamo in put print result! - putUrl(url2call, payload); + fatto = rPrint.printReport(confCoda.template, confCoda.rdsName, localReportPath, coda.Value.Printer, item.rdsTable, confCoda.deviceInfoParam, true); + } + // fatta stampa aggiorno server con indicazione ceh ho stampato + if (fatto) + { + // compongo payload... + printTask printResult = new printTask() + { + ticketNum = item.ticketNum, + newStatus = 1, + message = "" + }; + string payload = JsonConvert.SerializeObject(printResult); + // chiamo in put print result! + putUrl(url2call, payload); + } } + vetoPrint = adesso; } } } @@ -588,7 +601,5 @@ namespace LPA #endregion - - } } diff --git a/LPA/reportPrinter.cs b/LPA/reportPrinter.cs index dac4751..2fa4482 100644 --- a/LPA/reportPrinter.cs +++ b/LPA/reportPrinter.cs @@ -85,6 +85,8 @@ namespace LPA m_currentPageIndex = 0; // stampo Print(printerName); + // pulizia files da area temp... + pulisciDir(); // do dispose? Dispose(); } @@ -128,12 +130,14 @@ namespace LPA /// public void Dispose() { +#if false if (m_streams != null) { foreach (Stream stream in m_streams) stream.Close(); m_streams = null; - } + } +#endif } /// /// ciclo da fornire al renderizzatore dei report, per salvare 1 immagine da ogni pagina del report @@ -182,10 +186,17 @@ namespace LPA /// private void PrintPage(object sender, PrintPageEventArgs ev) { - Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); - ev.Graphics.DrawImage(pageImage, ev.PageBounds); - m_currentPageIndex++; - ev.HasMorePages = (m_currentPageIndex < m_streams.Count); + try + { + Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); + ev.Graphics.DrawImage(pageImage, ev.PageBounds); + m_currentPageIndex++; + ev.HasMorePages = (m_currentPageIndex < m_streams.Count); + } + catch(Exception exc) + { + Log.Instance.Error(exc, "Errore in PrintPage"); + } } /// /// funzione di stampa... @@ -206,6 +217,36 @@ namespace LPA printDoc.PrintPage += new PrintPageEventHandler(PrintPage); printDoc.Print(); } + /// + /// effettua pulizia della cartella temp x i files più vecchi di X ore (web.config) + /// + public void pulisciDir() + { + // num max ore di età x files "vecchi" da tenere in temp area... + int maxAgeMinutes = memLayer.ML.CRI("maxAgeTempArea"); + int eliminati = 0; + // ottengo elenco files *.emf + fileMover.obj.setDirectory($"{baseDir}{localPdfPath}\\temp\\"); + FileInfo[] _fis = fileMover.obj.elencoFiles_FI("*.emf"); + bool fatto = false; + foreach (FileInfo _file in _fis) + { + if (_file.CreationTime < DateTime.Now.AddMinutes(-maxAgeMinutes)) // elimino files vecchi... + { + fatto = fileMover.obj.eliminaFile(_file); + if (fatto) + { + Log.Instance.Info($"Eliminato file {_file.Name}"); + eliminati++; + } + } + } + // salvo il log degli update + if (eliminati > 0) + { + Log.Instance.Info($"Eliminati {eliminati} files temporanei da area temp"); + } + } #endregion } From a06c8f339c71c87427fe66965c09010cb83d8279 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Fri, 14 Feb 2020 13:11:04 +0100 Subject: [PATCH 8/8] PRIMA BOZZA stampa... --- LPA/MainForm.cs | 16 +++------------- LPA/reportPrinter.cs | 2 -- 2 files changed, 3 insertions(+), 15 deletions(-) diff --git a/LPA/MainForm.cs b/LPA/MainForm.cs index 9834166..ab5fcf3 100644 --- a/LPA/MainForm.cs +++ b/LPA/MainForm.cs @@ -56,10 +56,6 @@ namespace LPA /// protected List listQueue = new List(); /// - /// Classe gestioen stampa report - /// - protected reportPrinter rPrint; - /// /// Variabile appoggio semaforo divieto print x evitare accodamenti... 15 sec da last check... /// protected DateTime vetoPrint; @@ -90,14 +86,6 @@ namespace LPA refreshLocaltemplate(); refreshQueueAvail(); setupDGV(); - setupReportPrinter(); - } - /// - /// Setup istanza classe stampa report - /// - private void setupReportPrinter() - { - rPrint = new reportPrinter(); } /// @@ -550,6 +538,8 @@ namespace LPA // se ho stampe in coda --> verifico code gestite foreach (var coda in queueSetupConf) { + // init report printer... + reportPrinter rPrint = new reportPrinter(); url2call = $"{serverBaseAddr}/api/PrintQueue/{coda.Key}"; rawData = callUrl(url2call); if (!string.IsNullOrEmpty(rawData)) @@ -573,7 +563,7 @@ namespace LPA queueConf confCoda = listQueue.Find(conf => conf.name == coda.Key); if (confCoda != null) { - fatto = rPrint.printReport(confCoda.template, confCoda.rdsName, localReportPath, coda.Value.Printer, item.rdsTable, confCoda.deviceInfoParam, true); + fatto = rPrint.printReport(confCoda.template, confCoda.rdsName, localReportPath, coda.Value.Printer, item.rdsTable, confCoda.deviceInfoParam, false); } // fatta stampa aggiorno server con indicazione ceh ho stampato if (fatto) diff --git a/LPA/reportPrinter.cs b/LPA/reportPrinter.cs index 2fa4482..ecc81aa 100644 --- a/LPA/reportPrinter.cs +++ b/LPA/reportPrinter.cs @@ -130,14 +130,12 @@ namespace LPA /// public void Dispose() { -#if false if (m_streams != null) { foreach (Stream stream in m_streams) stream.Close(); m_streams = null; } -#endif } /// /// ciclo da fornire al renderizzatore dei report, per salvare 1 immagine da ogni pagina del report