Net Framework2.0
C# 桥接模式(抽象和实现分开)
namespace Mes.Printing.Printers { /// <summary> /// Label Printer. /// </summary> public interface ILabelPrinter { /// <summary> /// Print label. /// </summary> /// <param name="labelContent">label content</param> /// <returns></returns> void BarCodePrint(string labelContent); } }
using System; namespace Mes.Printing.Printers { /// <summary> /// Base Printer Type. /// </summary> public abstract class BasePrinter : ILabelPrinter { #region Printer Name private string _PrinterName; /// <summary> /// Get or set printer name. /// </summary> public string PrinterName { get { return _PrinterName; } set { _PrinterName = value; } } #endregion #region Device Name private string _DeviceName; /// <summary> /// Get or set device name. /// </summary> public string DeviceName { get { return _DeviceName; } set { _DeviceName = value; } } #endregion #region SourcePath private string _SourcePath; public string SourcePath { get { return _SourcePath; } set { _SourcePath = value; } } #endregion #region Copies private int _Copies; public int Copies { get { return _Copies; } set { _Copies = value; } } #endregion #region Print /// <summary> /// Print label. /// </summary> /// <param name="labelContent">label content</param> /// <returns></returns> public void BarCodePrint(string labelContent) { if (Copies <= 0) throw new ArgumentOutOfRangeException("copies", "The number of copies must be greater than 0."); if (String.IsNullOrEmpty(PrinterName)) throw new ArgumentNullException("PrinterName"); //if (String.IsNullOrEmpty(DeviceName)) // throw new ArgumentNullException("DeviceName"); if (String.IsNullOrEmpty(SourcePath)) throw new ArgumentNullException("SourcePath"); if (String.IsNullOrEmpty(labelContent)) throw new ArgumentNullException("labelContent"); // Print Label PrintLabel(PrinterName, DeviceName, SourcePath, labelContent, Copies); } #endregion /// <summary> /// Print label. /// </summary> /// <param name="printerName">user selected printer name(when tcp print, tcp ip address)</param> /// <param name="targetPath">target path(when tcp print,tcp port)</param> /// <param name="SourcePath">label file path</param> /// <param name="labelContent">label content</param> /// <param name="copies">print label copies</param> /// <returns></returns> protected abstract void PrintLabel(string printerName, string targetPath, string SourcePath, string labelContent, int copies); } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Configuration; namespace Mes.Printing.Printers { /// <summary> /// Zebra Printer. /// </summary> public abstract class ZebraPrinter : BasePrinter { private int _IntervalTime; private int _IntervalDefaultTime = 0; public ZebraPrinter() { _IntervalTime = String.IsNullOrEmpty(GetSettingValue("IntervalTime")) ? _IntervalDefaultTime : Convert.ToInt32(GetSettingValue("IntervalTime")); } private string GetSettingValue(string settingKey) { if (String.IsNullOrEmpty(settingKey)) return null; string settingValue = ConfigurationManager.AppSettings[settingKey]; if (!String.IsNullOrEmpty(settingValue)) return settingValue; return null; } /// <summary> /// Send command data to printer. /// </summary> /// <param name="cmdData">Command Data</param> //protected abstract void Print(byte[] cmdData); /// <summary> /// Send command data to printer. /// </summary> /// <param name="labelContent">Zebra CodeSoft Lab Detail Content</param> protected abstract void Print(string labelContent); /// <summary> /// Print label. /// </summary> /// <param name="printerName">user selected printer name(when tcp print, tcp ip address)</param> /// <param name="targetPath">target path(when tcp print,tcp port)</param> /// <param name="SourcePath">label file path</param> /// <param name="labelContent">label content</param> /// <param name="copies">print label copies</param> /// <returns></returns> protected override void PrintLabel(string printerName, string targetPath, string SourcePath, string labelContent, int copies) { if (copies <= 0) return; // Send to Printer for (int i = 0; i < copies; i++) { Print(labelContent); if (_IntervalTime > 0) Thread.Sleep(_IntervalTime); } } } }
using System; using System.IO.Ports; using HeT.Logging; using System.Text; namespace Mes.Printing.Printers { /// <summary> /// Zebra Printer (Device Type is COM). /// </summary> public class ZebraPrinter_COM : ZebraPrinter { /// <summary> /// Send command data to printer. /// </summary> /// <param name="zplText">Zebra CodeSoft Lab Detail Content</param> protected override void Print(string zplText) { // Get Command Data byte[] cmdData = Encoding.Default.GetBytes(zplText); // Serial Port for Printer SerialPort printerPort = null; try { // Create Serial Port printerPort = new SerialPort(DeviceName, 9600, Parity.None, 8, StopBits.One); // Open Port printerPort.Open(); // Write Command Data to Printer printerPort.Write(cmdData, 0, cmdData.Length); } catch { LogService.Error(String.Format("{0}-{1}", "Printer_InvalidPrinter", DeviceName)); throw new Exception(String.Format("{0}-{1}", "Printer_InvalidPrinter", DeviceName)); } finally { // Close Printer if (printerPort != null && printerPort.IsOpen) { try { printerPort.Close(); } catch { } } // Release Resource if (printerPort != null) printerPort.Dispose(); } } } }
using System; using System.Runtime.InteropServices; using HeT.Logging; using System.Text; namespace Mes.Printing.Printers { /// <summary> /// Zebra Printer (Device Type is DRV). /// </summary> public class ZebraPrinter_DRV : ZebraPrinter { #region Functions of winspool.Drv /// <summary> /// The DocInfo structure describes a document that will be printed. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] private class DocInfo { /// <summary> /// A string that specifies the name of the document. /// </summary> [MarshalAs(UnmanagedType.LPStr)] public string DocName; /// <summary> /// A string that specifies the name of an output file. To print to a printer, set this to NULL. /// </summary> [MarshalAs(UnmanagedType.LPStr)] public string OutputFile; /// <summary> /// A string that identifies the type of data used to record the document. /// </summary> [MarshalAs(UnmanagedType.LPStr)] public string DataType; } /// <summary> /// The OpenPrinter function retrieves a handle to the specified printer or print server or other types of handles in the print subsystem. /// </summary> /// <param name="printerName">A pointer to a null-terminated string that specifies the name of the printer or print server, the printer object, the XcvMonitor, or the XcvPort.</param> /// <param name="pPrinter">A pointer to a variable that receives a handle (not thread safe) to the open printer or print server object.</param> /// <param name="pDefault">A pointer to a PRINTER_DEFAULTS structure. This value can be NULL.</param> /// <returns>If the function succeeds, the return value is true.</returns> [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] private static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string printerName, out IntPtr pPrinter, IntPtr pDefault); /// <summary> /// The ClosePrinter function closes the specified printer object. /// </summary> /// <param name="pPrinter">A handle to the printer object to be closed. This handle is returned by the OpenPrinter function.</param> /// <returns>If the function succeeds, the return value is true.</returns> [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] private static extern bool ClosePrinter(IntPtr pPrinter); /// <summary> /// The StartDocPrinter function notifies the print spooler that a document is to be spooled for printing. /// </summary> /// <param name="pPrinter">A handle to the printer. Use the OpenPrinter function to retrieve a printer handle.</param> /// <param name="level">The version of the structure to which pDocInfo points. This value must be 1.</param> /// <param name="pDocInfo">A pointer to a DocInfo structure that describes the document to print.</param> /// <returns>If the function succeeds, the return value is true.</returns> [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] private static extern bool StartDocPrinter(IntPtr pPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DocInfo pDocInfo); /// <summary> /// The EndDocPrinter function ends a print job for the specified printer. /// </summary> /// <param name="pPrinter">Handle to a printer for which the print job should be ended. Use the OpenPrinter function to retrieve a printer handle.</param> /// <returns>If the function succeeds, the return value is true.</returns> [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] private static extern bool EndDocPrinter(IntPtr pPrinter); /// <summary> /// The StartPagePrinter function notifies the spooler that a page is about to be printed on the specified printer. /// </summary> /// <param name="pPrinter">Handle to a printer. Use the OpenPrinter function to retrieve a printer handle.</param> /// <returns>If the function succeeds, the return value is true.</returns> [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] private static extern bool StartPagePrinter(IntPtr pPrinter); /// <summary> /// The EndPagePrinter function notifies the print spooler that the application is at the end of a page in a print job. /// </summary> /// <param name="pPrinter">Handle to a printer. Use the OpenPrinter function to retrieve a printer handle.</param> /// <returns>If the function succeeds, the return value is true.</returns> [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] private static extern bool EndPagePrinter(IntPtr pPrinter); /// <summary> /// The WritePrinter function notifies the print spooler that data should be written to the specified printer. /// </summary> /// <param name="pPrinter">Handle to a printer. Use the OpenPrinter function to retrieve a printer handle.</param> /// <param name="pBuf">A pointer to an array of bytes that contains the data that should be written to the printer.</param> /// <param name="cbBuf">The size, in bytes, of the array.</param> /// <param name="pcWritten">A value that receives the number of bytes of data that were written to the printer.</param> /// <returns>If the function succeeds, the return value is true.</returns> [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] private static extern bool WritePrinter(IntPtr pPrinter, IntPtr pBuf, Int32 cbBuf, out Int32 pcWritten); #endregion /// <summary> /// Send command data to printer. /// </summary> /// <param name="zplText">Zebra CodeSoft Lab Detail Content</param> protected override void Print(string zplText) { // Get Command Data byte[] cmdData = Encoding.Default.GetBytes(zplText); // Command Data Length int cbBuf = cmdData.Length; // A pointer to unmanaged memory IntPtr pBuf = IntPtr.Zero; try { // Allocate unmanaged memory for command data pBuf = Marshal.AllocCoTaskMem(cbBuf); // Copy command data to the unmamaged memory Marshal.Copy(cmdData, 0, pBuf, cbBuf); // Send RAW data to Printer SendBytesToPrinter(pBuf, cbBuf); } finally { // Release the unmamaged memory. if (pBuf != IntPtr.Zero) Marshal.FreeCoTaskMem(pBuf); } } /// <summary> /// Send bytes to printer. /// </summary> /// <param name="pBuf">A pointer to command data</param> /// <param name="cbBuf">Command data length</param> private void SendBytesToPrinter(IntPtr pBuf, Int32 cbBuf) { if (String.IsNullOrEmpty(PrinterName)) throw new InvalidOperationException("Printer Name Required."); Int32 pcWritten = 0; // A Pointer to Printer IntPtr pPrinter = IntPtr.Zero; // Doc Information DocInfo pDocInfo = new DocInfo() { DocName = ".NET RAW Document",//"Label", DataType = "RAW" }; // Status Flags bool _Opened = false; bool _DocStarted = false; bool _PageStarted = false; try { // Open Printer _Opened = OpenPrinter(PrinterName.Normalize(), out pPrinter, IntPtr.Zero); if (_Opened) { // Start a Document _DocStarted = StartDocPrinter(pPrinter, 1, pDocInfo); if (_DocStarted) { // Start Page _PageStarted = StartPagePrinter(pPrinter); // Write Data to Printer if (_PageStarted && !WritePrinter(pPrinter, pBuf, cbBuf, out pcWritten)) { LogService.Error(String.Format("{0}-{1}", "Printer_InvalidPrinter", PrinterName)); throw new Exception(String.Format("{0}-{1}", "Printer_InvalidPrinter", PrinterName)); } } } } finally { // End Page if (_PageStarted) EndPagePrinter(pPrinter); // End Document if (_DocStarted) EndDocPrinter(pPrinter); // Close Printer if (_Opened) ClosePrinter(pPrinter); } } } }
using Microsoft.Office.Interop.Excel; using System; using System.Collections.Generic; using System.Reflection; using Microsoft.CSharp; namespace Mes.Printing.Printers { /// <summary> /// Zebra Printer (Device Type is Excel). /// </summary> public class ZebraPrinter_Excel : ZebraPrinter { /// <summary> /// Send command data to printer. /// </summary> /// <param name="labelContent">Zebra CodeSoft Lab Detail Content</param> protected override void Print(string labelContent) { // Declare excel variables. Microsoft.Office.Interop.Excel.Application mExcel = null; Microsoft.Office.Interop.Excel.Workbook mWorkbook = null; Microsoft.Office.Interop.Excel.Worksheet mWorkSheet = null; List<string> excelVariablesNameList = new List<string>(); try { // Initialize Excel for print. InitializeExcel(mExcel, mWorkbook, mWorkSheet, excelVariablesNameList, SourcePath); // Print barcode by excel. PrintBarCodeByExcel(mExcel, mWorkbook, mWorkSheet, excelVariablesNameList, labelContent); } catch (Exception ex) { throw new Exception(ex.ToString()); } } private void InitializeExcel(Microsoft.Office.Interop.Excel.Application mExcel, Microsoft.Office.Interop.Excel.Workbook mWorkbook, Microsoft.Office.Interop.Excel.Worksheet mWorkSheet, List<string> excelVariablesNameList, string fileFullPath) { //if (!File.Exists(strLabelFilePath)) //{ // strResult = "Lable文件:" + strLabelFilePath + "不存在!"; // return strResult; //} #region Initialize Excel for print. mExcel = new Microsoft.Office.Interop.Excel.Application(); //mExcel.Visible = true; mWorkbook = mExcel.Application.Workbooks.Open(fileFullPath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); mWorkSheet = new Worksheet(); mWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)mWorkbook.Worksheets[1]; // Empty all variables in EXCEL. for (int i = 1; i <= mWorkbook.Names.Count; i++) { if (mWorkbook.Names.Item(i).Value.ToString().ToUpper().IndexOf("!#REF!") < 0 && mWorkbook.Names.Item(i).Name.ToString().ToUpper().IndexOf("PALLET SHEET") < 0 && mWorkbook.Names.Item(i).Name.ToString().ToUpper().IndexOf("PRINT_TITLES") < 0 && mWorkbook.Names.Item(i).Name.ToString().ToUpper().IndexOf("PRINT_AREA") < 0) { excelVariablesNameList.Add(mWorkbook.Names.Item(i).Name.ToUpper().Trim()); Microsoft.Office.Interop.Excel.Range MyRange = mExcel.get_Range(mWorkbook.Names.Item(i).Name, Type.Missing); MyRange.Value2 = ""; } } #endregion } public void PrintBarCodeByExcel(Microsoft.Office.Interop.Excel.Application mExcel, Microsoft.Office.Interop.Excel.Workbook mWorkbook, Microsoft.Office.Interop.Excel.Worksheet mWorkSheet, List<string> excelVariablesNameList, string labelContent) { // Input is an array of strings, each member's format-》a:b:c:d; string strResult = string.Empty; string subTitle, mainTitle, labelVariableName, labelVariableValue; string[] labelContentArr = labelContent.Split(';'); foreach (string strTemp in labelContentArr) { mainTitle = (strTemp.Split(':'))[0];//row["recordtype"].ToString(); switch (mainTitle) { case "TEMPFILENAME": continue; case "DETAIL": subTitle = (strTemp.Split(':'))[1]; // Begin fill value. if (subTitle == "BEGIN") continue; if (subTitle == "END") { //print label. mWorkbook.PrintOut(Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); strResult = "OK"; } else { // Fill value. labelVariableName = (strTemp.Split(':'))[2].Replace("@", ""); // In the old way, no * sign is needed. //labelVariableValue = "*"+(strTemp.Split(':'))[3]+"*"; if (strTemp.Split(':').Length > 4) { //labelVariableValue = (strTemp.Split(':'))[3] + ":" + (strTemp.Split(':'))[4]; string v_Value_temp = strTemp; int iIndex = 0; iIndex = v_Value_temp.IndexOf(":"); v_Value_temp = v_Value_temp.Substring(iIndex + 1); iIndex = v_Value_temp.IndexOf(":"); v_Value_temp = v_Value_temp.Substring(iIndex + 1); iIndex = v_Value_temp.IndexOf(":"); v_Value_temp = v_Value_temp.Substring(iIndex + 1); labelVariableValue = v_Value_temp; } else { labelVariableValue = (strTemp.Split(':'))[3]; } if (excelVariablesNameList.Contains(labelVariableName.ToUpper().Trim())) { Microsoft.Office.Interop.Excel.Range MyRange = mExcel.get_Range(labelVariableName, Type.Missing); MyRange.Value2 = labelVariableValue; } } continue; } } } } }
using HeT.Logging; using LabelManager2; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Security.Cryptography; using System.Threading; namespace Mes.Printing.Printers { /// <summary> /// Zebra Printer (Device Type is LabelManager2). /// </summary> public class ZebraPrinter_LabelManager2 : ZebraPrinter { private double _PrintBreakTime; private double _PrintBreakDefaultTime = 2; #region Single Instance /// <summary> /// Print break monitor timer. /// </summary> private Timer _PrintBreakMonitorTimer; /// <summary> /// Constructor. /// </summary> public ZebraPrinter_LabelManager2() { _PrintBreakTime = String.IsNullOrEmpty(GetSettingValue("PrintBreakTime")) ? _PrintBreakDefaultTime : Convert.ToDouble(GetSettingValue("PrintBreakTime")); _PrintBreakMonitorTimer = new Timer(PrintBreakMonitorTimerCallback, null, 0, 1000); } private string GetSettingValue(string settingKey) { if (String.IsNullOrEmpty(settingKey)) return null; string settingValue = ConfigurationManager.AppSettings[settingKey]; if (!String.IsNullOrEmpty(settingValue)) return settingValue; return null; } /// <summary> /// instance. /// </summary> private static ZebraPrinter_LabelManager2 _Instance; /// <summary> /// instance sync object. /// </summary> private static readonly object instanceSyncRoot = new object(); /// <summary> /// Get ZebraPrinter_LabelManager2 instance. /// </summary> public static ZebraPrinter_LabelManager2 Instance { get { if (_Instance == null) { lock (instanceSyncRoot) { if (_Instance == null) InitializeInstance(); } } return _Instance; } } /// <summary> /// Initialize Instance. /// </summary> public static void InitializeInstance() { _Instance = new ZebraPrinter_LabelManager2(); } #endregion #region PrintBreakMonitorTimerCallback private readonly object monitorSyncRoot = new object(); /// <summary> /// Print break monitor timer call back. /// </summary> /// <param name="state"></param> private void PrintBreakMonitorTimerCallback(object state) { if (!System.Threading.Monitor.TryEnter(monitorSyncRoot)) return; if (isPrintingActive) return; try { if (lblApp == null) return; // When last print time break more than 2 minutes, force close labelmanagers. //if (printTimeLast.AddMinutes(2) <= System.DateTime.Now) if (printTimeLast.AddMinutes(_PrintBreakTime) <= System.DateTime.Now) { if (lblApp != null) { // Force close all documents. if (lblApp.Documents != null) lblApp.Documents.CloseAll(); // Force quit labelmanager2. lblApp.Quit(); } // Reset labelmanager2 and documents. lblApp = null; lblDoc = null; // Garbage Recycling, Cleaning Memory. GC.Collect(0); } } catch (Exception ex) { LogService.Error("PrintBreakMonitorTimerCallback error."); LogService.Error(ex.ToString()); } finally { System.Threading.Monitor.Exit(monitorSyncRoot); } } #endregion #region Print // Label manager2 application class. private LabelManager2.ApplicationClass lblApp = null; // Document. private Document lblDoc = null; // Last file hash code. private string labelFileHashCodeLast = String.Empty; // Last file full path. private string labelFilePathLast = String.Empty; // Last print time. private System.DateTime printTimeLast = System.DateTime.Now; // is printing now private bool isPrintingActive = false; // Print sync root object. private readonly object printSyncRoot = new object(); /// <summary> /// Send command data to printer. /// </summary> /// <param name="labelContent">Zebra CodeSoft Lab Detail Content</param> protected override void Print(string labelContent) { // 1. Add a reference to Lppx 2.tlb in the project // (this Lppx 2.tlb depends on the version of codesoft, // under 6 is the installation directory, under 7 is C: Program Files (x86) Tki 7 Common or C: Program Files Tki 7 Common). // 2. After adding a reference, find LabelManager2 under the project reference // and change the embedded interoperability type in its attribute to False, otherwise the operation will be wrong. // 3. Code Start lock (printSyncRoot) { isPrintingActive = true; try { string labelFileHashCodeCurr = GetFileHashcode(SourcePath); if (lblApp == null) { // Initialize label manager2 for print lab file. lblApp = new ApplicationClass(); lblApp.Documents.Open(SourcePath); lblDoc = lblApp.ActiveDocument; } // Validate file path change or file hash code change. if (labelFilePathLast != SourcePath || labelFileHashCodeLast != labelFileHashCodeCurr) { if (lblApp != null) { // Force close all documents. if (lblApp.Documents != null) lblApp.Documents.CloseAll(); // Force quit labelmanager2. lblApp.Quit(); } // Reset labelmanager2 and documents. lblApp = null; lblDoc = null; // Garbage Recycling, Cleaning Memory. GC.Collect(0); // Initialize label manager2 for print lab file. lblApp = new ApplicationClass(); lblApp.Documents.Open(SourcePath); lblDoc = lblApp.ActiveDocument; } List<string> labelVariablesNameList = new List<string>(); for (int i = 1; i <= lblDoc.Variables.FormVariables.Count; i++) { labelVariablesNameList.Add(lblDoc.Variables.FormVariables.Item(i).Name.ToUpper().Trim()); lblDoc.Variables.FormVariables.Item(lblDoc.Variables.FormVariables.Item(i).Name).Value = String.Empty; } #region Label Content Example //EG:strResult = print.PrintSSNLabel(pstrssn, pstrskuno, pstrwo, pstrtaskcode, functioncode); // return content like below: //TEMPFILENAME:\10880007961_SN_ELUX_45X15.LAB::; //DETAIL:BEGIN::; //DETAIL::APP_TYPE:EUI17D40HA; //DETAIL::BOARD_CODE:A06010931 / A; //DETAIL::BOOT_VER:BAA.G013; //DETAIL::DATE_YY / MM / DD:19 / 08 / 27; //DETAIL::FW_VER:UDA0L204; //DETAIL::PSOC_VER:CDA0L003; //DETAIL::SN:166326081901006; //DETAIL:END:: #endregion #region Prepare form variables for document. string mainTitle, subTitle, labelVariableName, labelVariableValue; string prepareFormVariableResult = "FAIL"; string[] labelContentArr = labelContent.Split(';'); if (labelContentArr.Length <= 0) throw new ArgumentNullException("labelContentArr"); #region Parse labelcontent arr. foreach (string strTemp in labelContentArr) { mainTitle = (strTemp.Split(':'))[0]; switch (mainTitle) { case "TEMPFILENAME": continue; case "DETAIL": subTitle = (strTemp.Split(':'))[1]; switch (subTitle) { case "BEGIN": continue; case "END": prepareFormVariableResult = "OK"; break; default: // Fill value. labelVariableName = (strTemp.Split(':'))[2].Replace("@", ""); if (strTemp.Split(':').Length > 4) { string v_Value_temp = strTemp; int iIndex = 0; iIndex = v_Value_temp.IndexOf(":"); v_Value_temp = v_Value_temp.Substring(iIndex + 1); iIndex = v_Value_temp.IndexOf(":"); v_Value_temp = v_Value_temp.Substring(iIndex + 1); iIndex = v_Value_temp.IndexOf(":"); v_Value_temp = v_Value_temp.Substring(iIndex + 1); labelVariableValue = v_Value_temp; } else { labelVariableValue = (strTemp.Split(':'))[3]; } if (labelVariablesNameList.Contains(labelVariableName.ToUpper())) lblDoc.Variables.FormVariables.Item(labelVariableName).Value = labelVariableValue; break; } continue; default: break; } } #endregion #endregion // Print label. if (prepareFormVariableResult == "OK") lblDoc.PrintDocument(Copies); // Record label file full path, label file hash code and print time. labelFileHashCodeLast = labelFileHashCodeCurr; labelFilePathLast = SourcePath; printTimeLast = System.DateTime.Now; } catch (Exception ex) { LogService.Error(ex.Message.ToString()); throw new Exception(ex.Message.ToString()); } finally { isPrintingActive = false; } } } /// <summary> /// Get file hash code. /// </summary> /// <param name="filePath">file full path</param> /// <returns></returns> private string GetFileHashcode(string filePath) { string hashValue = String.Empty; try { using (HashAlgorithm hash = HashAlgorithm.Create()) { using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { // Hash algorithm obtains byte array of hash code from text byte[] hashByte = hash.ComputeHash(file); // Replace byte assembly with string hashValue = BitConverter.ToString(hashByte); } } } catch (Exception ex) { LogService.Info("GetFileHashcode Error:" + ex.Message + filePath); return String.Empty; } return hashValue; } #endregion } }
using Microsoft.Win32.SafeHandles; using System; using System.IO; using System.Runtime.InteropServices; using HeT.Logging; using System.Text; using System.Diagnostics; namespace Mes.Printing.Printers { /// <summary> /// Zebra Printer (Device Type is LPT). /// </summary> public class ZebraPrinter_LPT : ZebraPrinter { #region Functions of kernal32.dll private const short INVALID_HANDLE_VALUE = -1; private const uint GENERIC_READ = 0x80000000; private const uint GENERIC_WRITE = 0x40000000; private const uint OPEN_EXISTING = 3; /// <summary> /// Creates or opens a file or I/O device. /// </summary> /// <param name="strFileName">The name of the file or device to be created or opened</param> /// <param name="dwDesiredAccess">The requested access to the file or device, which can be summarized as read, write, both or neither zero.</param> /// <param name="dwShareMode">The requested sharing mode of the file or device, which can be read, write, both, delete, all of these, or none (refer to the following table)</param> /// <param name="intptrSecurityAttributes">A pointer to a SECURITY_ATTRIBUTES structure that contains two separate but related data members: an optional security descriptor, and a Boolean value that determines whether the returned handle can be inherited by child processes.</param> /// <param name="dwCreationDisposition">An action to take on a file or device that exists or does not exist.</param> /// <param name="dwFlagsAndAttributes">The file or device attributes and flags.</param> /// <param name="intptrTemplateFile">A valid handle to a template file with the GENERIC_READ access right.</param> /// <returns>If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot.</returns> [DllImport("kernel32.dll")] private static extern SafeFileHandle CreateFile( string strFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr intptrSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr intptrTemplateFile ); #endregion /// <summary> /// Send command data to printer. /// </summary> /// <param name="zplText">Zebra CodeSoft Lab Detail Content</param> protected override void Print(string zplText) { // Get Command Data byte[] cmdData = Encoding.Default.GetBytes(zplText); #region Flex LPT print model // Open Printer //using (SafeFileHandle printerHandler = CreateFile(PrinterName, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero)) //{ // if (printerHandler.IsInvalid) // { // LogService.Error(String.Format("{0}-{1}", "Printer_InvalidPrinter", PrinterName)); // throw new Exception(String.Format("{0}-{1}", "Printer_InvalidPrinter", PrinterName)); // } // // Output Stream for Printer // FileStream oStream = null; // try // { // // Create Output Stream // oStream = new FileStream(printerHandler, FileAccess.ReadWrite); // // Write Command Data to Printer // oStream.Write(cmdData, 0, cmdData.Length); // } // catch // { // LogService.Error(String.Format("{0}-{1}", "Printer_InvalidPrinter", PrinterName)); // throw new Exception(String.Format("{0}-{1}", "Printer_InvalidPrinter", PrinterName)); // } // finally // { // if (oStream != null) // oStream.Dispose(); // oStream = null; // } //} #endregion #region Het LPT print model CreateZPLFile(zplText); string strcmd = "type c:\\SCANLOG\\temp.prn > " + DeviceName; ExecuteDosCommand(strcmd, 100); #endregion } /// <summary> /// Create ZPL format LABEL document and store it in C: SCANLOG directory. /// </summary> /// <param name="Strlabelcode"></param> private void CreateZPLFile(string Strlabelcode) { string filePath = @"C:\SCANLOG\"; string fileName = "temp.prn"; // Create a catalogue if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath); if (System.IO.File.Exists(filePath + fileName)) System.IO.File.Delete(filePath + fileName); FileStream fs = new FileStream(filePath + fileName, FileMode.CreateNew); StreamWriter sw = new StreamWriter(fs, Encoding.Default); sw.Write(Strlabelcode + "\r\n"); sw.Close(); fs.Close(); } /// <summary> /// Execute dos command. /// </summary> /// <param name="dosCommand">dosCommand</param> /// <param name="milliseconds">Waiting for command execution time (in milliseconds), if set to 0, then unlimited waiting</param> /// <returns>Returns the output, and if an exception occurs, returns an empty string</returns> public string ExecuteDosCommand(string dosCommand, int milliseconds) { // Output string. string output = String.Empty; if (!String.IsNullOrEmpty(dosCommand)) { // Create process objects. Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); // Set commands to be executed. startInfo.FileName = "cmd.exe"; // Set parameters, where "/C" means exit immediately after execution of the command. startInfo.Arguments = "/C " + dosCommand; // Start without System Shell. startInfo.UseShellExecute = false; // Unredirected input. startInfo.RedirectStandardInput = false; // Redirected output. startInfo.RedirectStandardOutput = true; // Do not create windows. startInfo.CreateNoWindow = true; process.StartInfo = startInfo; try { // Start the process if (process.Start()) { if (milliseconds == 0) process.WaitForExit();// There is no limit to waiting for the process to end. else process.WaitForExit(milliseconds);// Here, wait for the process to end, waiting for the specified milliseconds // Output of read process. output = process.StandardOutput.ReadToEnd(); } } catch (Exception ex) { LogService.Error(ex.Message.ToString()); } finally { if (process != null) process.Close(); } } return output; } } }