Beispiel #1
0
        public void GetPrintJob_ICardPrintingGetPrintJobSuccess_ReturnsValidPrintJob()
        {
            // Arrange
            var printer = Substitute.For <IPrinter>();

            var token = new Token {
                DeviceID = "DeviceId", Session = "Session", Workstation = "Workstation"
            };
            // TODO: PrinterInfo need to be built from information from IPrinter
            var printerInfo = new PrinterInfo();

            var printingWebService = Substitute.For <ICardPrinting>();

            printingWebService.GetPrintJob(token, printerInfo).Returns(new Response <PrintJob>
            {
                AdditionalInfo = "Call was successful",
                Session        = "SessionString",
                Success        = true,
                Value          = new PrintJob()
            });

            var cardPrintLogic = new CardPrintingLogic(printingWebService, printer);

            // Act
            string    additionalInfo;
            IPrintJob printJob = null;
            var       success  = cardPrintLogic.GetPrintJob(token, out printJob, out additionalInfo);

            // Assert
            printingWebService.Received().GetPrintJob(token, printerInfo);
            success.Should().BeTrue(because: "The call to ICardPrinting returns success as true. Which should mean the calling method is successful");
            printJob.Should().NotBeNull(because: "Successful call to ICardPrinting should return a PrintJob object returned in output argument");
        }
Beispiel #2
0
        public void GetPrintJob_ICardPrintingGetPrintJobUnsuccessful_ReturnPrintJobObject()
        {
            // Arrange
            var printingWebService = Substitute.For <ICardPrinting>();

            printingWebService.GetPrintJob(new Token(), new PrinterInfo()).ReturnsForAnyArgs(new Response <PrintJob>
            {
                AdditionalInfo = "Call was not successful",
                Session        = "SessionString",
                Success        = false,
                Value          = new PrintJob()
            });

            var printer = Substitute.For <IPrinter>();

            var cardPrintLogic = new CardPrintingLogic(printingWebService, printer);
            var token          = new Token();
            var printerInfo    = new PrinterInfo();

            // Act
            string    additionalInfo;
            IPrintJob printJob = null;
            var       success  = cardPrintLogic.GetPrintJob(token, out printJob, out additionalInfo);

            // Assert
            success.Should().BeFalse(because: "The call to ICardPrinting returns success as false. Which should mean the calling method is unsuccessful");
            printJob.Should().BeNull(because: "UnSuccessful call to ICardPrinting. Calling method should return a null PrintJob in output argument");
        }
Beispiel #3
0
        public bool GetPrintJob(Token token, out IPrintJob printJob, out string additionalInfo)
        {
            OnUiUpdate(CardPrintingLogicResource.FetchPrintJobUi, false, true, EventArgs.Empty);

            printJob = null;

            PrinterInfo printerInfo = new PrinterInfo
            {
                FirmwareVersion = _printer.FirmwareVersion,
                Manufacturer    = _printer.Manufacturer,
                Model           = _printer.Model,
                SerialNo        = _printer.DeviceId
            };


            var printJobResp = _cardPrinting.GetPrintJob(token, printerInfo);

            if (printJobResp.Success)
            {
                printJob = printJobResp.Value;
            }

            additionalInfo = printJobResp.AdditionalInfo;

            return(printJobResp.Success);
        }
 public PrintWorkerArguments(IPrintJob printJob, Engine engine, LabelFormatDocument orderFormat, LabelFormatDocument programFormat, LabelFormatDocument serviceTagFormat)
 {
     this.orderFormat      = orderFormat;
     this.programFormat    = programFormat;
     this.serviceTagFormat = serviceTagFormat;
     PrintJob = printJob;
     Engine   = engine;
 }
 public PrintWorkerArguments(IPrintJob printJob, Engine engine, LabelFormatDocument orderFormat, LabelFormatDocument programFormat, LabelFormatDocument serviceTagFormat)
 {
     this.orderFormat = orderFormat;
     this.programFormat = programFormat;
     this.serviceTagFormat = serviceTagFormat;
     PrintJob = printJob;
     Engine = engine;
 }
Beispiel #6
0
        public bool SetPrinterSetting(IPrintJob printJob, out string additionalInfo)
        {
            OnUiUpdate(CardPrintingLogicResource.PrinterOptionsUi, false, true, EventArgs.Empty);

            _printer.SetDeviceSettings(printJob.AppOptionToDictionary());

            additionalInfo = string.Empty;
            return(true);
        }
Beispiel #7
0
 /// <summary>
 /// This is the event handler for clicks on the 'Cancel print job' button.
 /// </summary>
 private void CancelPrintJob_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         IPrintJob job = (IPrintJob)PrintJobListBox.SelectedItem;
         job.RequestCancel();
     }
     catch (Exception exception)
     {
         rootPage.NotifyUser("Caught an exception: " + exception.Message, NotifyType.ErrorMessage);
     }
 }
        private void CreatePrintJobItem(IPrintJob printJob)
        {
            var formatItem = new ListViewItem(printJob.LabelFormatType)
            {
                Checked = true,
                Group   = printJob.SeriesNo == 0 ? null : printJobListView.Groups[printJob.SeriesId]
            };

            formatItem.SubItems.Add(printJob.LabelQuantity.ToString());
            formatItem.SubItems.Add(printJob.AdditionalInfo);
            formatItem.SubItems.Add(printJob.PrinterName);

            printJobListView.Items.Add(formatItem);
        }
Beispiel #9
0
        public bool StartPhysicalPrint(IPrintJob printJob, out CardData cardData, out string additionalInfo)
        {
            OnUiUpdate(CardPrintingLogicResource.BuildPrinterJobUi, false, true, EventArgs.Empty);

            cardData       = null;
            additionalInfo = string.Empty;

            var cardPrintDetails = _printer.PrinterDetailFactory().Populate(printJob.ProductFields);
            int printJobSuccess;

            Device.IDeviceMagData magData = null;

            if (printJob.MustReturnCardData)
            {
                printJobSuccess = _printer.ReadAndPrint(printJob.ProductBin, cardPrintDetails, out magData);
            }
            else
            {
                printJobSuccess = _printer.Print(printJob.ProductBin, cardPrintDetails);
            }

            if (printJobSuccess == PrinterCodes.Success && magData != null)
            {
                var track2 = magData.TrackDataToString(2);
                var sepPos = track2.IndexOfAny(new char[] { '=', 'D' });

                string ecryptedPAN = EncryptionManager.EncryptString(track2.Substring(0, sepPos),
                                                                     Veneka.Indigo.Common.Utilities.StaticFields.USE_HASHING_FOR_ENCRYPTION,
                                                                     Veneka.Indigo.Common.Utilities.StaticFields.EXTERNAL_SECURITY_KEY);
                cardData = new CardData
                {
                    Track2 = track2,
                    PAN    = ecryptedPAN
                };
            }
            ;

            if (printJobSuccess == PrinterCodes.ProductBinAndCardMismatch)
            {
                additionalInfo = "Card Product BIN does not match BIN on card used for printing";
            }
            else if (printJobSuccess == PrinterCodes.PrintJobCancelled)
            {
                additionalInfo = "Card Jammed in Printer while printing.";
            }

            return(printJobSuccess.Equals(PrinterCodes.Success));
        }
Beispiel #10
0
 /// <summary>
 /// This method is invoked when a print job is selected on the UI.
 /// Displays the details of the selected print job.
 /// </summary>
 private void PrintJob_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     try
     {
         // Display details of the selected print job.
         IPrintJob job = (IPrintJob)PrintJobListBox.SelectedItem;
         if (job != null)
         {
             PrintJobDetails.Text =
                 "Details of print job: " + job.Name + "\r\n" +
                 "Pages printed: " + job.PrintedPages + "/" + job.TotalPages + "\r\n" +
                 "Submission time: " + job.SubmissionTime + "\r\n" +
                 "Job status: " + DisplayablePrintJobStatus.ToString(job.Status);
         }
         else
         {
             PrintJobDetails.Text = "Please select a print job";
         }
     }
     catch (Exception exception)
     {
         rootPage.NotifyUser("Caught an exception: " + exception.Message, NotifyType.ErrorMessage);
     }
 }
Beispiel #11
0
        public async Task <object> PrintLabels(dynamic jobDetails)
        {
            Debug.WriteLine("NodeDymoLibrary: PrintLabels() called");
            // Debug.WriteLine(jobDetails.printer);
            //
            // Make sure the required parts exist
            if (!PropertyExists(jobDetails, "printer"))
            {
                Debug.WriteLine("NodeDymoLibrary: No `printer` parameter");
                throw new System.ArgumentException("'printer' parameter must be defined", "original");
            }
            else if (!PropertyExists(jobDetails, "labels"))
            {
                Debug.WriteLine("NodeDymoLibrary: No `labels` parameter");
                throw new System.ArgumentException("'labels' parameter must be defined", "original");
            }
            else
            {
                Debug.WriteLine("NodeDymoLibrary: Required base parameters defined");
                //Debug.WriteLine(jobDetails.printer);
            }

            //
            // Setup the printer and this job
            //ILabelWriterPrinter printer = Framework.GetLabelWriterPrinters()[(String)jobDetails.printer] as ILabelWriterPrinter;
            IPrinter printer;

            try
            {
                printer = Framework.GetPrinters()[jobDetails.printer] as IPrinter;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("NodeDymoLibrary: unable to find printer");
                throw ex;
            }

            //
            // Set some settings for this printing
            ILabelWriterPrintParams printParams = new LabelWriterPrintParams();

            printParams.PrintQuality = LabelWriterPrintQuality.BarcodeAndGraphics;
            printParams.JobTitle     = "Dymo Labels";
            printParams.Copies       = (int)1;
            if (PropertyExists(jobDetails, "jobTitle"))
            {
                Debug.WriteLine("NodeDymoLibrary Adding Print Job Title: " + (string)jobDetails.jobTitle);
                printParams.JobTitle = (string)jobDetails.jobTitle;
            }
            if (PropertyExists(jobDetails, "copies"))
            {
                Debug.WriteLine("NodeDymoLibrary Adding Print Copies: " + (string)jobDetails.copies);
                printParams.Copies = (int)jobDetails.copies;
            }
            // Set some settings for this printing
            //

            IPrintJob printJob = printer.CreatePrintJob(printParams);

            Debug.WriteLine("NodeDymoLibrary Print Job Created");

            //
            // Lets loop over these labels
            IDictionary <string, ILabel> label = new Dictionary <string, ILabel>();

            object[] suppliedLabels = (object[])jobDetails.labels;// Cast JS array as Object (no keys)
            foreach (IDictionary <string, object> thisLabel in suppliedLabels)
            {
                var i = label.Count.ToString();
                if (!thisLabel.ContainsKey("filename"))
                {
                    Debug.WriteLine("Dymo.cs No `labels`[x].`filename` parameter");
                    throw new System.ArgumentException("'labels'.'filename' parameter must be defined for each label", "original");
                }
//                if (!File.Exists((string)thisLabel["filename"]))
//                {
//                    Debug.WriteLine("Dymo.cs Unable to find label filename: " + (string)thisLabel["filename"]);
//                    throw new System.ArgumentException("'labels'.'filename' parameter must point to an existing file", "original");
//                }

                Debug.WriteLine("NodeDymoLibrary Adding label: " + (string)thisLabel["filename"]);
                try
                {
                    label[i] = Label.Open((string)thisLabel["filename"]);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                if (thisLabel.ContainsKey("fields"))
                {
                    Debug.WriteLine("NodeDymoLibrary Setting Field Values");
                    IDictionary <string, object> fields = (IDictionary <string, object>)thisLabel["fields"];
                    foreach (var kv in fields)
                    {
                        try
                        {
                            var k   = kv.Key.ToUpper();
                            var obj = label[i].GetObjectByName(k);
                            if (obj != null)
                            {
                                var v = kv.Value.ToString();
                                label[i].SetObjectText(k, v);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }

                if (thisLabel.ContainsKey("images"))
                {
                    Debug.WriteLine("NodeDymoLibrary Setting Image Values");
                    IDictionary <string, object> images = (IDictionary <string, object>)thisLabel["images"];
                    foreach (var kv in images)
                    {
                        try
                        {
                            var k   = kv.Key.ToUpper();
                            var obj = label[i].GetObjectByName(k);
                            if (obj != null)
                            {
                                var v = kv.Value;
                                label[i].SetImagePngData(k, new MemoryStream((byte[])v));
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }


                Debug.WriteLine("NodeDymoLibrary Add Label to print job");
                printJob.AddLabel(label[i]);
            }


            Debug.WriteLine("NodeDymoLibrary Lets Print the Label/s");
            try
            {
                printJob.Print();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            Debug.WriteLine("NodeDymoLibrary Label/s Printed");
            return(true);
        }
Beispiel #12
0
        public static void Main()
        {
            string url         = "https://dotnetbrowser-support.teamdev.com/docs/guides/gs/printing.html";
            string pdfFilePath = Path.GetFullPath("result.pdf");

            uint viewWidth   = 1024;
            uint viewHeight  = 768;
            Size browserSize = new Size(viewWidth, viewHeight);

            try
            {
                using (IEngine engine = EngineFactory.Create(new EngineOptions.Builder
                {
                    RenderingMode = RenderingMode.OffScreen,
                    GpuDisabled = true
                }.Build()))
                {
                    Console.WriteLine("Engine created");

                    using (IBrowser browser = engine.CreateBrowser())
                    {
                        Console.WriteLine("Browser created");
                        // 1. Resize browser to the required dimension.
                        browser.Size = browserSize;

                        // 2. Load the required web page and wait until it is loaded completely.
                        Console.WriteLine("Loading " + url);
                        browser.Navigation.LoadUrl(url).Wait();


                        // 3. Configure print handlers.
                        browser.RequestPrintHandler =
                            new Handler <RequestPrintParameters, RequestPrintResponse>(p =>
                        {
                            return(RequestPrintResponse
                                   .Print());
                        });

                        TaskCompletionSource <string> printCompletedTcs = new TaskCompletionSource <string>();
                        browser.PrintHtmlContentHandler
                            = new Handler <PrintHtmlContentParameters, PrintHtmlContentResponse>(p =>
                        {
                            try
                            {
                                // Get the print job for the built-in PDF printer.
                                PdfPrinter <PdfPrinter.IHtmlSettings> pdfPrinter = p.Printers.Pdf;
                                IPrintJob <PdfPrinter.IHtmlSettings> printJob    = pdfPrinter.PrintJob;

                                // Apply the necessary print settings
                                printJob.Settings.Apply(s =>
                                {
                                    s.PaperSize = pdfPrinter.Capabilities
                                                  .PaperSizes
                                                  .FirstOrDefault(size => size.Name.Contains("A4"));
                                    s.PrintingHeaderFooterEnabled = true;
                                    // Specify the path to save the result.
                                    s.PdfFilePath = pdfFilePath;
                                });

                                string browserUrl        = p.Browser.Url;
                                printJob.PrintCompleted += (sender, args) =>
                                {
                                    printCompletedTcs.TrySetResult(browserUrl);
                                };

                                // Tell Chromium to use the built-in PDF printer for printing.
                                return(PrintHtmlContentResponse.Print(pdfPrinter));
                            }
                            catch (Exception e)
                            {
                                printCompletedTcs.TrySetException(e);
                                throw;
                            }
                        });

                        // 4. Initiate printing and wait until it is completed.
                        Console.WriteLine("URL loaded. Initiate printing");
                        browser.MainFrame.Print();
                        string printedUrl = printCompletedTcs.Task.Result;
                        Console.WriteLine("Printing completed for the URL: " + printedUrl);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine("Press any key to terminate...");
            Console.ReadKey();
        }
Beispiel #13
0
        private void CreatePrintJobItem(IPrintJob printJob)
        {
            var formatItem = new ListViewItem(printJob.LabelFormatType)
            {
                Checked = true,
                Group = printJob.SeriesNo == 0 ? null : printJobListView.Groups[printJob.SeriesId]
            };

            formatItem.SubItems.Add(printJob.LabelQuantity.ToString());
            formatItem.SubItems.Add(printJob.AdditionalInfo);
            formatItem.SubItems.Add(printJob.PrinterName);

            printJobListView.Items.Add(formatItem);
        }
Beispiel #14
0
        public void DoPrintJob()
        {
            try
            {
                Token token = null;

                bool      complete       = false;
                bool      success        = true;
                string    additionalInfo = String.Empty;
                IPrintJob printJob       = null;
                CardData  cardData       = null;

                // Go through steps proided the process hasnt completed or a step was not sucessful
                for (int step = 0; complete == false && success == true; step++)
                {
                    switch (step)
                    {
                    case 0:     // Connect to printer and do any setup
                        success = PrinterConnectAndSetup(out token, out additionalInfo);
                        break;

                    case 1:     // Get the print Job and settings
                        success = GetPrintJob(token, out printJob, out additionalInfo);
                        break;

                    case 2:     // Set Printer settings
                        success = SetPrinterSetting(printJob, out additionalInfo);
                        break;

                    case 3:     // Start physical printing
                        success  = StartPhysicalPrint(printJob, out cardData, out additionalInfo);
                        complete = true;
                        break;

                    default: complete = true; break;
                    }
                }

                if (complete && success)
                {
                    // Update Indigo
                    _cardPrinting.PrintingComplete(token, cardData);
                    Dictionary <string, string> _printerInfo = _printer.GetPrinterInfo();
                    string cardscount = "-1";
                    _printerInfo.TryGetValue("Total Cards Printed", out cardscount);
                    if (!string.IsNullOrEmpty(cardscount))
                    {
                        PrinterInfo printerInfo = new PrinterInfo
                        {
                            TotalPrints = int.Parse(cardscount),
                            SerialNo    = _printer.DeviceId
                        };
                        // Send Analytics
                        _cardPrinting.PrinterAuditDetails(token, printerInfo);
                    }

                    OnUiUpdate(CardPrintingLogicResource.PrintingDoneUi, false, true, EventArgs.Empty);
                }
                else
                {
                    OnUiUpdate(CardPrintingLogicResource.PrintingFailedUi + additionalInfo, false, true, EventArgs.Empty);
                    _cardPrinting.PrintFailed(token, additionalInfo);
                }
            }
            catch (System.ServiceModel.EndpointNotFoundException enfex)
            {
                OnUiUpdate(enfex.Message, false, true, EventArgs.Empty);
                //Console.WriteLine(enfex);
            }
            catch
            {
                throw;
                //OnUiUpdate(String.Format("{0}{1}{2}{3}{4}", _pinPad.DllPath, Environment.NewLine,ex.Message, Environment.NewLine, ex.ToString()), EventArgs.Empty);
                //Console.WriteLine(ex);
            }
            finally
            {
                _printer.Disconnect();
                _printer.OnDeviceNotifcation -= DeviceNotifcation;
                _printer.Dispose();
            }
        }