-
Notifications
You must be signed in to change notification settings - Fork 4
/
RockLabelPrinter.cs
446 lines (383 loc) · 17.1 KB
/
RockLabelPrinter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// <copyright>
// Copyright 2013 by the Spark Development Network
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Caching;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using Newtonsoft.Json;
namespace CheckinClient
{
/// <summary>
///
/// </summary>
[PermissionSet( SecurityAction.Demand, Name = "FullTrust" )]
public class RockLabelPrinter
{
ObjectCache cache;
bool warnedPrinterError = false;
/// <summary>
/// Initializes a new instance of the <see cref="RockCheckinScriptManager"/> class.
/// </summary>
/// <param name="p">The p.</param>
public RockLabelPrinter( )
{
cache = MemoryCache.Default;
}
#region V1 Printing Code
/// <summary>
/// Prints the labels.
/// </summary>
/// <param name="labelData">The label data.</param>
/// <param name="hasPrinterCutter">if set to <c>true</c> the printer has a cutter; false otherwise.</param>
public void PrintLabels( string labelData, bool hasPrinterCutter )
{
warnedPrinterError = false;
var labels = JsonConvert.DeserializeObject<List<LabelItem>>(labelData);
Dictionary<string, List<LabelItem>> labelsByAddress = SortLabelsByAddress(labels);
//For each printer
foreach ( string labelAddress in labelsByAddress.Keys )
{
StringBuilder labelContents = new StringBuilder();
int labelIndex = 0;
foreach ( LabelItem label in labelsByAddress[labelAddress] )
{
labelIndex++;
// get label file & merge fields
var content = MergeLabelFields( GetLabelContents( label.LabelFile ), label.MergeFields ).TrimEnd();
// If the "enable label cutting" feature is enabled, then we are going to
// control which mode the printer is in. In this case, we will remove any
// tear-mode (^MMT) commands from the content and add the cut-mode (^MMC).
if ( hasPrinterCutter )
{
content = content.Replace( "^MMT", string.Empty );
// Here we are forcing the printer into cut mode (because
// we don't know if it has been put into cut-mode already) even
// though we might be suppressing the cut below. This is correct.
content = ReplaceIfEndsWith( content, "^XZ", "^MMC^XZ" );
// If it's not the last label or a "ROCK_CUT" label, then inject
// a suppress back-feed (^XB) command which will also suppress the cut.
if ( ! ( labelIndex == labelsByAddress[labelAddress].Count || content.Contains( "ROCK_CUT" ) ) )
{
content = ReplaceIfEndsWith( content, "^XZ", "^XB^XZ" );
}
}
labelContents.Append( content );
}
// print label
PrintLabel( labelContents.ToString(), labelAddress );
}
//RawPrinterHelper.SendStringToPrinter( "ZDesigner GX420d (Copy 1)", s );
}
/// <summary>
/// Puts labels into a dictionary
/// </summary>
/// <param name="labels">List of label items.</param>
/// <returns></returns>
private Dictionary<string, List<LabelItem>> SortLabelsByAddress(List<LabelItem> labels)
{
Dictionary<string, List<LabelItem>> labelsByAddress = new Dictionary<string, List<LabelItem>>();
foreach(var label in labels)
{
if (!labelsByAddress.ContainsKey(label.PrinterAddress))
{
labelsByAddress[label.PrinterAddress] = new List<LabelItem>();
}
labelsByAddress[label.PrinterAddress].Add(label);
}
return labelsByAddress;
}
/// <summary>
/// Gets the label contents.
/// </summary>
/// <param name="labelFile">The label file.</param>
/// <returns></returns>
private string GetLabelContents( string labelFile )
{
string labelContents = string.Empty;
if ( cache.Contains( labelFile ) )
{
//get an item from the cache
labelContents = cache.Get( labelFile ).ToString();
}
else
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
// get label from site
using ( WebClient client = new WebClient() )
{
labelContents = client.DownloadString( labelFile );
}
var rockConfig = RockConfig.Load();
if ( rockConfig.IsCachingEnabled )
{
CacheItemPolicy cachePolicy = new CacheItemPolicy();
cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds( rockConfig.CacheLabelDuration );
//add an item to the cache
cache.Set( labelFile, labelContents, cachePolicy );
}
}
return labelContents;
}
/// <summary>
/// Merges the label fields.
/// </summary>
/// <param name="labelContents">The label contents.</param>
/// <param name="mergeFields">The merge fields.</param>
/// <returns></returns>
private string MergeLabelFields( string labelContents, Dictionary<string, string> mergeFields )
{
foreach ( var mergeField in mergeFields )
{
if ( !string.IsNullOrWhiteSpace( mergeField.Value ) )
{
labelContents = Regex.Replace( labelContents, string.Format( @"(?<=\^FD){0}(?=\^FS)", mergeField.Key ), mergeField.Value );
}
else
{
// Remove the box preceding merge field
labelContents = Regex.Replace( labelContents, string.Format( @"\^FO.*\^FS\s*(?=\^FT.*\^FD{0}\^FS)", mergeField.Key ), string.Empty );
// Remove the merge field
labelContents = Regex.Replace( labelContents, string.Format( @"\^FD{0}\^FS", mergeField.Key ), "^FD^FS" );
}
}
return labelContents;
}
/// <summary>
/// Prints the label.
/// </summary>
/// <param name="labelContents">The label contents.</param>
/// <param name="labelPrinterIp">The label printer ip.</param>
private void PrintLabel( string labelContents, string labelPrinterIp )
{
var rockConfig = RockConfig.Load();
// if IP override
if ( !string.IsNullOrEmpty(rockConfig.PrinterOverrideIp) )
{
PrintViaIp( labelContents, rockConfig.PrinterOverrideIp );
}
else if ( !string.IsNullOrEmpty(rockConfig.PrinterOverrideLocal) ) // if printer local
{
// For USB printing we need to conver ^CI28 to ^CI27 inside of the label.
// Per research from Lee Peterson
// ^CI27 sets a Zebra printer to expect the code page Windows-1252 data as generated by the Win/USB app rather than
// UTF -8 as expected with ^CI28, so extended characters print correctly.
var usbLabelContent = labelContents.Replace( "^CI28", "^CI27" );
RawPrinterHelper.SendStringToPrinter( rockConfig.PrinterOverrideLocal, usbLabelContent );
}
else if (!string.IsNullOrWhiteSpace(labelPrinterIp)) // else print to given IP
{
PrintViaIp( labelContents, labelPrinterIp );
} else {
MessageBox.Show( "No printer has been configured.", "Print Error", MessageBoxButton.OK, MessageBoxImage.Error );
}
}
/// <summary>
/// Prints the via ip.
/// </summary>
/// <param name="labelContents">The label contents.</param>
/// <param name="ipAddress">The ip address.</param>
private void PrintViaIp( string labelContents, string ipAddress )
{
try
{
if ( !warnedPrinterError )
{
int printerPort = 9100;
var printerIpAddress = ipAddress;
// If the user specified in 0.0.0.0:1234 syntax then pull our the IP and port numbers.
if ( printerIpAddress.Contains( ":" ) )
{
var segments = printerIpAddress.Split( ':' );
printerIpAddress = segments[0];
int.TryParse( segments[1], out printerPort );
}
var printerEndpoint = new IPEndPoint( IPAddress.Parse( printerIpAddress ), printerPort );
Socket socket = null;
socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
IAsyncResult result = socket.BeginConnect( printerEndpoint, null, null );
bool success = result.AsyncWaitHandle.WaitOne( 5000, true );
if ( socket.Connected )
{
var ns = new NetworkStream( socket );
byte[] toSend = System.Text.Encoding.UTF8.GetBytes( labelContents );
ns.Write( toSend, 0, toSend.Length );
}
else
{
MessageBox.Show( String.Format( "Could not connect to the printer {0}.", ipAddress ), "Print Error", MessageBoxButton.OK, MessageBoxImage.Error );
warnedPrinterError = true;
}
if ( socket != null && socket.Connected )
{
socket.Shutdown( SocketShutdown.Both );
socket.Close();
}
}
}
catch ( Exception ex )
{
MessageBox.Show( String.Format( "Could not connect to the printer {0}. The error was {1}.", ipAddress, ex.Message ), "Print Error", MessageBoxButton.OK, MessageBoxImage.Error );
}
}
/// <summary>
/// Replaces string found at the very end of the content.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="suffix">The suffix.</param>
/// <returns></returns>
public static string ReplaceIfEndsWith( string content, string suffix, string replacement )
{
if ( content.EndsWith( suffix ) )
{
return content.Substring( 0, content.Length - suffix.Length ) + replacement;
}
else
{
return content;
}
}
#endregion
#region V2 Printing Code
/// <summary>
/// Print the V2 labels from the JSON encoded list of labels.
/// </summary>
/// <param name="labelData">The JSON encoded list of labels.</param>
/// <returns>A list of error messages.</returns>
public async Task<List<string>> PrintV2Labels( string labelData )
{
var labels = JsonConvert.DeserializeObject<List<ClientLabelBag>>( labelData );
var errorMessages = new List<string>();
foreach ( var label in labels )
{
var data = Convert.FromBase64String( label.Data );
var message = await PrintLabelAsync( data, label.PrinterAddress );
if ( !string.IsNullOrWhiteSpace( message ) )
{
errorMessages.Add( message );
}
}
return errorMessages;
}
/// <summary>
/// Prints the label.
/// </summary>
/// <param name="labelContents">The label contents.</param>
/// <param name="labelPrinterIp">The label printer ip.</param>
private Task<string> PrintLabelAsync( byte[] labelContents, string labelPrinterIp )
{
var rockConfig = RockConfig.Load();
// if IP override
if ( !string.IsNullOrEmpty( rockConfig.PrinterOverrideIp ) )
{
return PrintViaIpAsync( labelContents, rockConfig.PrinterOverrideIp );
}
else if ( !string.IsNullOrEmpty( rockConfig.PrinterOverrideLocal ) ) // if printer local
{
var zpl = Encoding.UTF8.GetString( labelContents );
// For USB printing we need to conver ^CI28 to ^CI27 inside of the label.
// Per research from Lee Peterson
// ^CI27 sets a Zebra printer to expect the code page Windows-1252 data as generated by the Win/USB app rather than
// UTF -8 as expected with ^CI28, so extended characters print correctly.
zpl = zpl.Replace( "^CI28", "^CI27" );
RawPrinterHelper.SendStringToPrinter( rockConfig.PrinterOverrideLocal, zpl );
return Task.FromResult<string>( null );
}
else if ( !string.IsNullOrWhiteSpace( labelPrinterIp ) ) // else print to given IP
{
return PrintViaIpAsync( labelContents, labelPrinterIp );
}
else
{
return Task.FromResult( "No printer has been configured." );
}
}
/// <summary>
/// Prints the label via IP address.
/// </summary>
/// <param name="labelContents">The label contents.</param>
/// <param name="ipAddress">The ip address.</param>
/// <returns>A string that contains an error message if the label failed to print or <c>null</c> otherwise.</returns>
private async Task<string> PrintViaIpAsync( byte[] labelContents, string ipAddress )
{
try
{
int printerPort = 9100;
var printerIpAddress = ipAddress;
// If the user specified in 0.0.0.0:1234 syntax then pull our the IP and port numbers.
if ( printerIpAddress.Contains( ":" ) )
{
var segments = printerIpAddress.Split( ':' );
printerIpAddress = segments[0];
int.TryParse( segments[1], out printerPort );
}
var printerEndpoint = new IPEndPoint( IPAddress.Parse( printerIpAddress ), printerPort );
var socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
try
{
var connectTask = socket.ConnectAsync( printerEndpoint );
await Task.WhenAny( connectTask, Task.Delay( 5000 ) );
if ( socket.Connected )
{
using ( var ns = new NetworkStream( socket ) )
{
ns.Write( labelContents, 0, labelContents.Length );
}
return null;
}
else
{
return $"Could not connect to the printer {ipAddress}.";
}
}
finally
{
if ( socket != null && socket.Connected )
{
socket.Shutdown( SocketShutdown.Both );
socket.Close();
}
}
}
catch ( Exception ex )
{
return $"Could not connect to the printer {ipAddress}. The error was {ex.Message}.";
}
}
#endregion
}
/// <summary>
///
/// </summary>
public class LabelItem
{
public int? PrinterDeviceId { get; set; }
public string PrinterAddress { get; set; }
public string LabelFile { get; set; }
public Dictionary<string, string> MergeFields { get; set; }
}
class ClientLabelBag
{
public string PrinterAddress { get; set; }
public string Data { get; set; }
}
}