From c63485f8277911e409683aee710e81974a677fbe Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Thu, 6 Aug 2020 12:02:50 +0200 Subject: [PATCH] Typo refresh + loggging refresh --- .editorconfig | 7 + LPA.sln | 5 + LPA/App.config | 119 ++-- LPA/LPA.csproj | 3 + LPA/MainForm.cs | 1459 ++++++++++++++++++++++++----------------------- 5 files changed, 819 insertions(+), 774 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a8314cb --- /dev/null +++ b/.editorconfig @@ -0,0 +1,7 @@ +[*.cs] + +# CA1031: Non rilevare tipi di eccezione generali +dotnet_diagnostic.CA1031.severity = none + +# CA1303: Non passare valori letterali come parametri localizzati +dotnet_diagnostic.CA1303.severity = none diff --git a/LPA.sln b/LPA.sln index 771c60f..fb4c6ec 100644 --- a/LPA.sln +++ b/LPA.sln @@ -7,6 +7,11 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LPA", "LPA\LPA.csproj", "{F EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VersGen", "VersGen\VersGen.csproj", "{58E399F3-9D4E-49D3-AB35-9ED536543D50}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8A16CC40-FAB6-4BF5-8AC8-7B7AB1A27C66}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/LPA/App.config b/LPA/App.config index e9ce3ea..5cd7a5a 100644 --- a/LPA/App.config +++ b/LPA/App.config @@ -1,62 +1,63 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/LPA/LPA.csproj b/LPA/LPA.csproj index 9650772..194d57a 100644 --- a/LPA/LPA.csproj +++ b/LPA/LPA.csproj @@ -198,6 +198,9 @@ True Resources.resx + + .editorconfig + Always diff --git a/LPA/MainForm.cs b/LPA/MainForm.cs index ad6d1e1..00b605f 100644 --- a/LPA/MainForm.cs +++ b/LPA/MainForm.cs @@ -13,745 +13,774 @@ using System.Windows.Forms; namespace LPA { - public partial class MainForm : Form - { - #region variabili di base + public partial class MainForm : Form + { + #region variabili di base - /// - /// Lista delle code di stampa da gestire - /// - protected List pqList; - /// - /// Indirizzo base del server cui connettersi - /// - protected string serverBaseAddr; - /// - /// Path salvataggio locale reports - /// - protected string localReportPath; - /// - /// Status runing della coda di stampa - /// - protected bool spoolerRun = false; - /// - /// Directory di abse applicazione - /// - protected string baseDir; - /// - /// File conf x setup code - /// - protected string qSetFilePath - { - get - { - string answ = demoMode ? "queueSetupDemo.json" : "queueSetup.json"; - return answ; - } - } - /// - /// Configurazione CORRENTE delle code di stampa (coda --> printer disponibile) - /// - protected Dictionary queueSetupConf; - /// - /// Binding source degli elementi di print queue gestiti.. - /// - private BindingSource pqBindSource = new BindingSource(); - /// - /// Uptime globale applicazione - /// - protected DateTime appStart = DateTime.Now; - /// - /// Code di stampa disponibili (da server) - /// - protected List listQueue = new List(); - /// - /// Variabile appoggio semaforo divieto print x evitare accodamenti... 15 sec da last check... - /// - protected DateTime vetoPrint; - /// - /// Modalità demo/test printing locale - /// - protected bool demoMode = false; - #endregion - - #region init form + dispose - - /// - /// Classe apertura - /// - public MainForm() - { - InitializeComponent(); - myInit(); - } - - private void myInit() - { - Log.Instance.Info("Avvio applicazione"); - spoolerRun = true; - setupConf(); - setupTimers(); - setupQueuePrinter(); - setupButtons(); - showPrinterList(); - setupPrintersList(); - refreshLocaltemplate(); - refreshQueueAvail(); - 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")}\\"; - vetoPrint = DateTime.Now; - } - /// - /// Fix timers - /// - private void setupTimers() - { - uiTimer.Interval = 50; - mainTimer.Interval = 900; - longTimer.Interval = 6000; - 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; - // 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 - /// - private void setupButtons() - { - btnStart.Enabled = !spoolerRun; - btnStop.Enabled = spoolerRun; - lblStatus.ForeColor = spoolerRun ? Color.Green : Color.OrangeRed; - lblStatus.Text = spoolerRun ? "Running" : "Stopped"; - // se demo aggiungo... - if (demoMode) - { - lblStatus.Text += " TEST/DEMO MODE"; - } - btnDemoPrint.Visible = demoMode; - chkTryMargin.Visible = demoMode; - } - /// - /// Setup oggetto DGV - /// - private void setupDGV() - { - // gestione eventi binding source - 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); - } - } - /// - /// Pulizia finale delle risorse in uso. - /// - /// ha valore true se le risorse gestite devono essere eliminate, false in caso contrario. - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (components != null) + /// + /// Lista delle code di stampa da gestire + /// + protected List pqList; + /// + /// Indirizzo base del server cui connettersi + /// + protected string serverBaseAddr; + /// + /// Path salvataggio locale reports + /// + protected string localReportPath; + /// + /// Status runing della coda di stampa + /// + protected bool spoolerRun = false; + /// + /// Directory di abse applicazione + /// + protected string baseDir; + /// + /// File conf x setup code + /// + protected string qSetFilePath { - components.Dispose(); + get + { + string answ = demoMode ? "queueSetupDemo.json" : "queueSetup.json"; + return answ; + } + } + /// + /// Configurazione CORRENTE delle code di stampa (coda --> printer disponibile) + /// + protected Dictionary queueSetupConf; + /// + /// Binding source degli elementi di print queue gestiti.. + /// + private BindingSource pqBindSource = new BindingSource(); + /// + /// Uptime globale applicazione + /// + protected DateTime appStart = DateTime.Now; + /// + /// Code di stampa disponibili (da server) + /// + protected List listQueue = new List(); + /// + /// Variabile appoggio semaforo divieto print x evitare accodamenti... 15 sec da last check... + /// + protected DateTime vetoPrint; + /// + /// Modalità demo/test printing locale + /// + protected bool demoMode = false; + #endregion + + #region init form + dispose + + /// + /// Classe apertura + /// + public MainForm() + { + InitializeComponent(); + myInit(); } - // Dispose stuff here - pqBindSource.Dispose(); - } - - base.Dispose(disposing); - } - - #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; - } - /// - /// 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.postAsync(callUri, callCont)); - 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\\{qSetFilePath}"; - // cerco file x leggere conf... - if (File.Exists(fullPath)) + private void myInit() { - try - { - string rawData = File.ReadAllText(fullPath); + utils.lgInfo("Starting app"); + lblAppName.Text = memLayer.ML.CRS("appName"); + spoolerRun = true; + setupConf(); + setupTimers(); + setupQueuePrinter(); + setupButtons(); + showPrinterList(); + setupPrintersList(); + refreshLocaltemplate(); + refreshQueueAvail(); + 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")}\\"; + vetoPrint = DateTime.Now; + } + /// + /// Fix timers + /// + private void setupTimers() + { + uiTimer.Interval = 50; + mainTimer.Interval = 900; + longTimer.Interval = 6000; + 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; + // 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 + /// + private void setupButtons() + { + btnStart.Enabled = !spoolerRun; + btnStop.Enabled = spoolerRun; + lblStatus.ForeColor = spoolerRun ? Color.Green : Color.OrangeRed; + lblStatus.Text = spoolerRun ? "Running" : "Stopped"; + // se demo aggiungo... + if (demoMode) + { + lblStatus.Text += " TEST/DEMO MODE"; + } + btnDemoPrint.Visible = demoMode; + chkTryMargin.Visible = demoMode; + } + /// + /// Setup oggetto DGV + /// + private void setupDGV() + { + // gestione eventi binding source + 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); + } + } + /// + /// Pulizia finale delle risorse in uso. + /// + /// ha valore true se le risorse gestite devono essere eliminate, false in caso contrario. + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (components != null) + { + components.Dispose(); + } + + // Dispose stuff here + pqBindSource.Dispose(); + } + + base.Dispose(disposing); + } + + #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; + } + /// + /// 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.postAsync(callUri, callCont)); + 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\\{qSetFilePath}"; + // 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) + { + utils.lgError("Error in deserialization of queueSetupJson file", exc); + } + } + return answ; + } + set + { + string fullPath = $"{baseDir}conf\\{qSetFilePath}"; + string rawData = JsonConvert.SerializeObject(value); + 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 + + #region gestione cicli di esecuzione + + /// + /// Timer principale di refresh + /// + /// + /// + private void MainTimer_Tick(object sender, EventArgs e) + { + // effettuo chiamata coda stampa... + refreshQueueStatus(); + // aggiorno visualizzazione + updateDGV(); + } + /// + /// Timer lungo periodo (salvataggi) + /// + /// + /// + private void LongTimer_Tick(object sender, EventArgs e) + { + // salvo conf ... + queueSetupJson = queueSetupConf; + // 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); + } + // pulizia files da area temp... + reportPrinter rPrint = new reportPrinter(); + rPrint.pulisciDir(); + } + /// + /// Rrefresh interfaccia + /// + /// + /// + private void UiTimer_Tick(object sender, EventArgs e) + { + progBar.Increment(1); + if (progBar.Value >= 100) + { + 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; + vetoPrint = DateTime.Now; + 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) + { + utils.lgError($"Impossible to associate to queue {currQueue} requested printer: {queueSetupConf[currQueue]}", exc); + } + } + } + } + + 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; + utils.lgInfo("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; + } + } + + /// + /// Testing print demo da files locali + /// + /// + /// + private void btnDemoPrint_Click(object sender, EventArgs e) + { + string rawData = ""; + string filePath = ""; + // SE SONO in DEMO mode, leggo da file locali e chiamo procedura di stampa! + if (demoMode) + { + // verifico code gestite + foreach (var coda in queueSetupConf) + { + filePath = $"{baseDir}demo\\{coda.Key}.json"; + rawData = File.ReadAllText(filePath); + if (!string.IsNullOrEmpty(rawData)) + { + try + { + // deserializzo + List report2print = JsonConvert.DeserializeObject>(rawData); + if (report2print != null) + { + // aggiorno contatore... + coda.Value.NumWaiting = report2print.Count; + // verifico sia RUNNING... + if (coda.Value.isRunning) + { + // verifico non ci sia veto print.. + DateTime adesso = DateTime.Now; + if (vetoPrint < adesso) + { + vetoPrint = adesso.AddSeconds(300); + foreach (var item in report2print) + { + reportPrinter rPrint = new reportPrinter(); + bool fatto = false; + bool fattoPdf = false; + // se ho almeno 1 stampa --> lancio! + queueConf confCoda = listQueue.Find(conf => conf.name == coda.Key); + if (confCoda != null) + { + // se ho selezionato test margini --> 3 stampe con valori 0/5/10 + if (chkTryMargin.Checked) + { + int numStep = 3; + string currMargin = ""; + for (int i = 0; i < numStep; i++) + { + // cambio i valori dei parametri deviceInfo + currMargin = $"{i * 5}mm"; + confCoda.deviceInfoParam.MarginBottom = currMargin; + confCoda.deviceInfoParam.MarginTop = currMargin; + confCoda.deviceInfoParam.MarginRight = currMargin; + confCoda.deviceInfoParam.MarginLeft = currMargin; + confCoda.deviceInfoParam.OutputFormat = confCoda.deviceInfoParam.OutputFormat.Replace("10mm", currMargin); + // stampo! + fatto = rPrint.printReport(confCoda.template, localReportPath, coda.Value.Printer, item.rdsData, confCoda.deviceInfoParam, true); + if (fatto) + { + coda.Value.NumWaiting--; + coda.Value.NumDone++; + } + } + } + else + { + fatto = rPrint.printReport(confCoda.template, localReportPath, coda.Value.Printer, item.rdsData, confCoda.deviceInfoParam, true); + if (fatto) + { + coda.Value.NumWaiting--; + coda.Value.NumDone++; + } + } + } + } + vetoPrint = adesso; + } + } + } + } + catch (Exception exc) + { + utils.lgError("Error in deserialization during btnDemoPrint_Click", exc); + } + } + } + } + } + + private void enableTestDemoModeToolStripMenuItem_Click(object sender, EventArgs e) + { + string message = demoMode ? "Confermi di voler abbandonare la modalità test/Demo?" : "Attenzione! sei sicuro di voler attivare la modalità Test/Demo? il sistema funzionerà in modalità offline e configurate le code di stampa effettuerà test di stampa locale"; + string title = "Test / Demo mode"; + DialogResult result = MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); + if (result == DialogResult.Yes) + { + demoMode = !demoMode; + } + // ricarico dati code e conf... + + // update buttons... + menuEnableDemo.Text = demoMode ? "&Exit Test Mode" : "&Enter Test Mode"; + setupButtons(); + // aggiorno code... + setupQueuePrinter(); + refreshQueueAvail(); + } + + #endregion + + #region metodi di chiamata a server + + /// + /// 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)) { - answ = JsonConvert.DeserializeObject>(rawData); - } - } - catch (Exception exc) - { - Log.Instance.Error(exc, "Errore in decodifica file queueSetup"); - } - } - return answ; - } - set - { - string fullPath = $"{baseDir}conf\\{qSetFilePath}"; - string rawData = JsonConvert.SerializeObject(value); - 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 - - #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 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); - } - // pulizia files da area temp... - reportPrinter rPrint = new reportPrinter(); - rPrint.pulisciDir(); - } - /// - /// Rrefresh interfaccia - /// - /// - /// - private void UiTimer_Tick(object sender, EventArgs e) - { - progBar.Increment(1); - if (progBar.Value >= 100) - { - 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; - vetoPrint = DateTime.Now; - 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; - } - } - - /// - /// Testing print demo da files locali - /// - /// - /// - private void btnDemoPrint_Click(object sender, EventArgs e) - { - string rawData = ""; - string filePath = ""; - // SE SONO in DEMO mode, leggo da file locali e chiamo procedura di stampa! - if (demoMode) - { - // verifico code gestite - foreach (var coda in queueSetupConf) - { - filePath = $"{baseDir}demo\\{coda.Key}.json"; - rawData = File.ReadAllText(filePath); - if (!string.IsNullOrEmpty(rawData)) - { - // deserializzo - List report2print = JsonConvert.DeserializeObject>(rawData); - if (report2print != null) - { - // aggiorno contatore... - coda.Value.NumWaiting = report2print.Count; - // verifico sia RUNNING... - if (coda.Value.isRunning) - { - // verifico non ci sia veto print.. - DateTime adesso = DateTime.Now; - if (vetoPrint < adesso) + try { - vetoPrint = adesso.AddSeconds(300); - foreach (var item in report2print) - { - reportPrinter rPrint = new reportPrinter(); - bool fatto = false; - bool fattoPdf = false; - // se ho almeno 1 stampa --> lancio! - queueConf confCoda = listQueue.Find(conf => conf.name == coda.Key); - if (confCoda != null) + // deserializzo + objFiles = JsonConvert.DeserializeObject(rawData); + if (objFiles != null) { - // se ho selezionato test margini --> 3 stampe con valori 0/5/10 - if (chkTryMargin.Checked) - { - int numStep = 3; - string currMargin = ""; - for (int i = 0; i < numStep; i++) + // salvo! + foreach (var item in objFiles.fileList) { - // cambio i valori dei parametri deviceInfo - currMargin = $"{i * 5}mm"; - confCoda.deviceInfoParam.MarginBottom = currMargin; - confCoda.deviceInfoParam.MarginTop = currMargin; - confCoda.deviceInfoParam.MarginRight = currMargin; - confCoda.deviceInfoParam.MarginLeft = currMargin; - confCoda.deviceInfoParam.OutputFormat = confCoda.deviceInfoParam.OutputFormat.Replace("10mm", currMargin); - // stampo! - fatto = rPrint.printReport(confCoda.template, localReportPath, coda.Value.Printer, item.rdsData, confCoda.deviceInfoParam, true); - if (fatto) - { - coda.Value.NumWaiting--; - coda.Value.NumDone++; - } + string fullPath = $"{localReportPath}{item.fileName}"; + File.WriteAllText(fullPath, item.content); } - } - else - { - fatto = rPrint.printReport(confCoda.template, localReportPath, coda.Value.Printer, item.rdsData, confCoda.deviceInfoParam, true); - if (fatto) - { - coda.Value.NumWaiting--; - coda.Value.NumDone++; - } - } + utils.lgInfo("Download template files aggiornati"); + } + else + { + utils.lgError($"Error: invalid file data received, deserialized to null ({rawData})"); } - } - vetoPrint = adesso; } - } + catch (Exception exc) + { + utils.lgError("Error in deserialization during refreshLocaltemplate", exc); + } + } + else + { + utils.lgError("Error: no file data downloaded"); } - } } - } - } - - private void enableTestDemoModeToolStripMenuItem_Click(object sender, EventArgs e) - { - string message = demoMode ? "Confermi di voler abbandonare la modalità test/Demo?" : "Attenzione! sei sicuro di voler attivare la modalità Test/Demo? il sistema funzionerà in modalità offline e configurate le code di stampa effettuerà test di stampa locale"; - string title = "Test / Demo mode"; - DialogResult result = MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); - if (result == DialogResult.Yes) - { - demoMode = !demoMode; - } - // ricarico dati code e conf... - - // update buttons... - menuEnableDemo.Text = demoMode ? "&Exit Test Mode" : "&Enter Test Mode"; - setupButtons(); - // aggiorno code... - setupQueuePrinter(); - refreshQueueAvail(); - } - - #endregion - - #region metodi di chiamata a server - - /// - /// 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) + /// + /// Aggiornamento code stampa disponibili + /// + private void refreshQueueAvail() { - // 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"); - } - } - /// - /// Aggiornamento code stampa disponibili - /// - private void refreshQueueAvail() - { - // svuoto - lbPrintQueue.Items.Clear(); - string rawData = ""; - // se sono in demo leggo da locale - if (demoMode) - { - // leggo da locale... - string filePath = $"{baseDir}demo\\PrintQueueConf.json"; - rawData = File.ReadAllText(filePath); - } - // altrimenti da metodi REST su server... - else - { - // scarico TUTTI i report definiti - string url2call = $"{serverBaseAddr}/api/PrintQueueConf"; - rawData = callUrl(url2call); - } - if (!string.IsNullOrEmpty(rawData)) - { - // deserializzo - listQueue = JsonConvert.DeserializeObject>(rawData); - if (listQueue != null) - { - // metto in elenco - foreach (var item in listQueue) - { - lbPrintQueue.Items.Add(item.name); - } - Log.Instance.Info("Effettuato update elenco printQueue"); - } - else - { - Log.Instance.Error($"Error: invalid file data received, deserialized to null ({rawData})"); - } - } - else - { - Log.Instance.Error("Error: no file data downloaded"); - } - showPrinterList(); - } - /// - /// Aggiorna stato code - /// - private void refreshQueueStsatus() - { - // verifico ed aggiorno quantità coda - int numTot = 0; - string urlApiQueue = $"{serverBaseAddr}/api/PrintQueue"; - string rawData = callUrl(urlApiQueue); - if (!string.IsNullOrEmpty(rawData)) - { - // 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) - { - string urlSingleQueue = $"{serverBaseAddr}/api/PrintQueue/{coda.Key}"; - rawData = callUrl(urlSingleQueue); + // svuoto + lbPrintQueue.Items.Clear(); + string rawData = ""; + // se sono in demo leggo da locale + if (demoMode) + { + // leggo da locale... + string filePath = $"{baseDir}demo\\PrintQueueConf.json"; + rawData = File.ReadAllText(filePath); + } + // altrimenti da metodi REST su server... + else + { + // scarico TUTTI i report definiti + string url2call = $"{serverBaseAddr}/api/PrintQueueConf"; + rawData = callUrl(url2call); + } if (!string.IsNullOrEmpty(rawData)) { - // deserializzo - List report2print = JsonConvert.DeserializeObject>(rawData); - if (report2print != null) - { - // aggiorno contatore... - coda.Value.NumWaiting = report2print.Count; - // verifico sia RUNNING... - if (coda.Value.isRunning) + try { - // verifico non ci sia veto print.. - DateTime adesso = DateTime.Now; - if (vetoPrint < adesso) - { - vetoPrint = adesso.AddSeconds(300); - foreach (var item in report2print) + // deserializzo + listQueue = JsonConvert.DeserializeObject>(rawData); + if (listQueue != null) { - reportPrinter rPrint = new reportPrinter(); - bool fatto = false; - bool fattoPdf = false; - // se ho almeno 1 stampa --> lancio! - queueConf confCoda = listQueue.Find(conf => conf.name == coda.Key); - if (confCoda != null) - { - fatto = rPrint.printReport(confCoda.template, localReportPath, coda.Value.Printer, item.rdsData, confCoda.deviceInfoParam, true); - } - // fatta stampa aggiorno server con indicazione ceh ho stampato - if (fatto) - { - coda.Value.NumWaiting--; - coda.Value.NumDone++; - // compongo payload... - printTask printResult = new printTask() + // metto in elenco + foreach (var item in listQueue) { - ticketNum = item.ticketNum, - newStatus = 1, - message = "" - }; - string payload = JsonConvert.SerializeObject(printResult); - // chiamo in put print result! - postUrl(urlApiQueue, payload); - } + lbPrintQueue.Items.Add(item.name); + } + utils.lgInfo("Effettuato update elenco printQueue"); + } + else + { + utils.lgError($"Error: invalid file data received, deserialized to null ({rawData})"); } - vetoPrint = adesso; - } } - } + catch (Exception exc) + { + utils.lgError("Error in deserialization during refreshQueueAvail", exc); + } } - } + else + { + utils.lgError("Error: no file data downloaded"); + } + showPrinterList(); } - } + /// + /// Aggiorna stato code + /// + private void refreshQueueStatus() + { + // verifico ed aggiorno quantità coda + int numTot = 0; + string urlApiQueue = $"{serverBaseAddr}/api/PrintQueue"; + string rawData = callUrl(urlApiQueue); + if (!string.IsNullOrEmpty(rawData)) + { + try + { + // 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) + { + string urlSingleQueue = $"{serverBaseAddr}/api/PrintQueue/{coda.Key}"; + rawData = callUrl(urlSingleQueue); + if (!string.IsNullOrEmpty(rawData)) + { + // deserializzo + List report2print = JsonConvert.DeserializeObject>(rawData); + if (report2print != null) + { + // aggiorno contatore... + coda.Value.NumWaiting = report2print.Count; + // verifico sia RUNNING... + if (coda.Value.isRunning) + { + // verifico non ci sia veto print.. + DateTime adesso = DateTime.Now; + if (vetoPrint < adesso) + { + vetoPrint = adesso.AddSeconds(300); + foreach (var item in report2print) + { + reportPrinter rPrint = new reportPrinter(); + bool fatto = false; + bool fattoPdf = false; + // se ho almeno 1 stampa --> lancio! + queueConf confCoda = listQueue.Find(conf => conf.name == coda.Key); + if (confCoda != null) + { + fatto = rPrint.printReport(confCoda.template, localReportPath, coda.Value.Printer, item.rdsData, confCoda.deviceInfoParam, true); + } + // fatta stampa aggiorno server con indicazione ceh ho stampato + if (fatto) + { + coda.Value.NumWaiting--; + coda.Value.NumDone++; + // compongo payload... + printTask printResult = new printTask() + { + ticketNum = item.ticketNum, + newStatus = 1, + message = "" + }; + string payload = JsonConvert.SerializeObject(printResult); + // chiamo in put print result! + postUrl(urlApiQueue, payload); + } + } + vetoPrint = adesso; + } + } + } + } + } + } + } + catch (Exception exc) + { + utils.lgError("Error in deserialization during refreshQueueStatus", exc); + } + } + } + + #endregion + } - - #endregion - - } }