/// <summary> /// Shows advanced settings window. /// </summary> /// <param name="owner">owner</param> public void ShowAdvancedSettings(Window owner) { try { // get chosen printer by color setting Printer pr = GetChosenPrinterWithSettings(PrintWithColor); if (pr == null) { return; } UISettingsExtractor extractor = new UISettingsExtractor(ChosenPrinter.Name, DesktopHelper.GetDesktopWindow()); extractor.Start(); MainController.Singleton.ShowAdvancedPrinterSettings(new WindowInteropHelper(owner).Handle, ChosenPrinter.Name, ref PrinterSettings); extractor.Stop(); PrintBooklet = extractor.Booklet; LogHelper.LogDebug(PrintBooklet); pr.Settings = PrinterSettings; SetByPrinterSettings(); } catch (Exception ex) { WPFNotifier.DebugError(ex); } }
/// <summary> /// Updates available printers /// </summary> /// <returns>available printers</returns> public Printers UpdateAvailablePrinters() { LogHelper.LogDebug(); try { _availablePrinters = null; // just retrieve new data var xxx = AvailablePrinters; LogHelper.LogDebug("HasAvailablePrinters : " + HasAvailablePrinters); // change (real) printers of local print event watcher if (localPrintEventWatcher != null) { localPrintEventWatcher.PrintersToPauseAndShow = new List <string>(); // check if there are available printers if (HasAvailablePrinters) { LogHelper.LogDebug("AvailablePrinters : " + AvailablePrinters.NamesInSystem.Count); // add (real) printers localPrintEventWatcher.PrintersToPauseAndShow.AddRange(AvailablePrinters.NamesInSystem); } } return(_availablePrinters); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(null); } }
/// Dispose #region Dispose /// <summary> /// Disposes data /// </summary> public void Dispose() { // get rid of event watcher if (_eventWatcher != null) { try { _eventWatcher.EventArrived -= mewPrintJobs_JobArrived; _eventWatcher.Stop(); _eventWatcher.Dispose(); _eventWatcher = null; } catch (Exception ex) { WPFNotifier.DebugError(ex); } } // get rid of management scope if (managementScope != null) { try { managementScope = null; } catch (Exception ex) { WPFNotifier.DebugError(ex); } } }
/// <summary> /// Gets value from the postscript file line /// </summary> /// <param name="line">postscript file line</param> /// <returns>value from the postscript file line</returns> private static string GetLineValue(string line) { try { // find semicolon int index = line.IndexOf(':'); if (index > 0) { // find star int index2 = line.LastIndexOf('*'); if (index2 > index) { // find first space after star int index3 = line.IndexOf(' ', index2); if (index3 > index2) { // extract starred value return(line.Substring(index3).Trim()); } } else { // extract simple value return(line.Substring(index + 1).Trim()); } } } catch (Exception ex) { WPFNotifier.DebugError(ex); } return(null); }
/// <summary> /// Gets value from the postscript file line /// </summary> /// <param name="line">postscript file line</param> /// <returns>value from the postscript file line</returns> private static string GetLineValue2(string line) { try { int index = line.IndexOf('='); if (index > 0) { int index2 = line.IndexOf('"', index + 1) + 1; if (index2 > index) { int index3 = line.IndexOf('"', index2); if (index3 > index2) { // extract value return(line.Substring(index2, index3 - index2).Trim()); } } else { // extract simple value return(line.Substring(index + 1).Trim()); } } } catch (Exception ex) { WPFNotifier.DebugError(ex); } return(null); }
/// <summary> /// Gets proper library /// </summary> /// <returns>path to the library</returns> private static string GetLib() { try { string path = getLib(true); if (File.Exists(path)) { return(path); } path = getLib(false); if (File.Exists(path)) { return(path); } path = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), getLib(false)); if (File.Exists(path)) { return(path); } throw new ArgumentNullException("File not found! " + Environment.NewLine + Application.ExecutablePath); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(null); } }
/// Post #region Post /// <summary> /// Initiates post request /// </summary> /// <param name="url"></param> /// <returns></returns> public static IRestResponse Post(string url, Dictionary <string, string> queryParameters = null) { try { string req = url; if (queryParameters != null && queryParameters.Count > 0) { req += "?" + queryParameters.GetAsQueryString(); } LastCall = req; LogHelper.LogDebug(new Uri(req).AbsoluteUri); RestClient client = new RestClient(new Uri(req)); RestRequest request = new RestRequest(Method.POST); request.Timeout = 5000; request.AddParameter("undefined", "{}", ParameterType.RequestBody); IRestResponse response = client.Execute(request); return(response); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(null); } }
/// Print #region Print /// <summary> /// Prints file with specified printer and settings /// </summary> /// <param name="fileName">file name</param> /// <param name="printer">printer settings</param> public static void Print(string fileName, string documentName, PrinterSettings printer, PostScriptMetaData data) { if (String.IsNullOrWhiteSpace(fileName)) { return; } if (printer == null) { return; } if (data == null) { return; } try { // check the existence of the file if (!File.Exists(fileName)) { return; } // get file format SupportedPrintFormat format = GetFileFormat(fileName); string newFileName = fileName; // if Postscript file if (format == SupportedPrintFormat.PS) { newFileName = fileName + ".pdf"; // convert to .pdf GhostScriptHelper.ConvertPStoPDF(fileName, newFileName); } // create corresponding print job title PrintJobTitle title = new PrintJobTitle(printer.PrinterName, documentName, Environment.UserName, Environment.MachineName, -1); // skip this title SkipMethod(title); // print document if (PDFHelper.Print(printer, newFileName, documentName, Environment.UserName, Environment.MachineName)) { // add title watcher AddWatcher(title); // log printed data LogPrint(ConfigData.FilePath_PrintLog, documentName, printer, data.NumberOfPages); } } catch (Exception ex) { WPFNotifier.DebugError(ex); } }
/// HasColor #region HasColor /// <summary> /// Indicates whether the image has color or not /// </summary> /// <param name="image">image to be inspected</param> /// <returns>true if has color; otherwise false</returns> public static bool HasColor(Image image) { try { return(!IsGrayScale(new Bitmap(image))); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(false); } }
/// <summary> /// /// </summary> /// <returns></returns> private MethodInfo[] GetMethods() { try { return((typeof(API)).GetMethods(BindingFlags.Public | BindingFlags.Static)); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(null); } }
/// GetPrinters #region GetPrinters /// <summary> /// Gets printer list from the specified config file /// </summary> /// <param name="fullPath">config file</param> /// <returns>printers</returns> public static Printers GetPrintersFromConfig(string fullPath) { LogHelper.LogDebug(fullPath); if (String.IsNullOrWhiteSpace(fullPath)) { return(null); } try { if (!File.Exists(fullPath)) { return(null); } string data = File.ReadAllText(fullPath); if (String.IsNullOrWhiteSpace(data)) { return(null); } LogHelper.LogDebug("From file: " + data); JArray jArray = JArray.Parse(data); foreach (JObject jObject in jArray.Children <JObject>()) { var workstation = jObject["workstation"]; if (workstation != null) { if (workstation.ToString() == Environment.MachineName) { LogHelper.LogDebug("Printer data found"); return(JsonConvert.DeserializeObject <Printers>(jObject["printers"].ToString())); } } else { return(JsonConvert.DeserializeObject <Printers>(jArray.ToString())); } } } catch (Exception ex) { WPFNotifier.DebugError(ex); } LogHelper.LogDebug("Printer data not found"); return(null); }
/// PrinterIssue #region PrinterIssue /// <summary> /// Sends printer issue if any exist /// </summary> /// <param name="printerName">printer name</param> /// <param name="issue">printer issue</param> public static void PrinterIssue(string machineName, string userName, string printerName, string issue) { try { LogHelper.LogDebug(printerName); var res = API.PrinterIssue(machineName, userName, printerName, issue); LogHelper.LogDebug(res); } catch (Exception ex) { WPFNotifier.DebugError(ex); } }
/// LogPrint #region LogPrint /// <summary> /// Logs print entry data /// </summary> /// <param name="machineName">computer name</param> /// <param name="userName">user name</param> /// <param name="printerName">printer name</param> /// <param name="isColored">is colored?</param> /// <param name="numberOfPrints">number of prints</param> /// <param name="doubleSided">double-sided print</param> public static void LogPrint(string machineName, string userName, string printerName, bool isColored, int numberOfPrints, bool doubleSided) { try { LogHelper.LogDebug(machineName); var res = API.LogPrint(machineName, userName, isColored, numberOfPrints, printerName, doubleSided); LogHelper.LogDebug(res); } catch (Exception ex) { WPFNotifier.DebugError(ex); } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void watcher_CanBeDisposed(object sender, EventArgs e) { PrintJobWatcher w = sender as PrintJobWatcher; if (w != null) { try { this.Remove(w); w.Dispose(); } catch (Exception ex) { WPFNotifier.DebugError(ex); } } }
/// HasColor #region HasColor /// <summary> /// Checks whether the postscript file has color inside /// </summary> /// <param name="psFileName">file to be inspected</param> /// <returns>true if colored; otherwise false</returns> public static bool?HasColor(string psFileName) { if (string.IsNullOrWhiteSpace(psFileName)) { return(null); } LogHelper.LogDebug(); try { if (!File.Exists(psFileName)) { return(null); } string pdfTMPFileName = Path.GetTempFileName() + ".pdf"; // and convert PS file to PDF GhostScriptHelper.ConvertPStoPDF(psFileName, pdfTMPFileName); // find out do PDF has color or not? bool hasColor = GhostScriptHelper.HasColor(pdfTMPFileName); try { File.Delete(pdfTMPFileName); } catch (Exception ex) { LogHelper.Log(ex); } return(hasColor); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(null); } }
/// HasColor #region HasColor /// <summary> /// Determines if the specified file has color /// </summary> /// <param name="fileName">file to be inspected</param> /// <returns>true if has color; otherwise false</returns> public static bool HasColor(string fileName, int desired_x_dpi = 96, int desired_y_dpi = 96) { LogHelper.LogDebug(fileName); try { GhostscriptVersionInfo gsVersion = new GhostscriptVersionInfo(GetLib()); using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer()) { rasterizer.Open(fileName, gsVersion, false); for (int pageNumber = 1; pageNumber <= rasterizer.PageCount; pageNumber++) { try { using (Image img = rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber)) { if (img.HasColor()) { LogHelper.LogDebug("Has Color"); return(true); } } } catch (Exception ex) { LogHelper.LogDebug(ex); } } rasterizer.Close(); } } catch (Exception ex) { WPFNotifier.DebugError(ex); } LogHelper.LogDebug("No Color"); return(false); }
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="printerName"></param> /// <param name="documentName"></param> /// <param name="color"></param> /// <param name="numberOfPrints"></param> /// <param name="duplex"></param> private static void LogPrint(string fileName, string printerName, string documentName, bool color, int numberOfPrints, Duplex duplex) { if (String.IsNullOrWhiteSpace(fileName)) { return; } if (String.IsNullOrWhiteSpace(printerName)) { return; } APIWrapper.LogPrint(Environment.MachineName, Environment.UserName, printerName, color, numberOfPrints, duplex != Duplex.Simplex); try { string path = Path.GetDirectoryName(fileName); if (!string.IsNullOrWhiteSpace(path)) { if (!Directory.Exists(path)) { IO.CreateHiddenDirectory(path, false); } } object[] data = new object[] { Environment.MachineName, Environment.UserName, printerName, documentName, color, duplex, numberOfPrints }; using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write)) { LogHelper.LogDebug(fileName); using (StreamWriter sw = new StreamWriter(fs, Encoding.Unicode)) { sw.WriteLine(data.ToCSV()); } } } catch (Exception ex) { WPFNotifier.DebugError(fileName + " " + ex); } }
/// GetPrinters #region GetPrinters /// <summary> /// Gets list of available printers /// </summary> /// <param name="machineName">computer name</param> /// <returns>list of available printers</returns> public static Printers GetPrinters(string machineName) { try { LogHelper.LogDebug(machineName); string res = API.GetPrinters(machineName); LogHelper.Log(res); if (string.IsNullOrWhiteSpace(res)) { return(null); } return(JsonConvert.DeserializeObject <Printers>(res)); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(null); } }
/// CheckIfCanPrint #region CheckIfCanPrint /// <summary> /// Checks if the user is able to print /// </summary> /// <param name="machineName">computer name</param> /// <param name="userName">user name</param> /// <param name="isColored">is colored?</param> /// <param name="numberOfPrints">number of prints</param> /// <param name="printerName">printer name</param> /// <returns>is user able to print?</returns> public static AllowedToPrintResponse CheckIfCanPrint(string machineName, string userName, bool isColored, int numberOfPrints, string printerName) { try { LogHelper.LogDebug(machineName); var res = API.CheckIfCanPrint(machineName, userName, isColored, numberOfPrints, printerName); LogHelper.LogDebug(res); if (string.IsNullOrWhiteSpace(res)) { return(null); } return(JsonConvert.DeserializeObject <AllowedToPrintResponse>(res)); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(null); } }
/// GetEnvironment #region GetEnvironment /// <summary> /// Gets environment data. /// </summary> /// <returns>environment data</returns> public static object GetEnvironment() { try { string res = API.GetEnvironment(); LogHelper.Log(res); if (string.IsNullOrWhiteSpace(res)) { return(null); } //return null; return(JToken.Parse(res)); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(null); } }
/// Convert #region Convert /// <summary> /// Converts postscript file to pdf /// </summary> /// <param name="psFileName">postscript file name</param> /// <returns>pdf file name</returns> public static void ConvertPStoPDF(string psFileName, string pdfFileName) { if (string.IsNullOrWhiteSpace(psFileName)) { return; } if (string.IsNullOrWhiteSpace(pdfFileName)) { return; } try { GhostscriptProcessor process = CreateProcessor(); process.Process(ConvertPStoPDFArgs(psFileName, pdfFileName)); process.Dispose(); } catch (Exception ex) { WPFNotifier.DebugError(ex); } }
private void bExecuteRaw_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(textBoxRequest.Text)) { return; } try { var res = Connection.Get(textBoxRequest.Text); if (res == null) { textBoxResults.Text = "Null result"; } else { textBoxResults.Text = res.ToString(); } } catch (Exception ex) { WPFNotifier.DebugError(ex); } }
/// <summary> /// Checks print job and printer status /// </summary> private void TimerCall() { timer.Enabled = false; bool jobfound = false; bool hasTrouble = false; try { string statusReport = ""; //_printerStatus |= PrintHelper.GetPrinterStatus(_printJob.ServerHost, _printJob.PrintJobTitle.PrinterName, out statusReport); _printerStatus |= PrintHelper.GetPrinterStatus(PrintJobTitle.Host, PrintJobTitle.PrinterName, out statusReport); if ((_printerStatus | PrinterTrouble.None) == PrinterTrouble.None) { hasTrouble = false; } else { hasTrouble = true; } // if issue found if (hasTrouble) { // send data to server //OnIssueFound(new PrinterIssueEventArgs(_printJob.PrintJobTitle.PrinterName, _printerStatus, statusReport)); OnIssueFound(new PrinterIssueEventArgs(PrintJobTitle.PrinterName, _printerStatus, statusReport)); OnCanBeDisposed(EventArgs.Empty); return; } // find the job //foreach (var printJob in PrintHelper.GetPrintJobs(_printJob.ServerHost, _printJob.PrintJobTitle.PrinterName)) foreach (var printJob in PrintHelper.GetPrintJobs(PrintJobTitle.Host, PrintJobTitle.PrinterName)) { //if (PrintHelper.ExtractDocumentName(printJob) == _printJob.PrintJobTitle.Document) if (PrintHelper.ExtractDocumentName(printJob) == PrintJobTitle.Document) { jobfound = true; break; } } } catch (Exception ex) { WPFNotifier.DebugError(ex); } // if job found if (jobfound) { // continue watching timer.Enabled = true; } else { // finish watching OnJobCompleted(new PrintJobDataEventArgs(null)); OnCanBeDisposed(EventArgs.Empty); } }
/// ReadFile #region ReadFile /// <summary> /// Reads postscript file and extracts file data /// </summary> /// <param name="fileName">file to be inspected</param> /// <returns>postscript file data</returns> public static PostScriptMetaData ReadFile(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { return(null); } try { if (!File.Exists(fileName)) { return(null); } // extract all the text string text = File.ReadAllText(fileName); if (string.IsNullOrWhiteSpace(text)) { return(null); } // get lines of text string[] textss = text.Split(new string[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries); if (textss == null || textss.Length < 1) { return(null); } // create meta data PostScriptMetaData data = new PostScriptMetaData(); // fill meta data foreach (string line in textss) { if (line.Contains(@"%Title:")) // Title { if (string.IsNullOrWhiteSpace(data.Title)) { data.Title = GetLineValue(line); } } else if (line.Contains(@"@PJL JOB NAME")) // Title { data.Title = GetLineValue2(line); } else if (line.Contains(@"%Orientation:")) // Orientation { data.Orientation = GetLineValue(line); } else if (line.Contains(@"%BeginFeature: *PageSize")) // PageSize { data.PageSizeName = GetLineValue(line); } else if (line.Contains(@"%BeginFeature: *Resolution")) // Resolution { data.Resolution = GetLineValue(line); } else if (line.Contains(@"%Pages:")) // Number of pages { int count; if (int.TryParse(GetLineValue(line), out count)) { data.NumberOfPages = count; } } } return(data); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(null); } }
/// Methods #region Methods /// <summary> /// /// </summary> /// <param name="method"></param> private void ExecuteMethod(MethodInfo method) { List <string> datas = new List <string>(); foreach (Control c in flowLayoutPanelParameters.Controls) { if (c as TextBox != null) { datas.Add(c.Text); } } List <object> data = new List <object>(); int i = 0; foreach (var parameter in method.GetParameters()) { if (parameter.ParameterType == typeof(bool)) { bool b = false; bool.TryParse(datas[i], out b); data.Add(b); } else if (parameter.ParameterType == typeof(int)) { int num = 0; int.TryParse(datas[i], out num); data.Add(num); } else if (parameter.ParameterType == typeof(string)) { data.Add(datas[i]); } i++; } try { var res = method.Invoke(null, data.ToArray()); if (res != null) { string result = res.ToString();//.Replace("\\", ""); if (string.IsNullOrWhiteSpace(result)) { textBoxResults.Text = "Null result X"; return; } textBoxResults.Text = result; try { JArray json = JArray.Parse(result); if (json == null) { //textBoxResults.Text = result.ToString(); } else { //textBoxResults.Text = JsonConvert.SerializeObject(json); } } catch (Exception exx) { WPFNotifier.DebugError(exx); } /* * try * { * JObject json = JObject.Parse(result); * if (json == null) * { * //textBoxResults.Text = result.ToString(); * } * else * { * //textBoxResults.Text = JsonConvert.SerializeObject(json); * } * } * catch (Exception exx) * { * WPFNotifier.DebugError(exx); * } */ /* * try * { * Printers xxxx = JsonConvert.DeserializeObject<Printers>(result); * } * catch (Exception exx) * { * WPFNotifier.DebugError(exx); * }*/ } else { textBoxResults.Text = "Null result"; } } catch (Exception ex) { WPFNotifier.DebugError(ex); } }
/// LoadConfig #region LoadConfig /// <summary> /// Loads API config data /// </summary> /// <param name="fileName"></param> public static string LoadConfig(string fileName) { LogHelper.LogDebug(); if (string.IsNullOrWhiteSpace(fileName)) { return(null); } try { if (!File.Exists(fileName)) { return(null); } string text = File.ReadAllText(fileName); if (string.IsNullOrWhiteSpace(text)) { return(null); } string[] sstext = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); if (sstext == null || sstext.Length < 1) { return(null); } LogHelper.LogDebug("API config : " + fileName); StringBuilder sb = new StringBuilder(); 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(); switch (key) { case "API_MainURL": _url = value; sb.AppendLine(line); break; case "API_GetPrinters": _url_GetPrinters = value; sb.AppendLine(line); break; case "API_GetEnvironment": _url_GetEnvironment = value; sb.AppendLine(line); break; case "API_CheckIfCanPrint": _url_CheckIfCanPrint = value; sb.AppendLine(line); break; case "API_LogPrint": _url_LogPrint = value; sb.AppendLine(line); break; case "API_PrinterIssue": _url_PrinterIssue = value; sb.AppendLine(line); break; } } return(sb.ToString()); } catch (Exception ex) { WPFNotifier.DebugError(ex); return(null); } }