Exemplo n.º 1
0
        private async void PrintDocument(Job job, bool manual = false)
        {
            try
            {
                var jobPrinters    = GetPrintersAsync(job);
                var printerToPrint = jobPrinters.FirstOrDefault(x => !_printingJobs.Keys.Any(p => string.Compare(x.Name, p.Name) == 0));
                if (printerToPrint == null)
                {
                    return;
                }

                _loggingService.WriteInformation($"Starting print document {job.Document.TypeTitle} on {printerToPrint.Name}");

                _printingJobs.Add(printerToPrint, job);

                job.Printer  = printerToPrint.Name;
                job.Quantity = printerToPrint.DocumentTypes
                               .Where(x => x.DocumentType == job.Document.Type)
                               .Select(x => x.Quantity).Single();
                job.State     = JobState.Printing;
                job.UpdatedOn = DateTime.Now;
                JobChangedEvent?.Invoke(job);

                await _printerService.PrintDocumentAsync(printerToPrint, job.Document, job.Quantity, (r, e) =>
                {
                    try
                    {
                        if (r)
                        {
                            _loggingService.WriteInformation($"Document {job.Document.TypeTitle} is printed on {printerToPrint.Name}");
                        }
                        else
                        {
                            Debug.WriteLine($"Error in {nameof(JobsService.PrintDocument)}: {e.ToString()}");
                            _loggingService.WriteInformation($"Printing document {job.Document.TypeTitle} on {printerToPrint.Name} is failed");
                            _loggingService.WriteError(e.ToString());
                        }

                        job.Error     = e;
                        job.State     = r ? JobState.Printed : JobState.Error;
                        job.UpdatedOn = DateTime.Now;
                        JobChangedEvent?.Invoke(job);

                        _printingJobs.Remove(printerToPrint);
                        if (!_printingJobs.Any())
                        {
                            MovePrintedJobs();
                        }
                    }
                    catch (Exception exception)
                    {
                        _loggingService.WriteError($"Error complited printing document. {exception}");
                    }
                });
            }
            catch (Exception exception)
            {
                _loggingService.WriteError($"Error printing document. {exception}");
            }
        }