private void UploadProfile(string profilePath, Connection connection) { if (connection != null) { try { connection.Open(); ZebraPrinter genericPrinter = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs printer = ZebraPrinterFactory.CreateLinkOsPrinter(genericPrinter); if (printer != null) { printer.LoadProfile(profilePath, FileDeletionOption.NONE, false); string printerAddress = connectionSelector.getConnectionAddress(); MessageBoxCreator.ShowInformation($"Profile loaded successfully to printer {printerAddress}", "Profile Uploaded Successfully"); } else { MessageBoxCreator.ShowError("Profile loading is only available on Link-OS(TM) printers", "Error"); } } catch (ConnectionException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (ZebraPrinterLanguageUnknownException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (IOException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (Exception e) { MessageBoxCreator.ShowError(e.Message, "Upload Profile Error"); } finally { SetButtonStates(true); try { connection.Close(); } catch (ConnectionException) { } } } }
private async Task <string> RetrieveFormatContentAsync(FormatViewModel format) { string formatContent = null; Connection connection = null; try { await Task.Factory.StartNew(() => { connection = ConnectionCreator.Create(ViewModel.SelectedPrinter); connection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); formatContent = Encoding.UTF8.GetString(printer.RetrieveFormatFromPrinter(format.PrinterPath)); }); } catch (Exception e) { await AlertCreator.ShowErrorAsync(this, e.Message); } finally { await Task.Factory.StartNew(() => { try { connection?.Close(); } catch (ConnectionException) { } }); } return(formatContent); }
/// <summary> /// /// head.resolution.in_dpi:203 /// zpl.label_length:590 /// odometer.label_dot_length:590 /// media.width_sense.in_mm:104.1 /// media.width_sense.in_cm:10.41 /// media.width_sense.in_dots:832 /// media.width_sense.in_inches:4.099 /// sensor.width.cur:209 /// sensor.width.in_dots:832 /// /// </summary> /// <param name="c"></param> private static void DisplaySettings(Connection c) { ZebraPrinter genericPrinter = ZebraPrinterFactory.GetInstance(c); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(genericPrinter); if (linkOsPrinter != null) { Console.WriteLine("Available Settings for myDevice"); HashSet <string> availableSettings = linkOsPrinter.GetAvailableSettings(); foreach (string setting in availableSettings) { Console.WriteLine($"{setting}: Range = ({linkOsPrinter.GetSettingRange(setting)})"); } Console.WriteLine("\nCurrent Setting Values for myDevice"); Dictionary <string, string> allSettingValues = linkOsPrinter.GetAllSettingValues(); foreach (string settingName in allSettingValues.Keys) { Console.WriteLine($"{settingName}:{allSettingValues[settingName]}"); } string darknessSettingId = "print.tone"; string newDarknessValue = "10.0"; if (availableSettings.Contains(darknessSettingId) && linkOsPrinter.IsSettingValid(darknessSettingId, newDarknessValue) && linkOsPrinter.IsSettingReadOnly(darknessSettingId) == false) { linkOsPrinter.SetSetting(darknessSettingId, newDarknessValue); } Console.WriteLine($"\nNew {darknessSettingId} Value = {linkOsPrinter.GetSettingValue(darknessSettingId)}"); } }
private async void CheckPrinterStatusButton_Clicked(object sender, EventArgs eventArgs) { SetInputEnabled(false); PrinterStatusLabel.Text = "Checking printer status..."; Connection connection = null; try { await Task.Factory.StartNew(() => { connection = CreateConnection(); connection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); PrinterStatus printerStatus = linkOsPrinter?.GetCurrentStatus() ?? printer.GetCurrentStatus(); Device.BeginInvokeOnMainThread(() => { PrinterStatusLabel.Text = BuildPrinterStatusString(printerStatus); }); }); } catch (Exception e) { PrinterStatusLabel.Text = $"Error: {e.Message}"; await DisplayAlert("Error", e.Message, "OK"); } finally { try { connection?.Close(); } catch (ConnectionException) { } SetInputEnabled(true); } }
//链接打印机 public static string LinkPrinter(string printerName, int port) { try { string ip = GetRegistryData(printerName + "\\DsSpooler", "portName"); if (ip == "" || ip.Split(new char[] { '.' }).Length != 4) { throw new ConnectionException("没找到IP"); } foreach (string s in ip.Split(new char[] { '.' })) { int.Parse(s); } Ping pingSender = new Ping(); PingReply reply = pingSender.Send(ip, 1);; if (reply.Status != IPStatus.Success) { throw new ConnectionException("链接失败!"); } /*Ping pingSender = new Ping(); * Thread thread = new Thread(new ThreadStart())); * thread.Start(); * PingReply reply = null; * reply = pingSender.Send(ip, 1);//第一个参数为ip地址,第二个参数为ping的时间 * * Func<string, int, PingReply> func = new Func<string, int, PingReply>(Printer.PingIP); * reply = func(ip, 1); * * if (reply.Status != IPStatus.Success) * throw new ConnectionException("链接失败!");*/ TcpConnection connection = new TcpConnection(ip, port); connection.Open(); printerHTTP = ZebraPrinterFactory.GetInstance(connection); linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printerHTTP); printerStatus = printerHTTP.GetCurrentStatus(); } catch (ConnectionException e) { printerHTTP = null; FileTools.WriteLineFile(FileTools.exceptionFilePath, DateTime.Now.ToString() + " " + printerName + e.Message); return(printerName + e.Message); } catch (FormatException e) { printerHTTP = null; FileTools.WriteLineFile(FileTools.exceptionFilePath, DateTime.Now.ToString() + " " + printerName + "IP地址不正确!"); return(printerName + "IP地址不正确!"); } return(""); }
//关闭链接 public static void ClosePrinter() { if (printerHTTP != null) { printerHTTP.Connection.Close(); printerHTTP = null; printerStatus = null; linkOsPrinter = null; } }
private void UpdateSettingsTable() { Connection connection = null; try { connection = connectionSelector.GetConnection(); connection.Open(); ZebraPrinter genericPrinter = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs printer = ZebraPrinterFactory.CreateLinkOsPrinter(genericPrinter); if (printer != null) { Dictionary <string, Sdk.Settings.Setting> settings = printer.GetAllSettings(); Application.Current.Dispatcher.Invoke(() => { if (settings != null) { foreach (string key in settings.Keys) { viewModel.Settings.Add(new Setting { Key = key, Value = settings[key].Value, Range = printer.GetSettingRange(key) }); } } else { MessageBoxCreator.ShowError("Error reading settings", "Settings Error"); } printerSettingsGrid.UnselectAll(); }); } else { MessageBoxCreator.ShowError("Connected printer does not support settings", "Connection Error"); } } catch (ConnectionException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (ZebraPrinterLanguageUnknownException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (SettingsException e) { MessageBoxCreator.ShowError(e.Message, "Settings Error"); } catch (Exception e) { MessageBoxCreator.ShowError(e.Message, "Save Settings Error"); } finally { SetButtonStates(true); try { if (connection != null) { connection.Close(); } } catch (ConnectionException) { } } }
private void GetFormatVariables(object sender, DoWorkEventArgs e) { object[] parameters = e.Argument as object[]; dynamic selectedFormat = parameters[0] as dynamic; string lastFormatOpened = (string)parameters[1]; string lastFormatOpenedSource = (string)parameters[2]; string lastFormatOpenedContents = (string)parameters[3]; object[] results = new object[4]; long formatId = long.Parse(selectedFormat.FormatId); lastFormatOpened = selectedFormat.FormatDrive + selectedFormat.FormatName + selectedFormat.FormatExtension; lastFormatOpenedSource = selectedFormat.FormatSource; try { OpenConnection(); ZebraPrinterLinkOs printer = ZebraPrinterFactory.GetLinkOsPrinter(printerConnection); if (lastFormatOpenedSource.Equals("Sample") && formatId > 0) { using (SavedFormatProvider provider = new SavedFormatProvider()) { lastFormatOpenedContents = provider.GetFormatContents(formatId); } } else { byte[] formatInBytes = printer.RetrieveFormatFromPrinter(lastFormatOpened); lastFormatOpenedContents = Encoding.UTF8.GetString(formatInBytes); } fieldDescDataVars = printer.GetVariableFields(lastFormatOpenedContents).ToList(); fieldDescDataVars = FormatFieldDescriptionDataVars(fieldDescDataVars); formatVariableCollection = new ObservableCollection <FormatVariable>(); for (int i = 0; i < fieldDescDataVars.Count; ++i) { formatVariableCollection.Add(new FormatVariable { FieldName = fieldDescDataVars[i].FieldName, FieldValue = "" }); } results[0] = lastFormatOpened; results[1] = lastFormatOpenedSource; results[2] = lastFormatOpenedContents; results[3] = formatVariableCollection; e.Result = results; } catch (ConnectionException error) { errorMessage = "Connection Error: " + error.Message; } finally { CloseConnection(); } }
private void RetrieveFormatsFromPrinter(object sender, DoWorkEventArgs e) { List <SavedFormat> savedFormats = GetSavedFormats(); foreach (SavedFormat format in savedFormats) { Dictionary <string, string> formatAttributes = new Dictionary <string, string> { { attributeKeys[0], format.formatDrive }, { attributeKeys[1], format.formatName }, { attributeKeys[2], format.formatExtension }, { attributeKeys[3], "/Resources/btn_star_big_on.png" }, { FORMAT_SOURCE_KEY, format.sourcePrinterName }, { SavedFormat._ID, format.id.ToString() } }; AddFormatToList(formatAttributes); } try { OpenConnection(); ZebraPrinterLinkOs printer = ZebraPrinterFactory.GetLinkOsPrinter(printerConnection); string[] printerFormats = printer.RetrieveFileNames(new string[] { "ZPL" }); foreach (string format in printerFormats) { int colonPosition = format.IndexOf(":"); int dotPosition = format.LastIndexOf("."); if (dotPosition < 0) { dotPosition = format.Length; } string drive = format.Substring(0, colonPosition + 1); string extension = format.Substring(dotPosition); string name = format.Substring(colonPosition + 1, dotPosition - 2); Dictionary <string, string> formatAttributes = new Dictionary <string, string> { { attributeKeys[0], drive }, { attributeKeys[1], name }, { attributeKeys[2], extension }, { attributeKeys[3], "/Resources/btn_star_big_off.png" }, { FORMAT_SOURCE_KEY, FORMAT_SOURCE_PRINTER }, { SavedFormat._ID, "-1" } }; AddFormatToList(formatAttributes); } } catch (ConnectionException error) { errorMessage = "Connection Error: " + error.Message; } finally { CloseConnection(); } }
private void GetPrinterStatus() { Connection printerConnection = null; Task.Run(() => { try { printerConnection = connectionSelector.GetConnection(); printerConnection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(printerConnection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); ZebraPrinterStatus status = (linkOsPrinter != null) ? linkOsPrinter.GetCurrentStatus() : printer.GetCurrentStatus(); string[] printerStatusString = new PrinterStatusMessages(status).GetStatusMessage(); List <string> printerStatusPrefix = GetPrinterStatusPrefix(status); StringBuilder sb = new StringBuilder(); foreach (string s in printerStatusPrefix) { sb.AppendLine(s); } foreach (string s in printerStatusString) { sb.AppendLine(s); } Application.Current.Dispatcher.Invoke(() => { printerStatus.Text = sb.ToString(); }); } catch (ConnectionException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (ZebraPrinterLanguageUnknownException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } finally { if (printerConnection != null) { try { printerConnection.Close(); } catch (ConnectionException) { } finally { SetTestButtonState(true); } } else { SetTestButtonState(true); } } }); }
private void TestConnectionString() { Task.Run(() => { try { ClearProgress(); connection = ZebraConnectionBuilder.Build(GetConnectionStringForSdk()); PublishProgress("Connection string evaluated as class type " + connection.GetType().Name); connection.Open(); PublishProgress("Connection opened successfully"); if (IsAttemptingStatusConnection()) { ZebraPrinterLinkOs printer = ZebraPrinterFactory.GetLinkOsPrinter(connection); PublishProgress("Created a printer, attempting to retrieve status"); ZebraPrinterStatus status = printer.GetCurrentStatus(); PublishProgress("Is printer ready to print? " + status.isReadyToPrint); } else { ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); PublishProgress("Created a printer, attempting to print a config label"); printer.PrintConfigurationLabel(); } PublishProgress("Closing connection"); } catch (ConnectionException) { MessageBoxCreator.ShowError("Connection could not be opened", "Error"); } catch (ZebraPrinterLanguageUnknownException) { MessageBoxCreator.ShowError("Could not create printer", "Error"); } finally { if (connection != null) { try { connection.Close(); } catch (ConnectionException) { } finally { connection = null; SetTestButtonState(true); } } else { SetTestButtonState(true); } } }); }
private bool SaveModifiedSettingsToPrinter() { bool result = false; Connection connection = null; try { connection = connectionSelector.GetConnection(); connection.Open(); ZebraPrinter genericPrinter = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs printer = ZebraPrinterFactory.CreateLinkOsPrinter(genericPrinter); if (printer != null) { foreach (string key in viewModel.ModifiedSettings.Keys) { if (printer.IsSettingReadOnly(key) == false) { printer.SetSetting(key, viewModel.ModifiedSettings[key]); } } viewModel.ModifiedSettings.Clear(); result = true; } else { MessageBoxCreator.ShowError("Connected printer does not support settings", "Connection Error"); } } catch (ConnectionException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (ZebraPrinterLanguageUnknownException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (SettingsException e) { MessageBoxCreator.ShowError(e.Message, "Settings Error"); } catch (Exception e) { MessageBoxCreator.ShowError(e.Message, "Save Settings Error"); } finally { try { if (connection != null) { connection.Close(); } } catch (ConnectionException) { } } return(result); }
private string GetFormatFromPrinter(string formatName) { string format = ""; try { OpenConnection(); ZebraPrinterLinkOs printer = ZebraPrinterFactory.GetLinkOsPrinter(printerConnection); byte[] formatInBytes = printer.RetrieveFormatFromPrinter(formatName); format = new UTF8Encoding().GetString(formatInBytes); format = format.Replace("\0", ""); } catch (ConnectionException error) { errorMessage = "Connection Error: " + error.Message; } finally { CloseConnection(); } return(format); }
private void CreateProfile(string profilePath, Connection connection) { if (connection != null) { try { connection.Open(); ZebraPrinter genericPrinter = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs printer = ZebraPrinterFactory.CreateLinkOsPrinter(genericPrinter); if (printer != null) { if (!profilePath.EndsWith(".zprofile")) { profilePath += ".zprofile"; } printer.CreateProfile(profilePath); MessageBoxCreator.ShowInformation($"Profile created successfully at location '{profilePath}'", "Profile Created Successfully"); } else { MessageBoxCreator.ShowError("Profile creation is only available on Link-OS(TM) printers", "Error"); } } catch (ConnectionException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (ZebraPrinterLanguageUnknownException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (IOException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (ZebraIllegalArgumentException e) { MessageBoxCreator.ShowError(e.Message, "Connection Error"); } catch (Exception e) { MessageBoxCreator.ShowError(e.Message, "Create Profile Error"); } finally { SetButtonStates(true); try { connection.Close(); } catch (ConnectionException) { } } } }
/// <summary> /// 获取打印机状态 /// </summary> /// <returns></returns> public PrinterStatus GetPrinterStatus() { lock (connectionHelper) { connection = null; } lock (printerHelper) { printer = null; } PrinterStatus printerStatus = null; if (TryOpenPrinterConnection()) { printer = GetPrinter(); if (printer != null) { try { ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); printerStatus = (linkOsPrinter != null) ? linkOsPrinter.GetCurrentStatus() : printer.GetCurrentStatus(); } catch (Exception ex) { myEventLog.LogError("获取打印机状态出错!", ex); } finally { } } } return(printerStatus); }
private async Task AddPrinterFormatsToFormatListAsync() { Connection connection = null; try { List <FormatViewModel> formats = new List <FormatViewModel>(); await Task.Factory.StartNew(() => { connection = ConnectionCreator.Create(ViewModel.SelectedPrinter); connection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); string[] formatPrinterPaths = printer.RetrieveFileNames(new string[] { "ZPL" }); foreach (string formatPrinterPath in formatPrinterPaths) { int colonIndex = formatPrinterPath.IndexOf(":"); string driveLetter = formatPrinterPath.Substring(0, colonIndex); string name = formatPrinterPath.Substring(colonIndex + 1, formatPrinterPath.LastIndexOf(".") - colonIndex - 1); string extension = formatPrinterPath.Substring(formatPrinterPath.LastIndexOf(".") + 1); if (!string.Equals(driveLetter, "Z", StringComparison.OrdinalIgnoreCase)) // Ignore all formats stored on printer's Z drive { formats.Add(new FormatViewModel { DriveLetter = driveLetter, Name = name, Extension = extension, Content = null, // Populate this later, upon navigating to print format page Source = FormatSource.Printer, OnSaveButtonClicked = new Command(async(object parameter) => { if (!ViewModel.IsSavingFormat && !ViewModel.IsDeletingFormat && !ViewModel.IsStoredFormatListRefreshing) { FormatViewModel format = parameter as FormatViewModel; await Task.Factory.StartNew(() => { ViewModel.IsSavingFormat = true; format.IsSaving = true; }); await SavePrinterFormatAsync(format); await Task.Factory.StartNew(() => { format.IsSaving = false; ViewModel.IsSavingFormat = false; }); await RefreshStoredFormatListAsync(); } }), OnPrintButtonClicked = new Command(async(object parameter) => { if (!ViewModel.IsSavingFormat) { FormatViewModel format = parameter as FormatViewModel; await PushPageAsync(new PrintFormatPage(ViewModel.SelectedPrinter, format)); } }) }); } } formats.ForEach(ViewModel.PrinterFormatList.Add); }); } catch (Exception e) { await AlertCreator.ShowErrorAsync(this, e.Message); } finally { await Task.Factory.StartNew(() => { try { connection?.Close(); } catch (ConnectionException) { } }); } }
private async Task SavePrinterFormatAsync(FormatViewModel format) { PrintStationDatabase.StoredFormat storedFormat = null; Connection connection = null; bool fileWriteAttempted = false; bool linePrintEnabled = false; try { await Task.Factory.StartNew(async() => { connection = ConnectionCreator.Create(ViewModel.SelectedPrinter); connection.Open(); string originalPrinterLanguage = SGD.GET(PrintFormatPage.DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(PrintFormatPage.DeviceLanguagesSgd, "zpl", connection); } ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); string formatContent = Encoding.UTF8.GetString(printer.RetrieveFormatFromPrinter(format.PrinterPath)); fileWriteAttempted = true; storedFormat = new PrintStationDatabase.StoredFormat { DriveLetter = format.DriveLetter, Name = format.Name, Extension = format.Extension, Content = formatContent }; await App.Database.SaveStoredFormatAsync(storedFormat); }); } catch (Exception e) { await Task.Factory.StartNew(async() => { if (fileWriteAttempted && storedFormat != null) { await App.Database.DeleteStoredFormatByIdAsync(storedFormat.Id); } }); await AlertCreator.ShowErrorAsync(this, e.Message); } finally { if (linePrintEnabled) { await Task.Factory.StartNew(() => { try { connection?.Open(); SGD.SET(PrintFormatPage.DeviceLanguagesSgd, "line_print", connection); } catch (ConnectionException) { } }); } await Task.Factory.StartNew(() => { try { connection?.Close(); } catch (ConnectionException) { } }); } }
private async void SaveSettingsButton_Clicked(object sender, EventArgs eventArgs) { SetInputEnabled(false); Connection connection = null; bool linePrintEnabled = false; bool deviceLanguageUpdated = false; try { await Task.Factory.StartNew(() => { connection = CreateConnection(); connection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); if (linkOsPrinter != null) { string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); printer = ZebraPrinterFactory.GetInstance(connection); linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); } foreach (string key in modifiedSettings.Keys) { if (linkOsPrinter.IsSettingReadOnly(key) == false) { linkOsPrinter.SetSetting(key, modifiedSettings[key]); } } deviceLanguageUpdated = modifiedSettings.ContainsKey(DeviceLanguagesSgd); modifiedSettings.Clear(); ClearSettings(); UpdateSettingsTable(connection, originalPrinterLanguage); } else { Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Connection Error", "Connected printer does not support settings", "OK"); }); } }); } catch (Exception e) { await DisplayAlert("Error", e.Message, "OK"); } finally { if (linePrintEnabled && !deviceLanguageUpdated) { await Task.Factory.StartNew(() => { try { connection?.Open(); SGD.SET(DeviceLanguagesSgd, "line_print", connection); } catch (ConnectionException) { } }); } try { connection?.Close(); } catch (ConnectionException) { } SetInputEnabled(true); } }
public async Task PrintAsync(DiscoveredPrinter printer, string message) { Connection connection = null; bool linePrintEnabled = false; try { await Task.Factory.StartNew(() => { connection = ConnectionCreator.Create(printer); connection.Open(); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); } ZebraPrinter zebraPrinter = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(zebraPrinter); string errorMessage = GetPrinterStatusErrorMessage(zebraPrinter.GetCurrentStatus()); if (errorMessage != null) { throw new PrinterNotReadyException($"{errorMessage}. Please check your printer and try again."); } else { connection.Write(Encoding.UTF8.GetBytes(message)); } }); if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } } catch (PrinterNotReadyException e) { if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } throw new Exception(e.Message); } catch (Exception e) { if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } throw new Exception(e.Message); } finally { await Task.Factory.StartNew(() => { try { connection?.Close(); } catch (ConnectionException) { } }); } }
private async Task PopulateVariableFieldListAsync() { await Task.Factory.StartNew(() => { viewModel.IsVariableFieldListRefreshing = true; try { viewModel.FormatVariableList.Clear(); } catch (NotImplementedException) { viewModel.FormatVariableList.Clear(); // Workaround for Xamarin.Forms.Platform.WPF issue: https://github.com/xamarin/Xamarin.Forms/issues/3648 } }); Connection connection = null; bool linePrintEnabled = false; try { await Task.Factory.StartNew(() => { connection = ConnectionCreator.Create(selectedPrinter); connection.Open(); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); } ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); if (format.Source == FormatSource.Printer) { format.Content = Encoding.UTF8.GetString(printer.RetrieveFormatFromPrinter(format.PrinterPath)); } FieldDescriptionData[] variableFields = printer.GetVariableFields(format.Content); foreach (FieldDescriptionData variableField in variableFields) { viewModel.FormatVariableList.Add(new FormatVariable { Name = variableField.FieldName ?? $"Field {variableField.FieldNumber}", Index = variableField.FieldNumber, }); } }); } catch (Exception e) { await AlertCreator.ShowErrorAsync(this, e.Message); } finally { if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } await Task.Factory.StartNew(() => { try { connection?.Close(); } catch (ConnectionException) { } viewModel.IsVariableFieldListRefreshing = false; }); } }
private async void UploadProfileButton_Clicked(object sender, EventArgs eventArgs) { SetInputEnabled(false); Connection connection = null; bool linePrintEnabled = false; try { await Task.Factory.StartNew(() => { connection = CreateConnection(); connection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); printer = ZebraPrinterFactory.GetInstance(connection); linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); } string selectedFilename = (string)FileListView.SelectedItem; if (selectedFilename != null) { if (linkOsPrinter != null) { string path = Path.Combine(LocalApplicationDataFolderPath, selectedFilename); linkOsPrinter.LoadProfile(path, FileDeletionOption.NONE, false); Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Profile Uploaded Successfully", $"Profile loaded successfully to printer", "OK"); }); } else { Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Error", "Profile loading is only available on Link-OS\u2122 printers", "OK"); }); } } else { Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("No Profile Selected", "Please select a profile to upload", "OK"); }); } }); } catch (Exception e) { await DisplayAlert("Error", e.Message, "OK"); } finally { if (linePrintEnabled) { await Task.Factory.StartNew(() => { try { connection?.Open(); SGD.SET(DeviceLanguagesSgd, "line_print", connection); } catch (ConnectionException) { } }); } try { connection?.Close(); } catch (ConnectionException) { } SetInputEnabled(true); } }
private void UpdateSettingsTable(Connection connection, string printerLanguage) { ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); Dictionary <string, Setting> settings = linkOsPrinter.GetAllSettings(); if (settings.ContainsKey(DeviceLanguagesSgd)) { settings[DeviceLanguagesSgd].Value = printerLanguage; } if (settings != null) { Device.BeginInvokeOnMainThread(() => { foreach (string key in settings.Keys) { Entry entry = new Entry { Text = settings[key].Value, }; entry.TextChanged += (object s, TextChangedEventArgs e) => { if (key != null) { if (modifiedSettings.ContainsKey(key)) { modifiedSettings[key] = e.NewTextValue; } else { modifiedSettings.Add(key, e.NewTextValue); } } }; SettingsTableSection.Add(new ViewCell { View = new StackLayout { Padding = new Thickness(15), HorizontalOptions = LayoutOptions.FillAndExpand, Children = { new Label { Text = key, FontSize = Device.GetNamedSize(NamedSize.Default, typeof(Label)), FontAttributes = FontAttributes.Bold }, entry, new Label { Text = $"Type: {linkOsPrinter.GetSettingType(key)}, Range: {linkOsPrinter.GetSettingRange(key)}" } } } }); } }); } else { Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Settings Error", "Error reading settings", "OK"); }); } }
private async void PrintButton_Clicked(object sender, EventArgs eventArgs) { await Task.Factory.StartNew(() => { viewModel.IsSendingPrintJob = true; }); Connection connection = null; bool linePrintEnabled = false; try { await Task.Factory.StartNew(() => { connection = ConnectionCreator.Create(selectedPrinter); connection.Open(); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); } ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); string errorMessage = GetPrinterStatusErrorMessage(printer.GetCurrentStatus()); if (errorMessage != null) { throw new PrinterNotReadyException($"{errorMessage}. Please check your printer and try again."); } else { if (format.Source != FormatSource.Printer) { connection.Write(Encoding.UTF8.GetBytes(format.Content)); } linkOsPrinter.PrintStoredFormatWithVarGraphics(format.PrinterPath, BuildFormatVariableDictionary(), "UTF-8"); } }); if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } await Task.Factory.StartNew(() => { viewModel.IsSendingPrintJob = false; }); } catch (PrinterNotReadyException e) { if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } await Task.Factory.StartNew(() => { viewModel.IsSendingPrintJob = false; }); await AlertCreator.ShowAsync(this, "Printer Error", e.Message); } catch (Exception e) { if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } await Task.Factory.StartNew(() => { viewModel.IsSendingPrintJob = false; }); await AlertCreator.ShowErrorAsync(this, e.Message); } finally { await Task.Factory.StartNew(() => { try { connection?.Close(); } catch (ConnectionException) { } }); } }
private async void CreateProfileButton_Clicked(object sender, EventArgs eventArgs) { SetInputEnabled(false); string filename = FilenameEntry.Text; Connection connection = null; bool linePrintEnabled = false; try { if (!string.IsNullOrWhiteSpace(filename)) { await Task.Factory.StartNew(() => { connection = CreateConnection(); connection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); printer = ZebraPrinterFactory.GetInstance(connection); linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); } if (linkOsPrinter != null) { if (!filename.EndsWith(".zprofile")) { filename += ".zprofile"; } string path = Path.Combine(LocalApplicationDataFolderPath, filename); linkOsPrinter.CreateProfile(path); Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Profile Created Successfully", $"Profile created successfully with filename {filename}", "OK"); }); RefreshLocalApplicationDataFiles(); } else { Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Error", "Profile creation is only available on Link-OS\u2122 printers", "OK"); }); } }); } else { await DisplayAlert("Invalid Filename", "Please enter a valid filename", "OK"); SetInputEnabled(true); } } catch (Exception e) { await DisplayAlert("Error", e.Message, "OK"); } finally { if (linePrintEnabled) { await Task.Factory.StartNew(() => { try { connection?.Open(); SGD.SET(DeviceLanguagesSgd, "line_print", connection); } catch (ConnectionException) { } }); } try { connection?.Close(); } catch (ConnectionException) { } SetInputEnabled(true); } }