Exemple #1
0
        /// <summary>
        /// Initializes data
        /// </summary>
        private void Init()
        {
            try
            {
                LogHelper.LogDebug();

                // get current dispatcher for work with UI
                _dispatcher = Dispatcher.CurrentDispatcher;

                // load config files
                API.LoadConfig(ConfigData.FilePath_InnerConfig);  // local config or 1st config
                API.LoadConfig(ConfigData.FilePath_RemoteConfig); // remote config or 2nd config

                // removes old print jobs of the available printers
                RemoveJobs();

                // establish call-backs
                PrintHelper.SkipMethod = SkipDocument;
                PrintHelper.AddWatcher = AddWatcher;

                // subscribe to the file monitor event
                fileMonitor.FileFound += fileMonitor_FileFound;

                // create list of (virtual) printers to be excluded from the track process
                List <string> allp = new List <string> {
                    ConfigData.PrinterName, ConfigData.PrinterName2
                };

                // set up local watcher
                localPrintEventWatcher = new PrintEventWatcher(Environment.MachineName, Environment.MachineName, false, allp, "0.001");
                localPrintEventWatcher.PrintJobPaused    += LocalPrintEventWatcherPrintJobPaused;
                localPrintEventWatcher.PrintJobStarted   += LocalPrintEventWatcherPrintJobStarted;
                localPrintEventWatcher.PrintJobCompleted += LocalPrintEventWatcherPrintJobCompleted;
                localPrintEventWatcher.PrintJobCancelled += LocalPrintEventWatcherPrintJobCancelled;

                // set up allowed printers to skip
                localPrintEventWatcher.AllowedPrintersToSkip = new List <string>();
                localPrintEventWatcher.AllowedPrintersToSkip.Add(ConfigData.PrinterName);
                localPrintEventWatcher.AllowedPrintersToSkip.Add(ConfigData.PrinterName2);

                // initialize watcher
                localPrintEventWatcher.Init();

                // update available printers
                UpdateAvailablePrinters();

                // init print job watchers
                _watchers               = new PrintJobWatchers();
                _watchers.IssueFound   += _watchers_IssueFound;
                _watchers.JobCompleted += _watchers_JobCompleted;
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
                _timerRetry.Start();
            }

            // set default printer
            SetDefaultPrinter();
        }
Exemple #2
0
        /// <summary>
        /// Initializes timers
        /// </summary>
        private void InitTimer()
        {
            try
            {
                // init retry timer
                _timerRetry           = new Timer();
                _timerRetry.Enabled   = false;
                _timerRetry.AutoReset = false;
                _timerRetry.Interval  = ConfigData.Interval_TimerRestart;
                _timerRetry.Elapsed  += timerRetry_Elapsed;
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }

            try
            {
                // init get printers timer
                _timerGetPrinters           = new Timer();
                _timerGetPrinters.Enabled   = false;
                _timerGetPrinters.AutoReset = false;
                _timerGetPrinters.Interval  = ConfigData.Interval_TimerGetPrinters;
                _timerGetPrinters.Elapsed  += timerGetPrinters_Elapsed;
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
Exemple #3
0
        /// <summary>
        /// Shows advanced printer settings
        /// </summary>
        /// <param name="handle">window handle</param>
        /// <param name="printerName">printer name</param>
        /// <param name="settings">settings</param>
        public void ShowAdvancedPrinterSettings(IntPtr handle, string printerName, ref System.Drawing.Printing.PrinterSettings settings)
        {
            // check the printer settings
            if (settings == null || !settings.IsValid)
            {
                LogHelper.LogDebug("Invalid printer settings for " + printerName);
                return;
            }

            LogHelper.LogDebug();

            try
            {
                // create new printer settings
                System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();

                // set new settings as an old one
                ps = settings;

                // show printer settings window as dialog for the current window
                if (PrintDialogHelper.EditPrinterSettings(ps, handle) == System.Windows.Forms.DialogResult.OK)
                {
                    LogHelper.LogDebug("Printer settings changed");

                    // save changed printer settings
                    settings = ps;
                }
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
Exemple #4
0
        /// Print
        #region Print

        /// <summary>
        /// Prints PDF
        /// </summary>
        /// <param name="printer">printer settings</param>
        /// <param name="fileName">file name</param>
        /// <param name="printerName">printer name</param>
        /// <param name="documentName">document name</param>
        /// <returns></returns>
        public static bool Print_Default(PrinterSettings printer, string fileName, string documentName, string owner, string host)
        {
            try
            {
                if (!File.Exists(fileName))
                {
                    LogHelper.Log("No file found : " + fileName);
                    return(false);
                }

                // Now print the PDF document
                using (var document = PdfDocument.Load(fileName))
                {
                    using (var printDocument = document.CreatePrintDocument())
                    {
                        printDocument.DocumentName        = documentName;
                        printDocument.PrinterSettings     = printer;
                        printDocument.DefaultPageSettings = printer.DefaultPageSettings;
                        printDocument.PrintController     = new StandardPrintController();
                        printDocument.Print();
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
                return(false);
            }
        }
Exemple #5
0
        /// Methods
        #region Methods

        /// <summary>
        /// Saves printers data.
        /// </summary>
        public void Save(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return;
            }

            try
            {
                /*
                 * JArray array = new JArray();
                 * foreach (var item in this)
                 *  array.Add(JToken.Parse(JsonConvert.SerializeObject(item)));
                 *
                 * string json = array.ToString();*/
                string json = JsonConvert.SerializeObject(this.ToArray());

                if (!string.IsNullOrWhiteSpace(json))
                {
                    File.WriteAllText(fileName, json);
                }
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
Exemple #6
0
        /// Window Event Handling
        #region Window Event Handling

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void WindowClosed(object sender, EventArgs e)
        {
            try
            {
                // get window as a sender of event
                PrintingControlWindow window = sender as PrintingControlWindow;

                // check the window
                if (window != null && window.ViewModel != null && window.ViewModel.PrintJobTitle != null)
                {
                    // remove window from the list
                    listOfWindows.Remove(window);

                    // remove print job title from the titles
                    localPrintEventWatcher.AllowedPrintersTitles.RemoveTitle(window.ViewModel.PrintJobTitle);

                    // unsubscribe from event
                    window.Closed -= WindowClosed;
                }
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
        /// HasColor
        #region HasColor

        /// <summary>
        /// Indicates whether specified file has color or not. Has to be supported file (ps or pdf)
        /// </summary>
        /// <param name="fileName">file name</param>
        /// <returns>true if has color; otherwise false</returns>
        public static bool?HasColor(string fileName)
        {
            if (String.IsNullOrWhiteSpace(fileName))
            {
                return(null);
            }

            try
            {
                if (!File.Exists(fileName))
                {
                    return(null);
                }

                SupportedPrintFormat format = GetFileFormat(fileName);
                if (format == SupportedPrintFormat.PDF)
                {
                    return(GhostScriptHelper.HasColor(fileName));
                }
                else if (format == SupportedPrintFormat.PS)
                {
                    return(PostScriptHelper.HasColor(fileName));
                }
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }

            return(null);
        }
        /// Print
        #region Print

        /// <summary>
        /// Prints data.
        /// </summary>
        public void Print()
        {
            // check if it's Demo mode
            if (IsTestMode)
            {
                return;
            }

            IsControlsEnabled = false;
            SetStatus();

            Task t = new Task(() =>
            {
                try
                {
                    if (IsBlockedMode)
                    {
                        ResumeJobFirstTry(PrintJobData);
                    }
                    else
                    {
                        PrintFirstTry(PDFFileName, Title.Document, ChosenPrinter.Settings);
                    }
                }
                catch (Exception ex)
                {
                    WPFNotifier.Error(ex);
                }
            });

            t.Start();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="host"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static bool UpdateJobData(string host, ref PrintJobData data)
        {
            if (data == null)
            {
                return(false);
            }

            if (data.PrintJobTitle == null)
            {
                return(false);
            }

            if (String.IsNullOrWhiteSpace(data.PrintJobTitle.PrinterName))
            {
                return(false);
            }

            bool updated = false;

            try
            {
                string printerName = data.PrintJobTitle.PrinterName;
                if (!String.IsNullOrWhiteSpace(host))
                {
                    printerName = data.PrintJobTitle.PrinterName.Replace(host, "").Trim();
                    if (printerName[0] == '\\')
                    {
                        printerName = printerName.Substring(1);
                    }

                    LogHelper.LogDebug("MAIN " + host + " printerName " + printerName);
                }
                else
                {
                    LogHelper.LogDebug("MAIN local printerName " + printerName);
                }

                updated = UpdateJobData(ref data, printerName, host);

                /*
                 * if (!updated)
                 * {
                 *  int pos = data.PrintJobTitle.PrinterName.LastIndexOf("\"");
                 *  string nnn = null;
                 *  if (pos > 0)
                 *      nnn = data.PrintJobTitle.PrinterName.Substring(pos + 1);
                 *  LogHelper.LogDebug("nnn " + nnn);
                 *  updated = UpdateJobData(ref data, nnn, host);
                 * }*/
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }

            return(updated);
        }
        /// <summary>
        /// Changes list of printers
        /// </summary>
        public void ChangePrinters()
        {
            LogHelper.LogDebug();

            try
            {
                bool nocolored = false;
                CanPrintWithColor = true;
                List <string> printers = null;
                if (PrintWithColor)
                {
                    printers = MainController.Singleton.AvailablePrinters.ColoredNames;
                    if (printers == null || printers.Count < 1)
                    {
                        nocolored = true;
                    }
                }
                else
                {
                    printers = MainController.Singleton.AvailablePrinters.AllNames;
                }

                if (nocolored)
                {
                    LogHelper.LogDebug("No available color printers found. You are not allowed to print colored this time.");
                    WPFNotifier.Warning("No available color printers found. You are not allowed to print colored this time.");
                    CanPrintWithColor = false;
                    return;
                }

                if (printers == null || printers.Count < 1)
                {
                    LogHelper.LogDebug("No available printers found. You are not allowed to print this time.");
                    WPFNotifier.Warning("No available printers found. You are not allowed to print this time.");
                    return;
                }

                LogHelper.LogDebug("Add printers to combo : " + printers.Count);

                MainController.Singleton.Dispatcher.Invoke(new Action(() =>
                {
                    Printers.Clear();
                    foreach (string name in printers.ToArray())
                    {
                        Printers.Add(name);
                    }
                }), DispatcherPriority.Background);

                Thread.Sleep(100);
                SetDefaultPrinter();
            }
            catch (Exception ex)
            {
                WPFNotifier.Error("This printer is not available now. Try to use one of the other printers.", null, ex);
                Close();
            }
        }
        /// UpdateJobData
        #region UpdateJobData

        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <param name="printerName"></param>
        /// <param name="host"></param>
        /// <returns></returns>
        private static bool UpdateJobData(ref PrintJobData data, string printerName, string host)
        {
            bool updated = false;

            try
            {
                LogHelper.LogDebug("INNER START " + printerName);
                PrintQueue queue = GetPrintQueue(printerName, host);
                if (queue == null)
                {
                    return(false);
                }

                queue.Refresh();
                if (queue.NumberOfJobs > 0)
                {
                    bool quit = false;
                    while (!quit)
                    {
                        try
                        {
                            LogHelper.LogDebug("jobs " + queue.GetPrintJobInfoCollection().Count() + " | " + queue.NumberOfJobs);
                            foreach (PrintSystemJobInfo info in queue.GetPrintJobInfoCollection())
                            {
                                info.Refresh();
                                string docName       = info.Name;
                                int    NumberOfPages = info.NumberOfPages;
                                int    xxx           = info.NumberOfPagesPrinted;
                                LogHelper.LogDebug("Printing " + info.IsPrinting + " | Paused " + info.IsPaused + " | Spooling " + info.IsSpooling + " | IsDeleting " + info.IsDeleting);
                                LogHelper.LogDebug("pages " + NumberOfPages + " printed " + xxx);
                                if (data.PrintJobTitle.Document == docName && data.PrintJobTitle.TotalPages < xxx)
                                {
                                    data.PrintJobTitle.TotalPages = xxx;
                                    updated = true;
                                }
                            }

                            quit = true;
                        }
                        catch (Exception ex)
                        {
                            queue.Refresh();
                            LogHelper.LogDebug("refresh");
                            WPFNotifier.Error(ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }

            LogHelper.LogDebug("INNER END " + printerName);
            return(updated);
        }
Exemple #12
0
        /// <summary>
        /// Launches print control window for the specified file. (Virtual printer method)
        /// </summary>
        /// <param name="eFileName">file name</param>
        /// <param name="copyFile">copy file flag</param>
        public void LaunchPrintControl(string eFileName, bool copyFile = true)
        {
            // check the file name
            if (string.IsNullOrWhiteSpace(eFileName))
            {
                return;
            }

            LogHelper.LogDebug("Launch UI For File " + eFileName);

            try
            {
                string newFileName = eFileName;
                if (copyFile)
                {
                    // create new file name
                    newFileName = Path.Combine(ConfigData.Path_Processing, Path.GetFileName(eFileName));

                    // if the file with new file name exists
                    if (File.Exists(newFileName))
                    {
                        // delete the file
                        File.Delete(newFileName);
                    }

                    // copy old file to the new one
                    File.Copy(eFileName, newFileName);
                }

                _dispatcher.BeginInvoke(new Action(() =>
                {
                    PrintJobTitle title = null;

                    // check the allowed printers
                    if (localPrintEventWatcher.AllowedPrintersTitles != null && localPrintEventWatcher.AllowedPrintersTitles.Count > 0)
                    {
                        // get the last title from the allowed printers (this needs for retrieving the correct print job title, for example)
                        title = localPrintEventWatcher.AllowedPrintersTitles.Last();
                    }

                    // show preparing progress
                    //MainController.Singleton.ShowProgressWindow("Preparing", "Your document is being prepared for printing, please wait...");

                    // set up an launch UI for the incoming file
                    PrintingControlWindow window = new PrintingControlWindow(newFileName, title);
                    window.Closed += WindowClosed;

                    // show UI
                    window.Show();
                }), DispatcherPriority.Background);
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
        /// <summary>
        /// Gets chosen printer and its' settings
        /// </summary>
        /// <returns></returns>
        public Printer GetChosenPrinterWithSettings(bool colored)
        {
            // check the selected index
            if (SelectedPrinterIndex < 0)
            {
                return(null);
            }

            try
            {
                LogHelper.LogDebug();

                // get chosen printer
                Printer PrinterX = MainController.Singleton.AvailablePrinters.ByColor(colored)[SelectedPrinterIndex];

                // set chosen printer
                ChosenPrinter = PrinterX;

                // check settings
                if (PrinterX.Settings == null)
                {
                    // first time settings set

                    // fullfill some important settings values
                    PrinterSettings = new PrinterSettings()
                    {
                        PrinterName = ChosenPrinter.Name, Duplex = PrintDuplex, DefaultPageSettings = { Color = colored }
                    };

                    // validate settings
                    if (!PrinterSettings.IsValid)
                    {
                        throw new NotSupportedException("Wrong printer settings");
                    }

                    // set settings
                    PrinterX.Settings = PrinterSettings;
                }
                else
                {
                    // set settings by saved settings set
                    PrinterSettings        = PrinterX.Settings;
                    PrinterSettings.Duplex = PrintDuplex;
                    PrinterSettings.DefaultPageSettings.Color = colored;
                    PrinterSettings.Copies = NumberOfCopies;
                }

                return(PrinterX);
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }

            return(null);
        }
Exemple #14
0
 /// <summary>
 ///
 /// </summary>
 /// <param appName="sender"></param>
 /// <param appName="e"></param>
 public static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
 {
     try
     {
         WPFNotifier.Error(e.Exception);
     }
     catch
     {
     }
 }
Exemple #15
0
        // Unhandled Exceptions
        #region Unhandled Exceptions

        /// <summary>
        ///
        /// </summary>
        /// <param appName="sender"></param>
        /// <param appName="e"></param>
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                WPFNotifier.Error(e.ExceptionObject as Exception);
            }
            catch
            {
            }
        }
 /// <summary>
 /// Saves data.
 /// </summary>
 private void Save()
 {
     try
     {
         string json = JsonConvert.SerializeObject(this);
         if (!string.IsNullOrWhiteSpace(json))
         {
             File.WriteAllText(ConfigData.FilePath_EnvironmentConfig, json);
         }
     }
     catch (Exception ex)
     {
         WPFNotifier.Error(ex);
     }
 }
Exemple #17
0
        static void Main()
        {
            try
            {
                LogHelper.Init("test.log.txt");

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new APITestForm());
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
        /// <summary>
        ///
        /// </summary>
        private void Init()
        {
            //API.LoadConfig(ConfigData.Path_InnerConfig);

            methods = GetMethods();

            try
            {
                comboBoxMethods.Items.AddRange(methods.Select(x => x.Name).ToArray());
                comboBoxMethods.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
        /// <summary>
        /// Shows advanced settings window.
        /// </summary>
        /// <param name="owner">owner</param>
        public void ShowAdvancedSettings(Window owner)
        {
            if (IsBlockedMode)
            {
                return;
            }

            try
            {
                // get chosen printer by color setting
                Printer pr = GetChosenPrinterWithSettings(PrintWithColor);
                if (pr == null)
                {
                    return;
                }

                // initialize settings extractor
                UISettingsExtractor extractor = new UISettingsExtractor(ChosenPrinter.Name, DesktopHelper.GetDesktopWindow());

                // start extractor
                extractor.Start();

                // show advanced printer settings
                MainController.Singleton.ShowAdvancedPrinterSettings(new WindowInteropHelper(owner).Handle, ChosenPrinter.Name, ref PrinterSettings);

                // stop extractor
                extractor.Stop();

                // get booklet data from extractor
                PrintBooklet = extractor.Booklet;
                LogHelper.LogDebug(PrintBooklet);

                // set changed printer settings
                pr.Settings = PrinterSettings;

                // set UI data by printer settings
                SetByPrinterSettings();
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
        /// <summary>
        /// Loads local environment data.
        /// </summary>
        /// <returns>true if loaded; otherwise false</returns>
        private bool LoadLocal()
        {
            try
            {
                if (File.Exists(ConfigData.FilePath_EnvironmentConfig))
                {
                    string data = File.ReadAllText(ConfigData.FilePath_EnvironmentConfig);
                    if (!string.IsNullOrWhiteSpace(data))
                    {
                        return(_Load(JToken.Parse(data)));
                    }
                }
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }

            return(false);
        }
 /// <summary>
 /// Update data by DEVMODE structure.
 /// </summary>
 private void UpdateDataDevMode()
 {
     try
     {
         // get job info
         var jobInfo2 = CubiclesPrinterLib.Win32.Print.PrintJob.GetJobInfo(PrintJobData.RemotePrinterName, PrintJobData.PrintJobTitle.JobID);
         if (jobInfo2 != null)
         {
             NumberOfCopies = (short)jobInfo2.dmOut.dmCopies;
             PrintDuplex    = (Duplex)jobInfo2.dmOut.dmDuplex;
         }
         else
         {
             WPFNotifier.Warning(PrintJobData.RemotePrinterName + Environment.NewLine + " Can't access printer, data corrupted, default values set.");
         }
     }
     catch (Exception ex)
     {
         WPFNotifier.Error(ex);
     }
 }
        /// <summary>
        /// Prints / Resumes print job.
        /// </summary>
        public void Print()
        {
            // check window
            if (_owner != null)
            {
                _owner.Dispatcher.BeginInvoke(new Action(() =>
                {
                    _owner.Hide();
                }), DispatcherPriority.Background);
            }

            MainController.Singleton.ShowProgressWindow("Sending", "Your document is being sent to the printer. \r\n\r\nPlease make sure the document has been fully printed before you log out.");

            // check the model and chosen printer
            if (_model != null && _model.ChosenPrinter != null)
            {
                // check the settings of the chosen printer
                if (_model.ChosenPrinter.Settings == null)
                {
                    WPFNotifier.Error("Default printer settings will be set");
                    _model.ChosenPrinter.Settings = new System.Drawing.Printing.PrinterSettings()
                    {
                        PrinterName = _model.ChosenPrinter.Name
                    };
                }

                _model.ChosenPrinter.Settings.DefaultPageSettings.Color = PrintWithColor;

                // print / resume
                _model.Print();
            }
            else
            {
                WPFNotifier.Error("Can't print - printer aren't chosen");
            }

            // update UI
            Update();
        }
Exemple #23
0
        /// <summary>
        /// Initializes data.
        /// </summary>
        public static void Init()
        {
            try
            {
                LoadConfig(FilePath_InnerConfig);
                LoadConfig(FilePath_RemoteConfig);

                IO.CreateHiddenDirectory(Path_App, false);
                IO.CreateHiddenDirectory(Path_User);
                IO.CreateHiddenDirectory(@"C:\PrinterLogs", false);
                IO.CreateHiddenDirectory(Path_Logs);
                IO.CreateHiddenDirectory(Path_Temp);
                IO.CreateHiddenDirectory(Path_Monitor);
                IO.CreateHiddenDirectory(Path_Processing);

                // clean monitor and processing directories at start
                IO.CleanDirectory(Path_Monitor);
                IO.CleanDirectory(Path_Processing);
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
Exemple #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _watchers_IssueFound(object sender, PrinterIssueEventArgs e)
        {
            LogHelper.LogDebug();
            try
            {
                // check the event args
                if (e != null)
                {
                    LogHelper.LogDebug(e.Issue.Issue());
                    if (e.Issue != PrinterTrouble.None)
                    {
                        // notify about issue via API
                        APIWrapper.PrinterIssue(Environment.MachineName, Environment.UserName, e.PrinterName, e.Issue);

                        // show error message to user
                        WPFNotifier.Error(string.Format("Document can't be printed because of printer issue : {1}.{0}Administration has been notified about this issue.", Environment.NewLine, e.Issue.Issue()));
                    }
                }
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
        /// <summary>
        /// Updates data.
        /// </summary>
        /// <param name="data">updated data to be used</param>
        public void UpdateData(PrintJobData data)
        {
            // check data
            if (data == null)
            {
                LogHelper.LogDebug("Update data but nothing received");
                return;
            }

            try
            {
                LogHelper.LogDebug("Update data, pages " + data.PrintJobTitle.TotalPages);

                // update data if more pages found
                if (data.PrintJobTitle.TotalPages > PrintJobData.PrintJobTitle.TotalPages)
                {
                    LogHelper.LogDebug("Current pages " + PrintJobData.PrintJobTitle.TotalPages);

                    // set data
                    PrintJobData = data;

                    // update values
                    Title         = data.PrintJobTitle;
                    NumberOfPages = data.PrintJobTitle.TotalPages;

                    // set status
                    SetStatus("Ready to print");
                }
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }

            UpdateDataDevMode();
        }
        /// <summary>
        /// Gets the data asynchronously
        /// </summary>
        private void GetDataAsync()
        {
            CancellationTokenSource source = new CancellationTokenSource();

            try
            {
                // main auxiliary task to perform subtasks and notify system when everything is done
                Task t = new Task(() =>
                {
                    try
                    {
                        // task to update printers list
                        Task t1 = new Task(() =>
                        {
                            SetStatus("Update Printers");
                            // update printers
                            if (!UpdatePrinters())
                            {
                                source.Cancel(false);
                            }
                            SetStatus();
                        });

                        // task to convert PS to PDF and determine colors
                        Task t2 = new Task(() =>
                        {
                            // get colors
                            // set status
                            PDFFileName = PSFileName + ".pdf";
                            SetStatus("Convert to PDF");
                            GhostScriptHelper.ConvertPStoPDF(PSFileName, PDFFileName);
                            SetStatus("Determine colors");
                            FileHasColor = PDFHelper.HasColor(PDFFileName);
                            OnColorDetermined(EventArgs.Empty);
                            SetStatus();
                        });

                        // task to get metadata from PS file
                        Task t3 = new Task(() =>
                        {
                            // get postscript data
                            SetStatus("Get Print Data");
                            GetPSData(PSFileName);
                            OnColorDetermined(EventArgs.Empty);
                            SetStatus();
                        });

                        t1.Start();
                        t2.Start();
                        t3.Start();

                        // wait until every auxiliary task is completed
                        Task.WaitAll(new Task[] { t1, t2, t3 }, source.Token);

                        if (PostScriptMetaData != null)
                        {
                            PostScriptMetaData.HasColor = FileHasColor;
                        }

                        SetStatus("Set Printers");
                        // change printers
                        ChangePrinters();

                        // release controls
                        IsControlsEnabled = true;
                        SetStatus("Ready to Print");

                        // notify system about readiness
                        OnReadyToPrint(EventArgs.Empty);
                    }
                    catch (Exception ex)
                    {
                        WPFNotifier.Error(ex);
                    }
                });

                t.Start();
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
        /// <summary>
        /// Print event arrived
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mewPrintJobs_JobArrived(object sender, EventArrivedEventArgs e)
        {
            if (!_doWatching)
            {
                return;
            }

            try
            {
                // get arrived print job
                ManagementBaseObject printJob = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
                if (printJob == null)
                {
                    return;
                }

                PrintJobData printJobData = new PrintJobData(printJob, _host);

                LogHelper.LogDebug(_host + " : " + printJobData.PrintJobTitle + " | " + printJobData.JobStatus);

                if (CanSkip(printJobData, false))
                {
                    //ResetSkip(printJobData);
                    //OnPrintJobStarted(new PrintJobDataEventArgs(printJobData));
                    return;
                }

                foreach (var _printerToPauseAndShow in _printersToPauseAndShow)
                {
                    if (IsSamePrinter(_printerToPauseAndShow, printJobData.PrintJobTitle.PrinterName, _jobHost))
                    {
                        if (ConfigData.Config_InterceptPrintJobAndCancel)
                        {
                            if (printJobData.PrintJobTitle.TotalPages > 0)
                            {
                                LogHelper.LogDebug(_host + " : TotalPages " + printJobData.PrintJobTitle.TotalPages);
                            }

                            // this job has to be intercepted
                            //PrintHelper.CancelPrintJob(printJob);
                            PrintHelper.CancelAllPrintJobs(printJob, _host);

                            OnPrintJobCancelled(new PrintJobDataEventArgs(printJobData));
                            //if (_host != "ADSERVER")
                            //WPFNotifier.Warning(string.Format("You are not allowed to choose this printer.{0}You have to use {1} or {2} instead.{0}Printing cancelled.", Environment.NewLine, ConfigData.PrinterName, ConfigData.PrinterName2));
                            return;
                        }
                        else
                        {
                            PrintHelper.PausePrintJob(printJob, _host);
                        }
                    }
                }

                /*
                 * // this job has to be intercepted
                 * PrintHelper.CancelPrintJob(printJob);
                 * WPFNotifier.Warning(string.Format("You are not allowed to choose this printer.{0}You have to use {1} instead.{0}Printing cancelled.", Environment.NewLine, ConfigData.PrinterName));*/
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
Exemple #28
0
        /// LoadConfig
        #region LoadConfig

        /// <summary>
        /// Loads config data from the specified file.
        /// </summary>
        /// <param name="fileName">config file name</param>
        static void LoadConfig(string fileName)
        {
            LogHelper.LogDebug(fileName);

            if (string.IsNullOrWhiteSpace(fileName))
            {
                return;
            }

            try
            {
                if (!File.Exists(fileName))
                {
                    return;
                }

                LogHelper.LogDebug("Reading file");
                string text = File.ReadAllText(fileName);
                if (string.IsNullOrWhiteSpace(text))
                {
                    return;
                }

                string[] sstext = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                if (sstext == null || sstext.Length < 1)
                {
                    return;
                }

                LogHelper.LogDebug("Reading config data");
                foreach (string line in sstext)
                {
                    string[] liness = line.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                    if (liness == null || liness.Length != 2)
                    {
                        continue;
                    }

                    string key   = liness[0].Trim();
                    string value = liness[1].Trim();
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        continue;
                    }

                    switch (key)
                    {
                    case "UserName":
                        UserName = value;
                        break;

                    case "MachineName":
                        MachineName = value;
                        break;

                    case "FilePath_PrintLog":
                        FilePath_PrintLog = value.FullPathFromRelative(Path_App);
                        LogHelper.LogDebug(FilePath_PrintLog);
                        break;

                    case "FilePath_PrinterConfig":
                        FilePath_PrinterConfig = value.FullPathFromRelative(Path_App);
                        break;

                    case "FilePath_RemoteConfig":
                        FilePath_RemoteConfig = value.FullPathFromRelative(Path_App);
                        break;
                    }
                }

                LogHelper.LogDebug("End");
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }
Exemple #29
0
        /// <summary>
        /// Launches print control window for the specified data. (Real printer method)
        /// </summary>
        /// <param name="printJob"></param>
        public void LaunchPrintControl(PrintJobData printJob)
        {
            // check the print job data
            if (printJob == null || printJob.PrintJobTitle == null)
            {
                return;
            }

            LogHelper.LogDebug("Launch For Real Printer " + printJob.PrintJobTitle);

            try
            {
                _dispatcher.BeginInvoke(new Action(() =>
                {
                    // Update print job logic:
                    // if the window already created but we received additional data (like number of pages) then find that window and update it's data

                    // iterate through the list of windows
                    foreach (var f in listOfWindows)
                    {
                        LogHelper.LogDebug("Seek Window");

                        // get the data context of the window - has to be a PrintingControlViewModel
                        var dc = f.DataContext as PrintingControlViewModel;

                        // check the data context
                        if (dc != null)
                        {
                            // compare print job titles
                            if (dc.PrintJobTitle.Equals(printJob.PrintJobTitle))
                            {
                                LogHelper.LogDebug("Window found");
                                // update data
                                f.UpdateData(printJob);
                                return;
                            }
                        }
                    }

                    // if the job ain't present for some reason at this moment then leave
                    if (!PrintHelper.HasPrintJob(printJob.ServerHost, printJob.PrintJobTitle))
                    {
                        return;
                    }

                    // set up an launch UI for the incoming data
                    PrintingControlWindow window = new PrintingControlWindow(printJob);
                    window.Closed += WindowClosed;

                    // add window to a list
                    listOfWindows.Add(window);

                    // show UI
                    window.ShowDialog();
                }), DispatcherPriority.Background);
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }
        }