Merge branch 'develop'

This commit is contained in:
Samuele E. Locatelli
2020-02-14 13:11:08 +01:00
10 changed files with 618 additions and 606 deletions
+2 -1
View File
@@ -7,8 +7,9 @@
<!-- conf server comunicazione-->
<add key="serverBaseAddr" value="http://iis02/NKC" />
<add key="localReportPath" value="reports" />
<add key="queueSetupFile" value="queueSetup.json" />
<add key="localPdfPath" value="pdf" />
<add key="_logDir" value="/logs/" />
<add key="maxAgeTempArea" value="60" />
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+10 -2
View File
@@ -168,6 +168,7 @@
<Compile Include="printQueue.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="reportPrinter.cs" />
<Compile Include="utils.cs" />
<EmbeddedResource Include="MainForm.resx">
<DependentUpon>MainForm.cs</DependentUpon>
@@ -181,7 +182,10 @@
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="queueSetup.json">
<None Include="conf\.placeholder">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="conf\queueSetup.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="App_Readme\SteamWare_demo\example-app.config" />
@@ -193,6 +197,9 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
<None Include="pdf\.placeholder">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
@@ -205,7 +212,7 @@
<None Include="reports\.placeholder">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="temp\.placeholder">
<None Include="pdf\temp\.placeholder">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
@@ -229,6 +236,7 @@
<Content Include="App_Readme\SteamWare_demo\example-favicon.ico" />
<Content Include="mongocrypt.dll" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
+101 -47
View File
@@ -45,30 +45,33 @@
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.lblUptime = new System.Windows.Forms.ToolStripStatusLabel();
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;
@@ -80,11 +83,11 @@
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lblAppName,
this.progBar,
this.lblStatus});
this.statusStrip1.Location = new System.Drawing.Point(0, 600);
this.lblStatus,
this.lblUptime});
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 +95,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 +117,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 +140,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);
this.tabStatus.Size = new System.Drawing.Size(753, 399);
this.tabStatus.TabIndex = 0;
this.tabStatus.Text = "Status";
this.tabStatus.UseVisualStyleBackColor = true;
@@ -164,11 +162,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 +174,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);
this.tabSetup.Size = new System.Drawing.Size(753, 399);
this.tabSetup.TabIndex = 1;
this.tabSetup.Text = "Setup";
this.tabSetup.UseVisualStyleBackColor = true;
@@ -189,10 +185,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 +196,77 @@
// 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;
//
// lblUptime
//
this.lblUptime.Name = "lblUptime";
this.lblUptime.Size = new System.Drawing.Size(16, 17);
this.lblUptime.Text = "...";
//
// 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 +275,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 +299,11 @@
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;
private System.Windows.Forms.ToolStripStatusLabel lblUptime;
}
}
+352 -174
View File
@@ -1,20 +1,20 @@
using System;
using Newtonsoft.Json;
using SteamWare;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using SteamWare;
namespace LPA
{
public partial class MainForm : Form
{
#region variabili di base
/// <summary>
/// Lista delle code di stampa da gestire
/// </summary>
@@ -38,7 +38,7 @@ namespace LPA
/// <summary>
/// File conf x setup code
/// </summary>
protected string queueSetupFile;
protected string qSetFilePath = "queueSetup.json";
/// <summary>
/// Configurazione CORRENTE delle code di stampa (coda --> printer disponibile)
/// </summary>
@@ -47,6 +47,22 @@ namespace LPA
/// Binding source degli elementi di print queue gestiti..
/// </summary>
private BindingSource pqBindSource = new BindingSource();
/// <summary>
/// Uptime globale applicazione
/// </summary>
protected DateTime appStart = DateTime.Now;
/// <summary>
/// Code di stampa disponibili (da server)
/// </summary>
protected List<queueConf> listQueue = new List<queueConf>();
/// <summary>
/// Variabile appoggio semaforo divieto print x evitare accodamenti... 15 sec da last check...
/// </summary>
protected DateTime vetoPrint;
#endregion
#region init form
/// <summary>
/// Classe apertura
@@ -69,10 +85,61 @@ namespace LPA
setupPrintersList();
refreshLocaltemplate();
refreshQueueAvail();
setupQueue();
setupDGV();
}
/// <summary>
/// Setup parametri base di configurazione
/// </summary>
private void setupConf()
{
baseDir = AppDomain.CurrentDomain.BaseDirectory;
serverBaseAddr = memLayer.ML.CRS("serverBaseAddr");
localReportPath = $"{AppDomain.CurrentDomain.BaseDirectory}{memLayer.ML.CRS("localReportPath")}\\";
vetoPrint = DateTime.Now;
}
/// <summary>
/// Fix timers
/// </summary>
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();
}
/// <summary>
/// Setup code di stampa disponibili da server
/// </summary>
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;
}
/// <summary>
/// Setup dei bottoni stato start/stop
/// </summary>
private void setupButtons()
{
btnStart.Enabled = !spoolerRun;
btnStop.Enabled = spoolerRun;
lblStatus.ForeColor = spoolerRun ? Color.Green : Color.OrangeRed;
lblStatus.Text = spoolerRun ? "Running" : "Stopped";
}
/// <summary>
/// Setup oggetto DGV
/// </summary>
private void setupDGV()
{
// gestione eventi binding source
@@ -80,60 +147,52 @@ namespace LPA
pqBindSource.ListChanged += qpBSList_ListChanged;
}
/// <summary>
/// Evento cambio
/// Setup elenco stampanti da disponibili su PC
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void qpBSList_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e)
private void setupPrintersList()
{
updateDGV();
}
/// <summary>
/// Evento aggiunta
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void qpBSList_AddingNew(object sender, System.ComponentModel.AddingNewEventArgs e)
{
updateDGV();
}
private void updateDGV()
{
List<printQueue> elencoCode = new List<printQueue>();
foreach (var item in queueSetupConf)
lbPrinters.Items.Clear();
foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
elencoCode.Add(item.Value);
lbPrinters.Items.Add(printer);
}
dgvQueueStatus.DataSource = elencoCode;
dgvQueueStatus.Invalidate();
}
/// <summary>
/// Setup parametri base du configurazione
/// </summary>
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()
#endregion
#region metodi interni ed helpers
/// <summary>
/// Chiamata async URL
/// </summary>
/// <param name="url2call"></param>
/// <returns></returns>
protected string callUrl(string url2call)
{
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);
//}
string result = "";
// recupero dati
var taskRes = Task.Run(() => utils.getPageAsync(url2call));
taskRes.Wait();
result = taskRes.Result;
return result;
}
/// <summary>
/// Chiamata PUT async URL
/// </summary>
/// <param name="url2call"></param>
/// <param name="payload"></param>
/// <returns></returns>
protected string putUrl(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;
}
/// <summary>
/// Configurazione coda stampa da json file
@@ -143,7 +202,7 @@ namespace LPA
get
{
Dictionary<string, printQueue> answ = new Dictionary<string, printQueue>();
string fullPath = $"{baseDir}{queueSetupFile}";
string fullPath = $"{baseDir}conf\\{qSetFilePath}";
// cerco file x leggere conf...
if (File.Exists(fullPath))
{
@@ -164,81 +223,86 @@ namespace LPA
}
set
{
string fullPath = $"{baseDir}{queueSetupFile}";
string fullPath = $"{baseDir}conf\\{qSetFilePath}";
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";
}
/// <summary>
/// Aggiornamento code stampa disponibili
/// Evento cambio
/// </summary>
private void refreshQueueAvail()
/// <param name="sender"></param>
/// <param name="e"></param>
private void qpBSList_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e)
{
// svuoto
lbPrintQueue.Items.Clear();
// scarico TUTTI i report definiti
List<queueConf> listQueue = new List<queueConf>();
string rawData = "";
string url2call = $"{serverBaseAddr}/api/PrintQueueConf";
// recupero dati
var taskRes = Task.Run(() => utils.getPageAsync(url2call));
taskRes.Wait();
rawData = taskRes.Result;
if (!string.IsNullOrEmpty(rawData))
{
// deserializzo
listQueue = JsonConvert.DeserializeObject<List<queueConf>>(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();
updateDGV();
}
/// <summary>
/// Fix timers
/// Evento aggiunta
/// </summary>
private void setupTimers()
/// <param name="sender"></param>
/// <param name="e"></param>
private void qpBSList_AddingNew(object sender, System.ComponentModel.AddingNewEventArgs e)
{
uiTimer.Interval = 50;
mainTimer.Interval = 500;
uiTimer.Tick += UiTimer_Tick;
mainTimer.Tick += MainTimer_Tick;
uiTimer.Start();
mainTimer.Start();
updateDGV();
}
/// <summary>
/// aggiorna elemento DGV
/// </summary>
private void updateDGV()
{
List<printQueue> elencoCode = new List<printQueue>();
foreach (var item in queueSetupConf)
{
elencoCode.Add(item.Value);
}
dgvQueueStatus.DataSource = elencoCode;
dgvQueueStatus.Invalidate();
}
#endregion
#region gestione cicli di esecuzione
/// <summary>
/// Timer principale di refresh
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainTimer_Tick(object sender, EventArgs e)
{
// effettuo chiamata coda stampa...
refreshQueueStsatus();
// aggiorno visualizzazione
updateDGV();
}
/// <summary>
/// Timer lungo periodo (salvataggi)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
/// <summary>
/// Rrefresh interfaccia
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UiTimer_Tick(object sender, EventArgs e)
{
progBar.Increment(1);
@@ -246,69 +310,45 @@ 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)
/// <summary>
/// Effettua download dei template report in locale
/// Avvio processo gestione code
/// </summary>
private void refreshLocaltemplate()
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStart_Click(object sender, EventArgs e)
{
// 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))
spoolerRun = true;
setupButtons();
// resetto data avvio delle code...
foreach (var item in queueSetupConf)
{
// deserializzo
objFiles = JsonConvert.DeserializeObject<filePack>(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");
item.Value.startTime = DateTime.Now;
item.Value.isRunning = true;
}
}
private void setupQueue()
/// <summary>
/// stop processo gestione code
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStop_Click(object sender, EventArgs e)
{
// fare leggere conf da json locale...
pqList = new List<string>();
pqList.Add("default");
#if false
// ciclo su IOB configurati
foreach (var currIob in printQueue)
spoolerRun = false;
setupButtons();
// resetto data avvio delle code...
foreach (var item in queueSetupConf)
{
}
#endif
}
private void setupPrintersList()
{
lbPrinters.Items.Clear();
foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
lbPrinters.Items.Add(printer);
item.Value.isRunning = false;
}
}
@@ -322,17 +362,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 +442,154 @@ namespace LPA
btnSetQueuePrinter.Visible = doShow;
}
}
#endregion
#region metodi di chiamata a server
/// <summary>
/// Effettua download dei template report in locale
/// </summary>
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<filePack>(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");
}
}
/// <summary>
/// Aggiornamento code stampa disponibili
/// </summary>
private void refreshQueueAvail()
{
// svuoto
lbPrintQueue.Items.Clear();
// scarico TUTTI i report definiti
string url2call = $"{serverBaseAddr}/api/PrintQueueConf";
string rawData = callUrl(url2call);
if (!string.IsNullOrEmpty(rawData))
{
// deserializzo
listQueue = JsonConvert.DeserializeObject<List<queueConf>>(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();
}
/// <summary>
/// Aggiorna stato code
/// </summary>
private void refreshQueueStsatus()
{
// verifico ed aggiorno quantità coda
int numTot = 0;
string url2call = $"{serverBaseAddr}/api/PrintQueue";
string rawData = callUrl(url2call);
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)
{
// init report printer...
reportPrinter rPrint = new reportPrinter();
url2call = $"{serverBaseAddr}/api/PrintQueue/{coda.Key}";
rawData = callUrl(url2call);
if (!string.IsNullOrEmpty(rawData))
{
// deserializzo
List<reportData> report2print = JsonConvert.DeserializeObject<List<reportData>>(rawData);
if (report2print != null)
{
// aggiorno contatore...
coda.Value.NumWaiting = report2print.Count;
// verifico non ci sia veto print..
DateTime adesso = DateTime.Now;
if (vetoPrint < adesso)
{
vetoPrint = adesso.AddSeconds(30);
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 = 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)
{
// 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;
}
}
}
}
}
}
}
#endregion
}
}
+3
View File
@@ -126,4 +126,7 @@
<metadata name="uiTimer.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>242, 17</value>
</metadata>
<metadata name="longTimer.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>334, 17</value>
</metadata>
</root>
+1
View File
@@ -0,0 +1 @@

+1
View File
@@ -0,0 +1 @@

+148 -382
View File
@@ -1,99 +1,107 @@
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
{
/// <summary>
/// Classe che si occupa di stampare report da reportViewer via printer locale/remota
/// </summary>
public class reportPrinter
{
#region area codice da non modificare
/// <summary>
/// Directory di abse applicazione
/// </summary>
protected string baseDir;
/// <summary>
/// Path x salvataggio locale pdf
/// </summary>
protected string localPdfPath = "pdf";
/// <summary>
/// Classe reportprinter
/// </summary>
public reportPrinter()
{
baseDir = AppDomain.CurrentDomain.BaseDirectory;
localPdfPath = memLayer.ML.confReadString("localPdfPath");
}
#region metodi stampa effettiva report
/// <summary>
/// Indice pagina corrente x stampa ogni report
/// </summary>
private int m_currentPageIndex;
protected int logLevel = 0;
protected bool doPdfCopy = false;
/// <summary>
/// stream del report...
/// </summary>
private IList<Stream> m_streams;
/// <summary>
/// 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
/// </summary>
/// <param name="name"></param>
/// <param name="fileNameExtension"></param>
/// <param name="encoding"></param>
/// <param name="mimeType"></param>
/// <param name="willSeek"></param>
/// <returns></returns>
private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
/// <param name="reportTemplate">Nome report (file)</param>
/// <param name="rdsName">Nome report</param>
/// <param name="localReportPath">Cartella locale dei report</param>
/// <param name="printerName">nome completo stampante (rispetto al server)</param>
/// <param name="tabDati">tabella dati da caricare nel report</param>
/// <param name="deviceInfoParam">parametri "device input"</param>
/// <param name="doPdfCopy">effettua ANCHE copia pdf</param>
public bool printReport(string reportTemplate, 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;
}
/// <summary>
/// ciclo da fornire al renderizzatore dei report, per salvare 1 pdf da ogni pagina del report
/// </summary>
/// <param name="name"></param>
/// <param name="fileNameExtension"></param>
/// <param name="encoding"></param>
/// <param name="mimeType"></param>
/// <param name="willSeek"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Handler per PrintPageEvents
/// </summary>
/// <param name="sender"></param>
/// <param name="ev"></param>
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);
}
/// <summary>
/// funzione di stampa...
/// </summary>
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}\\{reportTemplate}";
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;
}
/// <summary>
/// esegue print vero e proprio
/// </summary>
/// <param name="printerName"></param>
/// <param name="report"></param>
/// <param name="deviceInfo"></param>
private void doEmfPrint(string printerName, LocalReport report, string deviceInfo)
{
// export in EMF
Export(report, deviceInfo);
m_currentPageIndex = 0;
// stampo
Print(printerName);
// pulizia files da area temp...
pulisciDir();
// do dispose?
Dispose();
}
/// <summary>
/// effettua stampa in PDF dei vari report in una cartella Anno/Mese/Giorno
/// </summary>
/// <param name="report"></param>
/// <param name="deviceInfo"></param>
private void doLocalPdfPrint(LocalReport report, string deviceInfo)
{
// export in PDF
ExportPDF(report, deviceInfo);
m_currentPageIndex = 0;
// do dispose?
Dispose();
}
/// <summary>
/// Export del report come EMF (Enhanced Metafile) file.
@@ -127,348 +135,106 @@ namespace LPA
foreach (Stream stream in m_streams)
stream.Close();
m_streams = null;
}
}
#endregion
#region area codice da modificare
/// <summary>
/// carica i dati richiesti dal report dalla StoredProcedure (filtrando quindi...)
/// </summary>
/// <param name="tipoReport"></param>
/// <param name="keyParam">cod UDC</param>
/// <returns>tabella dati</returns>
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;
}
}
/// <summary>
/// Crea un report locale da file rdlc, carica i dati, esporta report come EMF file e quindi lo invia alla stampante
/// ciclo da fornire al renderizzatore dei report, per salvare 1 immagine da ogni pagina del report
/// </summary>
/// <param name="tipoReport">report ammessi: ElencoMacchine / RichiestaIntervento</param>
/// <param name="printerName">nome completo stampante (rispetto al server)</param>
/// <param name="keyParam">cod UDC</param>
/// <param name="deviceInfoParam">parametri "device input"</param>
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);
}
}
/// <summary>
/// esegue print vero e proprio
/// </summary>
/// <param name="printerName"></param>
/// <param name="report"></param>
/// <param name="deviceInfo"></param>
private void doEmfPrint(string printerName, LocalReport report, string deviceInfo)
{
// export in EMF
Export(report, deviceInfo);
m_currentPageIndex = 0;
// stampo
Print(printerName);
// do dispose?
Dispose();
}
/// <summary>
/// effettua stampa in PDF dei vari report in una cartella Anno/Mese/Giorno
/// </summary>
/// <param name="report"></param>
/// <param name="deviceInfo"></param>
private void doLocalPdfPrint(LocalReport report, string deviceInfo)
{
// export in PDF
ExportPDF(report, deviceInfo);
m_currentPageIndex = 0;
// do dispose?
Dispose();
}
/// <summary>
/// effettua la stampa del cartellino indicato
/// </summary>
/// <param name="documento"></param>
/// <param name="keyParam"></param>
/// <param name="printerName">indirizzo di rete completo stampante del tipo \\nomePc\nomeStampante, oppure "" x default</param>
/// <param name="name"></param>
/// <param name="fileNameExtension"></param>
/// <param name="encoding"></param>
/// <param name="mimeType"></param>
/// <param name="willSeek"></param>
/// <returns></returns>
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 = $"{baseDir}{localPdfPath}\\temp\\{name}_{adesso:HHmmss}_{adesso:ffff}.{fileNameExtension}";
Stream stream = new FileStream(filePathName, FileMode.Create);
m_streams.Add(stream);
return stream;
}
/// <summary>
/// effettua la vera e propria fase di stampa
/// ciclo da fornire al renderizzatore dei report, per salvare 1 pdf da ogni pagina del report
/// </summary>
/// <param name="keyParam"></param>
/// <param name="printerName"></param>
/// <param name="answ"></param>
/// <param name="report"></param>
/// <param name="deviceInfo"></param>
/// <param name="name"></param>
/// <param name="fileNameExtension"></param>
/// <param name="encoding"></param>
/// <param name="mimeType"></param>
/// <param name="willSeek"></param>
/// <returns></returns>
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)
{
// compongo stringhe
DateTime adesso = DateTime.Now;
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(pdfPathName, FileMode.Create);
m_streams.Add(stream);
return stream;
}
/// <summary>
/// Handler per PrintPageEvents
/// </summary>
/// <param name="sender"></param>
/// <param name="ev"></param>
private void PrintPage(object sender, PrintPageEventArgs ev)
{
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;
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 e)
catch(Exception exc)
{
logger.lg.scriviLog(String.Format("Errore in fase di creazione e stampa report: stampante {0}, errore riscontrato {1}", printerName, e), tipoLog.EXCEPTION);
Log.Instance.Error(exc, "Errore in PrintPage");
}
return answ;
}
/// <summary>
/// oggetto protected
/// funzione di stampa...
/// </summary>
/// <param name="args"></param>
protected reportPrinter()
private void Print(string printerName)
{
logLevel = memLayer.ML.CRI("_logLevel");
doPdfCopy = memLayer.ML.CRB("doPdfCopy");
//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)
{
Log.Instance.Error($"Impostazioni non valide per la stampante {printerName}");
return;
}
printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
printDoc.Print();
}
/// <summary>
/// singleton pubblico
/// </summary>
public static reportPrinter obj = new reportPrinter();
/// <summary>
/// effettua pulizia della cartella temp x i files più vecchi di X ore (web.config)
/// </summary>
public void pulisciDir()
{
// num max ore di età x files "vecchi" da tenere in temp area...
int maxOre = memLayer.ML.CRI("maxAgeTempAreaHours");
int maxAgeMinutes = memLayer.ML.CRI("maxAgeTempArea");
int eliminati = 0;
// ottengo elenco files *.emf
fileMover.obj.setDirectory(@"~\temp\");
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.AddHours(-maxOre)) // elimino files vecchi...
if (_file.CreationTime < DateTime.Now.AddMinutes(-maxAgeMinutes)) // elimino files vecchi...
{
fatto = fileMover.obj.eliminaFile(_file);
if (fatto)
{
logger.lg.scriviLog(String.Format("Eliminato file {0}", _file.Name), tipoLog.INFO);
Log.Instance.Info($"Eliminato file {_file.Name}");
eliminati++;
}
}
@@ -476,7 +242,7 @@ namespace LPA
// 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.Info($"Eliminati {eliminati} files temporanei da area temp");
}
}