forked from SparkDevNetwork/Rock-WindowsCheckin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RockLabelPrinter.cs
264 lines (231 loc) · 9.96 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
// <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.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using Newtonsoft.Json;
using System.Text;
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;
}
/// <summary>
/// Prints the labels.
/// </summary>
/// <param name="labelData">The label data.</param>
public void PrintLabels( string labelData )
{
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();
foreach (LabelItem label in labelsByAddress[labelAddress])
{
// get label file & merge fields
labelContents.Append(MergeLabelFields(GetLabelContents(label.LabelFile), label.MergeFields));
}
// 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>
///
/// </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; }
}
}