private static Status CancelJob(PrintQueue printQueue, string uniqueFileName) { // If you do not "refresh" the print queue, then getting information about the jobs will fail. printQueue.Refresh(); PrintJobInfoCollection jobs = printQueue.GetPrintJobInfoCollection(); // Extension is pulled out because some applications omit the file extension when it creates the job name. string fileName = Path.GetFileNameWithoutExtension(uniqueFileName); PrintSystemJobInfo jobInfo = jobs.FirstOrDefault(j => j.Name.Contains(fileName)); jobInfo?.Cancel(); //wait for 20 seconds to check if the job got deleted DateTime expireTime = DateTime.Now + TimeSpan.FromSeconds(20); while (jobInfo.IsDeleting && DateTime.Now < expireTime) { Thread.Sleep(100); } if (jobInfo.IsDeleted) { return(Status.Passed); } return(Status.Failed); }
private void btnLoadQueues_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; var jobList = String.Empty; var server = new PrintServer(); var queues = server.GetPrintQueues(); foreach (PrintQueue pq in queues) { pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { // Since the user may not be able to articulate which job is problematic, // present information about each job the user has submitted. jobList = jobList + "\nServer:\r\n"; jobList = jobList + "\n\tQueue:" + pq.Name; jobList = jobList + "\n\tLocation:" + pq.Location; jobList = jobList + "\n\t\tJob: " + job.JobName + " ID: " + job.JobIdentifier; } // end for each print job } // end for each print queue txtStatus.Text = jobList; Cursor.Current = Cursors.Default; }
public List <uJob> PrinterQueueView() { List <uJob> printJobs = new List <uJob>(); try { PrintServer printServer = new PrintServer(); PrintQueueCollection printQueues = printServer.GetPrintQueues(); foreach (PrintQueue pq in printQueues) { if (pq.NumberOfJobs > 0) { pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { uJob printJob = new uJob(job.Name, $"{pq.Name} | {job.JobName} | {job.JobIdentifier}"); printJobs.Add(printJob); } } } } catch (Exception) { uJob printJob = new uJob("Print Spooler Service", $"An error occurred while loading the Print Jobs."); printJobs.Add(printJob); } return(printJobs); }
private int Count_Jobs(string _ptr_device) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown if (string.IsNullOrEmpty(_ptr_device)) { return(0); } if (!Exist_Printer(_ptr_device)) { MessageBox.Show("Printer '" + _ptr_device + "' is not present"); return(0); } LocalPrintServer val = (LocalPrintServer)(object)new LocalPrintServer(); PrintQueue printQueue = ((PrintServer)val).GetPrintQueue(_ptr_device); ((PrintSystemObject)printQueue).Refresh(); int num = 0; if (printQueue.NumberOfJobs > 0) { PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection(); { foreach (PrintSystemJobInfo item in printJobInfoCollection) { _ = item; num++; } return(num); } } return(num); }
private void buttonShowJobs_Click(object sender, EventArgs e) { try { string psName = ""; PrintServer _ps = new PrintServer();//(@"\\" + psName); PrintQueueCollection _psAllQueues = _ps.GetPrintQueues(); StringBuilder prnStr = new StringBuilder(); foreach (PrintQueue pq in _psAllQueues) { try { pq.Refresh(); //_pq.IsProcessing(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { prnStr.Append("\r\n"); prnStr.Append(pq.Name); prnStr.Append(" : "); prnStr.Append(pq.Location); prnStr.Append("\r\n"); prnStr.Append(job.JobName); prnStr.Append(" ID: "); prnStr.Append(job.JobIdentifier); prnStr.Append(" ID: "); prnStr.Append(job.NumberOfPagesPrinted); prnStr.Append("/"); prnStr.Append(job.NumberOfPages); prnStr.Append(" st:"); prnStr.Append(job.JobStatus.ToString()); prnStr.Append("\r\n-------------------------------------\r\n"); } } catch (Exception ex) { string sEvent = pq.Name + " : " + ex.Message; } } string jobList = prnStr.ToString(); if (string.IsNullOrEmpty(jobList)) { this.textBox1.Text = "No job in queue."; } else { this.textBox1.Text = jobList; } } catch (System.Exception ex) { this.textBox1.Text = ex.Message; } }
public static int SendCommandToPrinter(string command, string printer, string jobId = "", string documentName = "") { Dictionary <string, object> properties = new Dictionary <string, object>(); List <Dictionary <string, object> > printers = new List <Dictionary <string, object> >(); EnumeratedPrintQueueTypes[] enumerationFlags = { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Shared }; LocalPrintServer printServer = new LocalPrintServer(); //Use the enumerationFlags to filter out unwanted print queues PrintQueueCollection printQueuesOnLocalServer = printServer.GetPrintQueues(enumerationFlags); int counter = 0; foreach (PrintQueue printeQueue in printQueuesOnLocalServer) { properties = new Dictionary <string, object>(); printeQueue.Refresh(); PrintJobInfoCollection jobsQueued = printeQueue.GetPrintJobInfoCollection(); if (printeQueue.Name.ToLower().Trim() == printer.ToLower().Trim()) { foreach (PrintSystemJobInfo job in jobsQueued) { if (((job.Name.ToLower().Trim() == documentName.ToLower().Trim() && !string.IsNullOrEmpty(documentName.ToLower().Trim())) || job.JobIdentifier.ToString().ToLower().Trim() == jobId.ToLower().Trim()) || jobId.ToLower().Trim() == "*" ) { if (command.ToLower().Trim() == "purge") { job.Cancel(); counter++; } else if (command.ToLower().Trim() == "pause") { job.Pause(); counter++; } else if (command.ToLower().Trim() == "resume") { job.Resume(); counter++; } else { return(0); } } } } } return(counter); }
private bool checkPrintSuccess(string docName) { bool success = false; PrintServer myPrintServer = new PrintServer(); // List the print server's queues PrintQueueCollection myPrintQueues = myPrintServer.GetPrintQueues(); String printQueueNames = "My Print Queues:\n\n"; string printJob = "JOBS:\n\n"; foreach (PrintQueue pq in myPrintQueues) { printQueueNames += "\t" + pq.Name + "\n"; //HP LaserJet Pro MFP M127fw if (pq.Name == "HP LaserJet Pro MFP M127fw") { try { PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); if (jobs != null) { foreach (PrintSystemJobInfo job in jobs) { printJob += "\t" + job.Name + "\n"; if (job.Name == docName && (((job.JobStatus & PrintJobStatus.Completed) == PrintJobStatus.Completed) || ((job.JobStatus & PrintJobStatus.Printed) == PrintJobStatus.Printed))) { success = true; } else { success = false; } }// end for each print job } } catch (NullReferenceException e) { success = true; } break; } } Console.WriteLine(printQueueNames); MessageBox.Show(printJob); Console.WriteLine("\nPress Return to continue."); Console.ReadLine(); return(success); }
public override void Start() { PrintServer PrintS = new PrintServer(); PrintQueue queue = new PrintQueue(PrintS, _window.PrintInformation.PrinterSettings.PrinterName); bool trouve; List <Document> tempDocToRemove; List <Document> tempDocInQueue; do { tempDocToRemove = new List <Document>(); tempDocInQueue = _window.DocumentsInQueue.ToList(); queue.Refresh(); foreach (Document theDoc in tempDocInQueue) { trouve = false; try { using (PrintJobInfoCollection jobinfo = queue.GetPrintJobInfoCollection()) { foreach (PrintSystemJobInfo job in jobinfo) { using (job) { if (job.Name.Contains(theDoc.Name)) { trouve = true; } } } } } catch (NullReferenceException) { } catch (RuntimeWrappedException) { } catch (InvalidOperationException) { } if (trouve == false) { tempDocToRemove.Add(theDoc); SetStatus(theDoc, State.Printed); } } foreach (Document theDoc in tempDocToRemove) { _window.DocumentsInQueue.Remove(theDoc); } } while (!_token.IsCancellationRequested || _stopWindow.Stopped); PrintS.Dispose(); queue.Dispose(); }
/// <summary> /// Cancel Print Job /// </summary> /// <param name="printName"></param> public static void ClearJob(string printName) { PrintServer localPrintServer = new LocalPrintServer(); PrintQueue pq = localPrintServer.GetPrintQueue(printName); pq.Refresh(); PrintJobInfoCollection allPrintJobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo printJob in allPrintJobs) { printJob.Cancel(); } }
private void buttonDelJob_Click(object sender, EventArgs e) { string psName = ""; PrintServer _ps = new PrintServer();//(@"\\" + psName); PrintQueueCollection _psAllQueues = _ps.GetPrintQueues(); StringBuilder prnStr = new StringBuilder(); string jobList = ""; foreach (PrintQueue pq in _psAllQueues) { try { pq.Refresh(); //_pq.IsProcessing(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { // delete jobs when in error status if (job.IsInError && !job.IsRestarted && !job.IsDeleting) { job.Cancel(); prnStr.Append("\r\nDelete Job: "); prnStr.Append(pq.Name); prnStr.Append(" : "); prnStr.Append(pq.Location); prnStr.Append("\r\n"); prnStr.Append(job.JobName); prnStr.Append(" ID: "); prnStr.Append(job.JobIdentifier); prnStr.Append(" ID: "); prnStr.Append(job.NumberOfPagesPrinted); prnStr.Append("/"); prnStr.Append(job.NumberOfPages); prnStr.Append(" st:"); prnStr.Append(job.JobStatus.ToString()); prnStr.Append("\r\n-------------------------------------\r\n"); } } } catch (Exception ex) { string sEvent = pq.Name + " : " + ex.Message; } } this.textBox1.Text = prnStr.ToString() + jobList; }
public static PrintSystemJobInfo[] PrinterInfo(String printerName) { PrinterSettings printerSettings = new PrinterSettings { PrinterName = printerName }; if (!printerSettings.IsValid) { printerName = (new PrinterSettings()).PrinterName; //fallback to default printer } PrintJobInfoCollection jobs = Methods.GetPrintQueue(printerName) .GetPrintJobInfoCollection(); return(jobs.ToArray()); }
private int Wait_Ticket_Poll(string _ptr_device) { LocalPrintServer localPrintServer = new LocalPrintServer(); PrintQueue printQueue = localPrintServer.GetPrintQueue(_ptr_device); PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection(); if (printQueue.NumberOfJobs > 0) { if (printQueue.IsPrinting) { return(2); } return(1); } return(0); }
internal static PrinterState CheckPrinterQueue(string printerName) { //List<PrintJobStatus> prints = new List<PrintJobStatus>(); if (ConfigurationManager.AppSettings["Mode"] == "Diagnostic") { logger.Log(NLog.LogLevel.Info, "Inside CheckPrinterQueue function"); } PrinterState pstate = new PrinterState(); var printServer = new PrintServer(); var myPrintQueues = printServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }); foreach (PrintQueue pq in myPrintQueues) { pq.Refresh(); if (!pq.Name.ToLower().Contains(printerName.ToLower())) { continue; } PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { if (job.JobStatus == PrintJobStatus.PaperOut || job.JobStatus == PrintJobStatus.UserIntervention || job.JobStatus == PrintJobStatus.Offline || job.JobStatus == PrintJobStatus.Error || job.JobStatus == PrintJobStatus.Blocked) { pstate.alert = true; pstate.status = job.JobStatus; } else { pstate.alert = false; pstate.status = job.JobStatus; } //var aux = job; //Check job status here //job.JobStatus } // end for each print job } // end for each print queue return(pstate); }
/// <summary> /// 清理打印机队列中的JOb /// </summary> public void ClearJobs() { //清空打印机里残留的队列 PrintServer ps = new PrintServer(); PrintQueue queue = ps.GetPrintQueue(ConfigurationManager.AppSettings["printer"]); queue.Refresh(); PrintJobInfoCollection allPrintJobs = queue.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo printJob in allPrintJobs) { printJob.Cancel(); } //释放资源 ps.Dispose(); queue.Dispose(); allPrintJobs.Dispose(); }
/// <summary> /// Check Printqueue Status /// </summary> /// <param name="second">จำนวนระยะเวลา (หน่วยวินาที) ที่มี queue ค้างอยู่ใน printer นั้นๆ</param> /// <returns>จำนวน queue ที่เกินเวลาที่กำหนดไว้</returns> public static int CheckPrintQueueStatus(int?second) { try { if (second == null) { second = 7; } int ret = 0; using (PrintServer server = new PrintServer()) { foreach (PrintQueue pq in server.GetPrintQueues()) { if (pq.FullName.Trim().ToLower() != "CUSTOM TG2480-H".ToLower()) { continue; } pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { // Since the user may not be able to articulate which job is problematic, // present information about each job the user has submitted. //Console.WriteLine((DateTime.UtcNow - job.TimeJobSubmitted).TotalSeconds); if ((DateTime.UtcNow - job.TimeJobSubmitted).TotalSeconds > second) { ret++; } } // end for each p } } return(ret); } catch (Exception ex) { throw ex; } }
// This is the method to run when the timer is raised. private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) { try { PrintServer ps = new PrintServer(PrintSystemDesiredAccess.None); PrintQueueCollection pqc = ps.GetPrintQueues(); foreach (PrintQueue pq in pqc) { pq.Refresh(); if (pq.NumberOfJobs != 0) { PrintJobInfoCollection pjic = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo v in pjic) { DateTime dt = DateTime.UtcNow; TimeSpan ts = (dt - v.TimeJobSubmitted); int ms = (int)ts.TotalMilliseconds; if (ms > 7000) { ServiceController sc = new ServiceController("Spooler"); if (sc.CanStop) { sc.Stop(); } while (sc.Status == ServiceControllerStatus.Running) { sc.Refresh(); } sc.Start(); } } } } } catch { } }
public string GetQueue() { StringBuilder jobList = new StringBuilder("Черга друку"); LocalPrintServer ps = new LocalPrintServer(); // Get the default print queue //PrintQueue pq = ps.DefaultPrintQueue; foreach (PrintQueue pq in ps.GetPrintQueues()) { jobList.Append("\n" + pq.FullName); pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); jobList.Append($"\n\tQueue:{pq.Name} \tLocation:{ pq.Location}"); foreach (PrintSystemJobInfo job in jobs) { jobList.Append($"\nJob: {job.JobName} ID: {job.JobIdentifier} Document Name: {job.Name} Page:{job.NumberOfPages} Time:{job.TimeJobSubmitted}"); } } return(jobList.ToString()); }
public bool Printer_Poll(string _ptr_device) { if (string.IsNullOrEmpty(_ptr_device)) { return(false); } LocalPrintServer localPrintServer = new LocalPrintServer(); PrintQueue printQueue = localPrintServer.GetPrintQueue(_ptr_device); PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection(); if (printQueue.NumberOfJobs > 0) { if (printQueue.IsPrinting) { return(true); } return(false); } return(false); }
/// <summary> /// Check Printqueue Status /// </summary> /// <param name="second">จำนวนระยะเวลา (หน่วยวินาที) ที่มี queue ค้างอยู่ใน printer นั้นๆ</param> /// <returns>จำนวน queue ที่เกินเวลาที่กำหนดไว้</returns> public virtual int CheckPrintQueueStatus(int?second) { try { if (second == null) { second = 7; } int ret = 0; PrintServer server = new PrintServer(); foreach (PrintQueue pq in server.GetPrintQueues()) { if (pq.FullName.Trim().ToLower() != deviceManagerName.Trim().ToLower()) { continue; } pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { // Since the user may not be able to articulate which job is problematic, // present information about each job the user has submitted. //Console.WriteLine((DateTime.UtcNow - job.TimeJobSubmitted).TotalSeconds); if ((DateTime.UtcNow - job.TimeJobSubmitted).TotalSeconds > second) { ret++; } }// end for each p } return(ret); } catch (Exception ex) { throw new RMSAppException(this, "0500", "CheckPrintQueueStatus failed. " + ex.Message, ex, false); } }
//Funciona, pero dependiendo de la impresora sólo muestra que está imprimiendo aunque la impresora no tenga papel, //no tenga tinta, etc. porque ya lo muestra con los drivers propios en vez de mostrarlos en la cola de impresión. /// <summary> /// Método que accede a la cola de impresión de Windows y recoge un trabajo que envía a Trabajos() /// </summary> /// <returns></returns> public string impCheck() { estadoActualImpresora = ""; LocalPrintServer printServer = new LocalPrintServer(); PrintQueueCollection printQueues = printServer.GetPrintQueues(); foreach (PrintQueue pq in printQueues) { pq.Refresh(); PrintJobInfoCollection pCollection = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo trabajo in pCollection) { trabajo.Refresh(); if (Trabajos(trabajo)) { timer.Change(Timeout.Infinite, Timeout.Infinite); } } } return(estadoActualImpresora); }
private static void TestPrintingStatus() { PrintServer server = new PrintServer(); foreach (PrintQueue pq in server.GetPrintQueues()) { if (pq.FullName != "Brother MFC-7450 Printer") { continue; } pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { // Since the user may not be able to articulate which job is problematic, // present information about each job the user has submitted. Console.WriteLine((DateTime.UtcNow - job.TimeJobSubmitted).TotalSeconds); } // end for each p } }
public string GetQueue() { string jobList = ""; LocalPrintServer ps = new LocalPrintServer(); // Get the default print queue PrintQueue pq = ps.DefaultPrintQueue; // foreach (PrintQueue pq in myPrintQueues) // { pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { jobList = jobList + "\n\tQueue:" + pq.Name; jobList = jobList + "\n\tLocation:" + pq.Location; jobList = jobList + "\n\t\tJob: " + job.JobName + " ID: " + job.JobIdentifier; }// end for each print job // }// end for e return(jobList); }
internal static void AbortPrinting() { if (ConfigurationManager.AppSettings["Mode"] == "Diagnostic") { logger.Log(NLog.LogLevel.Info, "Inside Abort printing function"); } //List<PrintJobStatus> prints = new List<PrintJobStatus>(); PrinterState pstate = new PrinterState(); var printServer = new PrintServer(); var myPrintQueues = printServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }); foreach (PrintQueue pq in myPrintQueues) { pq.Refresh(); //if (!pq.Name.ToLower().Contains(printerName.ToLower())) continue; PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { job.Cancel(); } // end for each print job } // end for each print queue }
private int GetNumberOfPrintJobs(string dep) { LocalPrintServer server = new LocalPrintServer(); PrintQueueCollection queueCollection = server.GetPrintQueues(); PrintQueue printQueue = null; foreach (PrintQueue pq in queueCollection) { if (pq.FullName.Equals(dep)) { printQueue = pq; } } int numberOfJobs = 0; if (printQueue != null) { numberOfJobs = printQueue.NumberOfJobs; } string jobList = null; foreach (PrintQueue pq in queueCollection) { pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { // Since the user may not be able to articulate which job is problematic, // present information about each job the user has submitted. jobList = jobList + "\n\tQueue:" + pq.Name; jobList = jobList + "\n\tLocation:" + pq.Location; jobList = jobList + "\n\t\tJob: " + job.JobName + " ID: " + job.JobIdentifier; } // end for each print job } // end for each print queue Console.Write(jobList); return(numberOfJobs); }
private bool Print_Reset(string _ptr_device) { if (string.IsNullOrEmpty(_ptr_device)) { return(false); } if (!Exist_Printer(_ptr_device)) { return(false); } LocalPrintServer localPrintServer = new LocalPrintServer(); PrintQueue printQueue = localPrintServer.GetPrintQueue(_ptr_device); printQueue.Refresh(); if (printQueue.NumberOfJobs > 0) { PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo item in printJobInfoCollection) { item.Cancel(); } } return(true); }
public async Task <bool> PrinterQueuePurge() { await Task.Delay(1000); bool purgeSucceeded = true; try { PrintServer printServer = new PrintServer(); PrintQueueCollection printQueues = printServer.GetPrintQueues(); foreach (PrintQueue pq in printQueues) { if (pq.NumberOfJobs > 0) { pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); try { pq.Purge(); } catch (Exception) { purgeSucceeded = false; } } } } catch (Exception) { purgeSucceeded = false; } return(purgeSucceeded); }
static void Main(string[] args) { // Obtain a list of print servers. Console.Write("Enter path and file name of CRLF-delimited list of print servers" + "\n(press Return for default \"C:\\PrintServers.txt\"): "); String pathToListOfPrintServers = Console.ReadLine(); if (pathToListOfPrintServers == "") { pathToListOfPrintServers = @"C:\PrintServers.txt"; } StreamReader fileOfPrintServers = new StreamReader(pathToListOfPrintServers); // Obtain the username of the person with the problematic print job. Console.Write("\nEnter username of person that submitted print job" + "\n(press Return for the current user {0}: ", Environment.UserName); String userName = Console.ReadLine(); if (userName == "") { userName = Environment.UserName; } // Prompt user to determine the method that will be used to read the queue status. Console.Write("\nEnter \"Y\" to check the problematic job using its JobStatus attributes." + "\nOtherwise, press Return and the job will be checked using its specific properties: "); String useAttributesResponse = Console.ReadLine(); // Create list of all jobs submitted by user. String line; Boolean atLeastOne = false; String jobList = "\n\nAll print jobs submitted by the user are listed here:\n\n"; while ((line = fileOfPrintServers.ReadLine()) != null) { PrintServer myPS = new PrintServer(line, PrintSystemDesiredAccess.AdministrateServer); PrintQueueCollection myPrintQueues = myPS.GetPrintQueues(); //<SnippetEnumerateJobsInQueues> foreach (PrintQueue pq in myPrintQueues) { pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { // Since the user may not be able to articulate which job is problematic, // present information about each job the user has submitted. if (job.Submitter == userName) { atLeastOne = true; jobList = jobList + "\nServer:" + line; jobList = jobList + "\n\tQueue:" + pq.Name; jobList = jobList + "\n\tLocation:" + pq.Location; jobList = jobList + "\n\t\tJob: " + job.JobName + " ID: " + job.JobIdentifier; } } // end for each print job } // end for each print queue //</SnippetEnumerateJobsInQueues> } // end while list of print servers is not yet exhausted fileOfPrintServers.Close(); if (!atLeastOne) { jobList = "\n\nNo jobs submitted by " + userName + " were found.\n\n"; Console.WriteLine(jobList); } else { jobList = jobList + "\n\nIf multiple jobs are listed, use the information provided" + " above and by the user to identify the job needing diagnosis.\n\n"; Console.WriteLine(jobList); //<SnippetIdentifyAndDiagnoseProblematicJob> // When the problematic print job has been identified, enter information about it. Console.Write("\nEnter the print server hosting the job (including leading slashes \\\\): " + "\n(press Return for the current computer \\\\{0}): ", Environment.MachineName); String pServer = Console.ReadLine(); if (pServer == "") { pServer = "\\\\" + Environment.MachineName; } Console.Write("\nEnter the print queue hosting the job: "); String pQueue = Console.ReadLine(); Console.Write("\nEnter the job ID: "); Int16 jobID = Convert.ToInt16(Console.ReadLine()); // Create objects to represent the server, queue, and print job. PrintServer hostingServer = new PrintServer(pServer, PrintSystemDesiredAccess.AdministrateServer); PrintQueue hostingQueue = new PrintQueue(hostingServer, pQueue, PrintSystemDesiredAccess.AdministratePrinter); PrintSystemJobInfo theJob = hostingQueue.GetJob(jobID); if (useAttributesResponse == "Y") { TroubleSpotter.SpotTroubleUsingJobAttributes(theJob); // TroubleSpotter class is defined in the complete example. } else { TroubleSpotter.SpotTroubleUsingProperties(theJob); } TroubleSpotter.ReportQueueAndJobAvailability(theJob); //</SnippetIdentifyAndDiagnoseProblematicJob> }// end else at least one job was submitted by user // End the program Console.WriteLine("\nPress Return to end."); Console.ReadLine(); } // end Main
public static List <Dictionary <string, object> > GetPrintQueue() { Dictionary <string, object> properties = new Dictionary <string, object>(); Dictionary <string, object> jobs = new Dictionary <string, object>(); List <Dictionary <string, object> > printers = new List <Dictionary <string, object> >(); List <object> jobsQueue = new List <object>(); EnumeratedPrintQueueTypes[] enumerationFlags = { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Shared }; LocalPrintServer printServer = new LocalPrintServer(); //Use the enumerationFlags to filter out unwanted print queues PrintQueueCollection printQueuesOnLocalServer = printServer.GetPrintQueues(enumerationFlags); foreach (PrintQueue printeQueue in printQueuesOnLocalServer) { properties = new Dictionary <string, object>(); printeQueue.Refresh(); PrintJobInfoCollection jobsQueued = printeQueue.GetPrintJobInfoCollection(); jobsQueue.Clear(); foreach (PrintSystemJobInfo job in jobsQueued) { jobs = new Dictionary <string, object>(); // Since the user may not be able to articulate which job is problematic, // present information about each job the user has submitted. jobs.Add("Job", job.JobName); jobs.Add("Name", job.Name); jobs.Add("ID", job.JobIdentifier); jobs.Add("Priority", job.PositionInPrintQueue); jobs.Add("SummitedOn", DateTime.Parse(job.TimeJobSubmitted.ToString()).ToString("yyyy-MM-dd hh:mm:ss")); jobs.Add("IsPaused", job.IsPaused); jobs.Add("IsPrinting", job.IsPrinting); jobs.Add("IsDeleting", job.IsDeleting); jobs.Add("IsInError", job.IsInError); jobsQueue.Add(jobs); }// end for each print job properties.Add("Printer", printeQueue.Name); properties.Add("Location", printeQueue.Location); properties.Add("NumberOfJobs", printeQueue.NumberOfJobs); properties.Add("Jobs", jobsQueue); properties.Add("QueueAttributes", printeQueue.QueueAttributes); properties.Add("QueueDriver", printeQueue.QueueDriver.Name); properties.Add("QueuePort", printeQueue.QueuePort.Name); properties.Add("QueuePrintProcessor", printeQueue.QueuePrintProcessor.Name); properties.Add("QueueStatus", printeQueue.QueueStatus); properties.Add("IsDirect", printeQueue.IsDirect); properties.Add("PrintingIsCancelled", printeQueue.PrintingIsCancelled); properties.Add("IsRawOnlyEnabled", printeQueue.IsRawOnlyEnabled); properties.Add("IsWaiting", printeQueue.IsWaiting); properties.Add("IsQueued", printeQueue.IsQueued); properties.Add("IsProcessing", printeQueue.IsProcessing); properties.Add("IsPrinting", printeQueue.IsPrinting); properties.Add("IsBusy", printeQueue.IsBusy); properties.Add("IsNotAvailable", printeQueue.IsNotAvailable); properties.Add("IsOffline", printeQueue.IsOffline); properties.Add("IsPaused", printeQueue.IsPaused); properties.Add("IsIOActive", printeQueue.IsIOActive); properties.Add("IsOutOfPaper", printeQueue.IsOutOfPaper); properties.Add("IsOutOfMemory", printeQueue.IsOutOfMemory); properties.Add("IsPaperJammed", printeQueue.IsPaperJammed); properties.Add("IsManualFeedRequired", printeQueue.IsManualFeedRequired); properties.Add("IsDoorOpened", printeQueue.IsDoorOpened); properties.Add("IsTonerLow", printeQueue.IsTonerLow); properties.Add("IsOutputBinFull", printeQueue.IsOutputBinFull); properties.Add("NeedUserIntervention", printeQueue.NeedUserIntervention); properties.Add("IsInError", printeQueue.IsInError); printers.Add(properties); } return(printers); }
private void Hodoo_SIP30C(DataTable dt, string BizCode, bool IsNewData) { DataTable mdt = dt.Copy(); for (int i = 0; i < mdt.Rows.Count; i++) { #region 카드발급프린터 대기열 작업완료시까지 기다림 using (LocalPrintServer localPrinterServer = new LocalPrintServer()) { PrintQueue printQueue = localPrinterServer.GetPrintQueue(PrintName); if (printQueue.NumberOfJobs > 0) { MessageBox.Show("인쇄 대기인 문서가 있습니다."); return; } localPrinterServer.Dispose(); } #endregion rPrintData = null; rPrintData = mdt.Rows[i]; //일반(사진) info.xpos = Convert.ToInt32(rPrintData["X_POS"].ToString().Trim()); info.ypos = Convert.ToInt32(rPrintData["Y_POS"].ToString().Trim()); info.xsize = Convert.ToInt32(rPrintData["X_SIZE"].ToString().Trim()); info.ysize = Convert.ToInt32(rPrintData["Y_SIZE"].ToString().Trim()); //일반(승산)-카드프린터 클래스 생성 info.bizcode = BizCode; info.membername = rPrintData["MEMBER_NAME_KOR"].ToString().Trim(); info.memberno = rPrintData["MEMBER_NO"].ToString().Trim(); info.memberphoto = rPrintData["PHOTO"] == DBNull.Value ? null : (Byte[])rPrintData["PHOTO"]; info.cardissueno = rPrintData["CARD_ISSUE_NO"].ToString().Trim(); //예외(승산)-카드프린터 클래스 생성 if (info.bizcode == "23") { info.commodity_accountcode = rPrintData["COMMODITY_ACCOUNT_CODE"].ToString().Trim(); info.gccode = rPrintData["GC_CODE"].ToString().Trim(); info.memberno = string.Format("{0}-{1}{2}", info.memberno.Trim().Substring(2, 6) , info.memberno.Trim().Substring(8, 2) , info.commodity_accountcode.Trim()); if (info.membername.Length == 3) { info.membername = String.Format("{0} {1} {2}", info.membername.Substring(0, 1), info.membername.Substring(1, 1), info.membername.Substring(2, 1)); } } //예외(대천)-카드프린터 클래스 생성 if (info.bizcode == "22") { info.registercode = rPrintData["REGISTER_CODE"].ToString().Trim(); info.printdate = DateTime.Today.ToString("yyyy.MM.dd"); if (info.memberno.Length == 10) { info.memberno = String.Format("{0}-{1}-{2}-{3}", info.memberno.Substring(0, 2), info.memberno.Substring(2, 2), info.memberno.Substring(4, 4), info.memberno.Substring(8, 2)); } //기명=N if (info.membername.Length == 3 && info.registercode == "N") { info.membername = String.Format("{0} {1} {2}", info.membername.Substring(0, 1), info.membername.Substring(1, 1), info.membername.Substring(2, 1)); } //무기명=U else { string strmemberName = info.membername; if (info.membername.Length > 11) { strmemberName = info.membername.Substring(0, 11); } info.printdate = info.printdate + (info.membername.Equals("") ? "" : " " + strmemberName); } } //예외(엘도라도)-카드프린터 클래스 생성 if (info.bizcode == "51") { info.membername = rPrintData["MEMBER_NAME_ENG"].ToString().Trim(); } //일반(대천) - 마그네틱엔코딩 info.mstrack1 = ""; info.mstrack2 = String.Format("{0}={1}", rPrintData["CARD_ISSUE_NO"].ToString().Trim(), rPrintData["MEMBER_NO"].ToString().Trim()); info.mstrack3 = ""; //예외(승산) - 마그네틱엔코딩 /*설명 : 1.승산 임시회원카드 = track1=골프혜택, track2=회원번호(8), track3="" * 2.승산 임시회원카드 = track1=회원번호(8)골프혜택, track2="", track3="" * 승산 임시회원카드는 정식카드 사용전까지 사용하며, * 정식 마그네틱 저장형식은 추후 협의후 결정(기본 = track2사용, 카드번호(10자리)=회원번호(10자리)) */ if (info.bizcode == "23") { info.mstrack1 = String.Format("{0}{1}", rPrintData["MEMBER_NO"].ToString().Trim().Substring(2, 8), rPrintData["GC_CODE"].ToString().Trim()); //rPrintData["GC_CODE"].ToString().Trim(); info.mstrack2 = ""; //rPrintData["CARD_ISSUE_NO"].ToString().Trim();//"";//String.Format("{0}", rPrintData["MEMBER_NO"].ToString().Trim().Substring(2, 8)); info.mstrack3 = ""; } if (!WriteMagnetic(IsNewData, info.mstrack1, info.mstrack2, info.mstrack3)) { return; } if (IsNewData) { Drawprint(PrintName); } suSender sender = new suSender { BizCode = BizCode, sucMode = IsNewData ? SucessMode.NewData : SucessMode.Magstripe }; bool IsSucess = true; using (LocalPrintServer localPrinterServer1 = new LocalPrintServer()) { PrintQueue printQueue = localPrinterServer1.GetPrintQueue(PrintName); int startTick = Environment.TickCount; bool isTimeOut = false; while (printQueue.NumberOfJobs > 0 & !(isTimeOut)) { printQueue.Refresh(); int currentTick = Environment.TickCount; if (currentTick - startTick > 60000) { isTimeOut = true; } System.Threading.Thread.Sleep(10); Application.DoEvents(); } if (isTimeOut) { PrintJobInfoCollection jobs = printQueue.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { job.Cancel(); } int deleteStateTime = System.Environment.TickCount; string strmsg = "제한시간초과 - 인쇄가 완료되지 못했습니다. "; while ((System.Environment.TickCount - deleteStateTime) < 1000) { printQueue.Refresh(); } if (printQueue.NumberOfJobs > 0) { strmsg += "\n\r인쇄문서가 대기 중 입니다 . \n\r\n\r취소 후 다시 시도 하세요!"; } IsSucess = false; RaiseErrorEvent(new Exception(strmsg)); return; } if (IsSucess) { RaiseDataSucessEvent(sender, rPrintData); } } } }
/// <summary> /// Fonction qui lit les fichier contenu dans le spool d'une imprimante /// </summary> /// <param name="nomIMP">Nom de l'imprimante.</param> public void lectureSpooler(string nomIMP) { string typeDoc = ""; listFichierSpool.Clear(); // Je vide ma liste avant de débuter une nouvelle lecture string[] files; // pour avoir les noms des fichiers et sous-répertoires files = Directory.GetFiles("C:\\Windows\\System32\\spool\\PRINTERS", "*.SPL"); //Repertoire du spool Windows PrintServer myPrintServer = new PrintServer(); PrintQueueCollection myPrintQueues = myPrintServer.GetPrintQueues(); bool supOk = false; string nomDoc = ""; string profil = ""; foreach (PrintQueue pq in myPrintQueues) //Analyse du spool du pc (Dossier Windows\System32\spool\PRINTERS) { if (pq.FullName == nomIMP) //Condition sur imprimante qui a créer l'objet Imprimante { try { int filecount = files.GetUpperBound(0) + 1; //Nombre de fichier contenu dans le spool for (int i = 0; i < filecount; i++) //Nombre de fichier dans dossier spool { DateTime temp = Directory.GetLastWriteTime(files[i]).AddMilliseconds(-Directory.GetLastWriteTime(files[i]).Millisecond); //Décalage de lecture des documents DateTime actuelle = DateTime.Now; actuelle = DateTime.Now.AddMilliseconds(-actuelle.Millisecond); string nom_spool = ""; string nomFichier = System.IO.Path.GetFileName(files[i]); //Récuperation du nom du fichier lu string sourceFile = System.IO.Path.Combine(@"C:\Windows\System32\spool\PRINTERS", nomFichier); //C:\Windows\System32\spool\PRINTERS string destFile = System.IO.Path.Combine(cheminDocFinaux + @"\Copie spool", nomFichier); string[] files2 = Directory.GetFiles(cheminDocFinaux + @"\Copie spool", "*SPL"); //Tableau contenant les fichier SPL int file2count = files2.GetUpperBound(0) + 1; int emplacementDoc = 0; if (temp.Second != actuelle.Second) //Condition tempo de temps d'analyse des docs { for (int j = 0; j < filecount; j++) //Analyse existant dans fichier de destination { if (System.IO.File.Exists(cheminDocFinaux + @"\Copie spool\" + nomFichier)) //Condition d'existance { System.IO.File.Copy(sourceFile, destFile, true); supOk = true; emplacementDoc = j; } else { System.IO.File.Copy(sourceFile, destFile, true); //Si le fichier n'existe pas, je le copie afin de pouvoir le traiter par la suite supOk = true; emplacementDoc = j; } } nbDoc = 1; string[] text = System.IO.File.ReadAllLines(files[i], Encoding.Default); //string patternLectFalse = "(%-12345X@PJL JOB NAME|\\210-SERVIMP|&l26A)";//Premier caractère qui apparait sur les documents en cours d'impression string patternLectFalse = "(%-12345X@PJL|\\210-SERVIMP|&l26A)"; //Premier caractère qui apparait sur les documents en cours d'impression //"%-12345X@PJL SET RENDERMODE=COLOR" string sPattern = "<Spool>"; string sPatternTypeDoc = "<Document_type>"; bool patternOK = true; bool patternOK2 = false; bool découpageOK = true; int controle = 0; int test = 0; string sPatternTypeDoc2 = "<Document type=\"DOC_CLIENT\" doc=\"FACTURE "; string sPatternTypeDoc3 = "<Document type=\"DOC_CLIENT\" doc=\"RELEVE\""; StreamWriter sr = null; foreach (string s in text) //Analyse ligne du document actuel { controle++; //Premier tri si le document lu est en fait l'impression final d'un doc déjà traité, ne pas le lire et passer au suivant if ((System.Text.RegularExpressions.Regex.IsMatch(s, patternLectFalse, System.Text.RegularExpressions.RegexOptions.IgnoreCase) == false) && patternOK == true) { if (System.Text.RegularExpressions.Regex.IsMatch(s, "<Document type=\"DOC_CLIENT\" doc=\"FACTURE ", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { découpageOK = false; sr = new StreamWriter(cheminDocFinaux + @"\Copie spool\tempo" + test + ".SPL", false, Encoding.GetEncoding("iso-8859-1")); } if (System.Text.RegularExpressions.Regex.IsMatch(s, "<Document type=\"DOC_CLIENT\" doc=\"RELEVE\"", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { découpageOK = false; sr = new StreamWriter(cheminDocFinaux + @"\Copie spool\tempo" + test + ".SPL", false, Encoding.GetEncoding("iso-8859-1")); } if (System.Text.RegularExpressions.Regex.IsMatch(s, "</Document>", System.Text.RegularExpressions.RegexOptions.IgnoreCase) && découpageOK == false) { sr.WriteLine(s); découpageOK = true; } if (découpageOK == false) { sr.WriteLine(s); } if ((découpageOK == true) && (sr != null)) { sr.Close(); test++; } //Regex type de document if (System.Text.RegularExpressions.Regex.IsMatch(s, sPatternTypeDoc2, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { typeDoc = "FACTURE"; patternOK2 = true; } else { if (System.Text.RegularExpressions.Regex.IsMatch(s, sPatternTypeDoc, System.Text.RegularExpressions.RegexOptions.IgnoreCase) && patternOK2 == false) { typeDoc = s.Substring(24, (s.IndexOf(']') - 24)); } } if (System.Text.RegularExpressions.Regex.IsMatch(s, sPatternTypeDoc3, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { typeDoc = "RELEVE"; patternOK2 = true; } else { if (System.Text.RegularExpressions.Regex.IsMatch(s, sPatternTypeDoc, System.Text.RegularExpressions.RegexOptions.IgnoreCase) && patternOK2 == false) { typeDoc = s.Substring(24, (s.IndexOf(']') - 24)); } } //Regex balise <spool>/ prévoir changement du regex dans les fichiers de conf if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { nom_spool = s.Substring(16, 10); if (supOk == true) //Condition si copie ok donc suppression { System.IO.File.Delete(sourceFile); PrintServer myPrintServer2 = new PrintServer(); PrintQueueCollection myPrintQueues2 = myPrintServer.GetPrintQueues(); foreach (PrintQueue pq2 in myPrintQueues2) { pq2.Refresh(); PrintJobInfoCollection jobs = pq2.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) //Lecture des docs dans file d'attente { if (job.Name == nom_spool) { //Condition nom du doc de la file job.Cancel(); profil = job.Submitter; break; } } } } } } else { patternOK = false; typeDoc = null; System.IO.File.Delete(sourceFile); patternOK2 = false; } //Si tout est OK je supprime le fichier copier nomDoc = nomFichier; } cheminDoc = destFile; if ((Environment.UserName != profil) && profil != "") //TEST sur le nom du profil { if (test != 0) { int compteur = 0; while (compteur < (test - 3)) { cheminDoc = cheminDocFinaux + @"\Copie spool\tempo" + compteur + ".SPL"; destFile = cheminDocFinaux + @"\Copie spool\tempo" + compteur + ".SPL"; switch (typeDoc.TrimStart()) { case "DEVIS": Devis dev = new Devis(); dev.lectureDevis(cheminDoc, profil); break; case "BORDEREAU DE LIVRAISON": BonLivraison BL = new BonLivraison(); BL.lectureBL(cheminDoc, profil); break; case "BON D'ENLEVEMENT": BonLivraison BL2 = new BonLivraison(); BL2.lectureBL(cheminDoc, profil); break; case "BON DE PREPARATION": BonPréparation BP = new BonPréparation(); BP.lectureBP(cheminDoc, profil); break; case "COMMANDE ADHERENT": AccuseReception AR = new AccuseReception(); AR.lectureAR(cheminDoc, profil); break; case "BON DE COMMANDE FOURNISSEUR": CommandeFournisseur CF = new CommandeFournisseur(); CF.lectureCF(cheminDoc, profil); break; case "RETOUR FOURNISSEUR": CommandeFournisseur rCF = new CommandeFournisseur(); rCF.lectureCF(cheminDoc, profil); break; case "AVOIR": BonLivraison BL3 = new BonLivraison(); BL3.lectureBL(cheminDoc, profil); break; case "FACTURE": Facturation FA = new Facturation(); FA.lectureFA(cheminDoc, profil); break; case "RELEVE": Releve R = new Releve(); R.lectureR(cheminDoc, profil); break; case null: break; } compteur++; System.IO.File.Delete(destFile); } } else { switch (typeDoc.TrimStart()) { case "DEVIS": Devis dev = new Devis(); dev.lectureDevis(cheminDoc, profil); break; case "BORDEREAU DE LIVRAISON": BonLivraison BL = new BonLivraison(); BL.lectureBL(cheminDoc, profil); break; case "BON D'ENLEVEMENT": BonLivraison BL2 = new BonLivraison(); BL2.lectureBL(cheminDoc, profil); break; case "BON DE PREPARATION": BonPréparation BP = new BonPréparation(); BP.lectureBP(cheminDoc, profil); break; case "COMMANDE ADHERENT": AccuseReception AR = new AccuseReception(); AR.lectureAR(cheminDoc, profil); break; case "BON DE COMMANDE FOURNISSEUR": CommandeFournisseur CF = new CommandeFournisseur(); CF.lectureCF(cheminDoc, profil); break; case "RETOUR FOURNISSEUR": CommandeFournisseur rCF = new CommandeFournisseur(); rCF.lectureCF(cheminDoc, profil); break; case "AVOIR": BonLivraison BL3 = new BonLivraison(); BL3.lectureBL(cheminDoc, profil); break; case "FACTURE": Facturation FA = new Facturation(); FA.lectureFA(cheminDoc, profil); break; case "RELEVE": Releve R = new Releve(); R.lectureR(cheminDoc, profil); break; case null: break; } System.IO.File.Delete(destFile); } } } else { System.IO.File.Delete(destFile); break; } supOk = false; } } catch (Exception e) { //Inscrit dans un fichier les differente erreur LogHelper.WriteToFile(e.Message, "Imprimante " + nomDoc); } } } }