Skip to content

Commit

Permalink
Execute print in STAThread, this may solve the random freeze issue
Browse files Browse the repository at this point in the history
  • Loading branch information
xWTF committed Jan 12, 2023
1 parent 0070d9a commit 973cc6e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 24 deletions.
51 changes: 27 additions & 24 deletions SnipeIT-bPAC/ServerForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ namespace SnipeIT_bPAC
public partial class ServerForm : Form
{
public HttpListener? Listener;
public DocumentClass Document = new DocumentClass();

private bool StartMinimized = false;

Expand Down Expand Up @@ -127,6 +126,30 @@ private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs
UseShellExecute = true,
});

private void DoPrint(Dictionary<string, object>[] requests)
{
var document = new DocumentClass();
if (!document.Open(textBox_template.Text))
{
throw new Exception("Print error: Unable to open template");
}
document.StartPrint(requests.Length + " Labels", PrintOptionConstants.bpoDefault);
foreach (var r in requests)
{
foreach (var kv in r)
{
var obj = document.GetObject(kv.Key);
if (obj != null)
{
obj.Text = kv.Value.ToString();
}
}
document.PrintOut(1, PrintOptionConstants.bpoDefault);
}
document.EndPrint();
document.Close();
}

private void SaveSettings(object? sender = null, EventArgs? e = null) => Properties.Settings.Default.Save();

private void HandleRequest(HttpListenerContext ctx)
Expand Down Expand Up @@ -167,35 +190,15 @@ private void HandleRequest(HttpListenerContext ctx)

try
{
if (!Document.Open(Invoke(() => textBox_template.Text)))
{
Log("Print error: Unable to open template");
ctx.SendJson(new { code = 500, msg = "Unable to open template" });
return;
}

Document.StartPrint(requests.Length + " Labels", PrintOptionConstants.bpoDefault);
foreach (var r in requests)
{
foreach (var kv in r)
{
var obj = Document.GetObject(kv.Key);
if (obj != null)
{
obj.Text = kv.Value.ToString();
}
}
Document.PrintOut(1, PrintOptionConstants.bpoDefault);
}
Document.EndPrint();
Document.Close();
// Call the bPAC in STAThread
Invoke(() => DoPrint(requests));

Log("Printed " + requests.Length + " labels from " + req.RemoteEndPoint.ToString());
}
catch (Exception ex)
{
Log("Print error: " + ex);
ctx.SendJson(new { code = 500, msg = "Unknown error occured" });
ctx.SendJson(new { code = 500, msg = "Unknown error occured: " + ex.Message });
return;
}
ctx.SendJson(new { code = 200 });
Expand Down
1 change: 1 addition & 0 deletions SnipeIT-bPAC/SnipeIT-bPAC.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<Authors>xWTF</Authors>
<Description>Convenient bPAC print daemon for Snipe-IT asset management software</Description>
<Copyright>Copyright (c) 2023 xWTF</Copyright>
<Version>1.0.1</Version>
</PropertyGroup>

<ItemGroup>
Expand Down

0 comments on commit 973cc6e

Please sign in to comment.