From 8f8c1594b6fada83e88ec29d1502f1cf76b163f2 Mon Sep 17 00:00:00 2001 From: agent-aspose-barcode-examples Date: Tue, 7 Jul 2026 05:06:53 +0500 Subject: [PATCH 1/2] =?UTF-8?q?feat(mailmark-two-dimensional-barcode):=20A?= =?UTF-8?q?dd=2034=20Aspose.BarCode=20.NET=20C#=20examples=20for=20Mailmar?= =?UTF-8?q?k=20Two=20Dimensional=20Barcode=20=E2=80=94=20Aspose.BarCode=20?= =?UTF-8?q?for=20.NET=2026.6.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...-for-high-resolution-printing-on-labels.cs | 74 ++++---- ...-barcode-image-using-generator-settings.cs | 28 +-- ...-containing-multiple-rows-of-field-data.cs | 164 ++++++++++------- ...ry-and-output-their-decoded-data-to-csv.cs | 172 +++++++---------- ...t-regeneration-for-identical-field-sets.cs | 106 ++++++----- ...en-mailmark-type-7-and-type-29-barcodes.cs | 128 ++++++++----- ...age-with-custom-dimensions-for-printing.cs | 52 +++--- ...module-size-for-higher-density-barcodes.cs | 39 ++-- ...elds-and-saves-resulting-barcode-as-png.cs | 85 ++++----- ...outing-service-and-customer-data-values.cs | 65 +++---- ...ance-and-generate-corresponding-barcode.cs | 74 ++++---- ...-returns-generated-barcode-image-stream.cs | 137 +++++++------- ...d-assess-its-impact-on-barcode-capacity.cs | 85 ++++----- ...ce-code-from-decoded-mailmark2dcodetext.cs | 83 +++++---- ...ground-for-overlaying-on-other-graphics.cs | 28 +-- ...ecified-routing-and-service-code-fields.cs | 66 ++++--- ...logging-warning-and-skipping-generation.cs | 112 ++++++----- ...neration-service-throughout-application.cs | 94 ++++++---- ...coding-fails-or-returns-incomplete-data.cs | 102 +++++----- ...nsient-errors-occur-during-image-saving.cs | 97 +++++----- ...ntroller-and-return-image-as-fileresult.cs | 59 +++--- ...es-and-values-to-assist-troubleshooting.cs | 103 +++++------ ...parallel-library-to-improve-performance.cs | 49 ++--- ...barcodereader-with-decodetypedatamatrix.cs | 55 +++--- ...to-satisfy-specific-layout-requirements.cs | 50 ++--- ...as-jpeg-file-to-specified-output-folder.cs | 44 ++--- ...nd-later-reconstruction-in-applications.cs | 81 ++++---- ...ix-before-invoking-read-method-on-image.cs | 63 ++++--- ...o-http-response-without-writing-to-disk.cs | 54 +++--- ...rk2dcodetext-object-from-decoded-result.cs | 84 ++++++--- ...r-in-memory-processing-and-transmission.cs | 46 +++-- ...-to-c40-character-set-before-generation.cs | 117 +++++------- ...eed-capacity-for-selected-mailmark-type.cs | 174 +++++++----------- ...n-exact-routing-and-service-code-values.cs | 108 ++++++----- 34 files changed, 1480 insertions(+), 1398 deletions(-) diff --git a/mailmark-two-dimensional-barcode/adjust-generator-settings-to-produce-barcode-image-suitable-for-high-resolution-printing-on-labels.cs b/mailmark-two-dimensional-barcode/adjust-generator-settings-to-produce-barcode-image-suitable-for-high-resolution-printing-on-labels.cs index 5b853ed..1cb34f3 100644 --- a/mailmark-two-dimensional-barcode/adjust-generator-settings-to-produce-barcode-image-suitable-for-high-resolution-printing-on-labels.cs +++ b/mailmark-two-dimensional-barcode/adjust-generator-settings-to-produce-barcode-image-suitable-for-high-resolution-printing-on-labels.cs @@ -1,49 +1,61 @@ +// Title: High‑Resolution Barcode Generation for Label Printing +// Description: Demonstrates configuring Aspose.BarCode generator to create a high‑resolution PNG suitable for printing labels. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to set resolution, image size, module dimensions, colors, and text options using BarcodeGenerator and related parameter classes. Developers often need to produce crisp barcodes for packaging, shipping labels, or product tags, and this snippet shows the typical API usage for such scenarios. +// Prompt: Adjust generator settings to produce a barcode image suitable for high‑resolution printing on labels. +// Tags: code128, highresolution, png, barcode generation, aspnet, aspose.barcode, image parameters + using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; -namespace BarcodeHighResolution +/// +/// Generates a high‑resolution Code128 barcode image suitable for label printing. +/// +class Program { /// - /// Demonstrates generating a high‑resolution Code128 barcode and saving it as a PNG file. + /// Entry point. Configures barcode generator settings and saves the image. /// - class Program + static void Main() { - /// - /// Entry point of the application. Creates a barcode with specific dimensions and resolution, - /// then writes the image to disk. - /// - static void Main() + // Initialize a barcode generator for Code128 with the sample text "HIGHRES12345" + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "HIGHRES12345")) { - // Path where the generated barcode image will be saved. - string outputPath = "highres_label.png"; + // Set the image resolution to 300 DPI, which is appropriate for high‑quality label printing + generator.Parameters.Resolution = 300; - // Initialize a barcode generator for Code128 with the sample text "1234567890". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) - { - // Set the image resolution to 300 DPI, suitable for high‑quality label printing. - generator.Parameters.Resolution = 300f; + // Use interpolation mode to allow explicit pixel dimensions for the output image + generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - // Turn off automatic sizing so we can manually define dimensions. - generator.Parameters.AutoSizeMode = AutoSizeMode.None; + // Define the exact image size in pixels (width x height) for the label + generator.Parameters.ImageWidth.Pixels = 1200f; // label width + generator.Parameters.ImageHeight.Pixels = 600f; // label height - // Configure the module (X) size and the bar height in points. - generator.Parameters.Barcode.XDimension.Point = 2f; // 2 points per module (narrow bar width) - generator.Parameters.Barcode.BarHeight.Point = 50f; // 50 points tall (overall bar height) + // Configure module (X‑dimension) size and bar height (height is ignored in interpolation mode but set for completeness) + generator.Parameters.Barcode.XDimension.Pixels = 2f; // each module ~2 pixels wide + generator.Parameters.Barcode.BarHeight.Pixels = 50f; // bar height for 1D barcodes - // Apply uniform padding of 5 points on all sides of the barcode. - generator.Parameters.Barcode.Padding.Left.Point = 5f; - generator.Parameters.Barcode.Padding.Top.Point = 5f; - generator.Parameters.Barcode.Padding.Right.Point = 5f; - generator.Parameters.Barcode.Padding.Bottom.Point = 5f; + // Set high‑contrast colors: black bars on a white background + generator.Parameters.Barcode.BarColor = Color.Black; + generator.Parameters.BackColor = Color.White; - // Save the generated barcode image to the specified file. - // The format (PNG) is inferred from the file extension. - generator.Save(outputPath); - } + // Customize human‑readable text appearance + generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial"; + generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f; + generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center; + generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; - // Inform the user that the image has been saved. - Console.WriteLine($"Barcode image saved to: {outputPath}"); + // Add uniform padding of 5 points on all sides of the barcode + generator.Parameters.Barcode.Padding.Left.Point = 5f; + generator.Parameters.Barcode.Padding.Top.Point = 5f; + generator.Parameters.Barcode.Padding.Right.Point = 5f; + generator.Parameters.Barcode.Padding.Bottom.Point = 5f; + + // Save the generated barcode as a PNG file + string outputPath = "highres_label.png"; + generator.Save(outputPath); + Console.WriteLine($"Barcode saved to {outputPath}"); } } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/apply-custom-foreground-and-background-colors-to-barcode-image-using-generator-settings.cs b/mailmark-two-dimensional-barcode/apply-custom-foreground-and-background-colors-to-barcode-image-using-generator-settings.cs index 9baf6e1..f71868d 100644 --- a/mailmark-two-dimensional-barcode/apply-custom-foreground-and-background-colors-to-barcode-image-using-generator-settings.cs +++ b/mailmark-two-dimensional-barcode/apply-custom-foreground-and-background-colors-to-barcode-image-using-generator-settings.cs @@ -1,38 +1,40 @@ +// Title: Custom Foreground and Background Colors for Barcode Image +// Description: Demonstrates how to apply custom bar (foreground) and background colors when generating a barcode with Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and the Parameters property to customize visual aspects of barcodes. Typical scenarios include branding, UI integration, and printing where specific color schemes are required. Developers often need to adjust bar and background colors to match corporate identity or improve readability on various media. +// Prompt: Apply custom foreground and background colors to the barcode image using generator settings. +// Tags: barcode, color, generation, png, aspose.barcode, csharp + using System; using Aspose.BarCode.Generation; using Aspose.Drawing; /// -/// Demonstrates generating a Code128 barcode with custom colors using Aspose.BarCode. +/// Shows how to set custom foreground (bar) and background colors for a generated barcode image. /// class Program { /// - /// Entry point of the application. Generates a barcode image with custom foreground and background colors, - /// saves it to a PNG file, and writes the output path to the console. + /// Entry point of the example. Generates a Code128 barcode with blue bars on a light‑gray background and saves it as a PNG file. /// static void Main() { // Define the output file path for the generated barcode image. string outputPath = "custom_color_barcode.png"; - // Initialize a BarcodeGenerator for Code128 symbology with the desired text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Initialize a BarcodeGenerator for the Code128 symbology with sample text. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Set the color of the barcode bars (foreground). + // Set the foreground color (the color of the bars) to blue. generator.Parameters.Barcode.BarColor = Color.Blue; - // Set the background color of the image. - generator.Parameters.BackColor = Color.LightYellow; - - // Increase the image resolution to 300 DPI for higher quality output. - generator.Parameters.Resolution = 300f; + // Set the background color of the image to light gray. + generator.Parameters.BackColor = Color.LightGray; - // Save the generated barcode as a PNG file to the specified path. + // Save the generated barcode image to the specified file path (default format is PNG). generator.Save(outputPath); } // Inform the user where the barcode image has been saved. - Console.WriteLine($"Barcode image saved to {outputPath}"); + Console.WriteLine($"Barcode image saved to: {outputPath}"); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/batch-generate-mailmark-barcodes-from-csv-file-containing-multiple-rows-of-field-data.cs b/mailmark-two-dimensional-barcode/batch-generate-mailmark-barcodes-from-csv-file-containing-multiple-rows-of-field-data.cs index b6ec54c..52b6c95 100644 --- a/mailmark-two-dimensional-barcode/batch-generate-mailmark-barcodes-from-csv-file-containing-multiple-rows-of-field-data.cs +++ b/mailmark-two-dimensional-barcode/batch-generate-mailmark-barcodes-from-csv-file-containing-multiple-rows-of-field-data.cs @@ -1,99 +1,125 @@ +// Title: Batch Mailmark Barcode Generation from CSV +// Description: Demonstrates reading a CSV file with Mailmark data and generating a PNG barcode for each row using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on complex barcodes such as Mailmark. It showcases the use of MailmarkCodetext and ComplexBarcodeGenerator classes to create 4‑state Mailmark symbols, a common requirement for postal automation and tracking solutions. Developers often need to batch‑process data sources (e.g., CSV, databases) to produce barcodes for large volumes of items. +// Prompt: Batch generate Mailmark barcodes from a CSV file containing multiple rows of field data. +// Tags: mailmark, barcode, csv, batch, generation, png, aspose.barcode + using System; using System.IO; -using System.Collections.Generic; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; /// -/// Generates Mailmark barcodes from a CSV file or sample data and saves them as PNG images. +/// Generates Mailmark barcodes in batch from a CSV file. /// class Program { /// - /// Entry point of the application. - /// Reads records, constructs MailmarkCodetext objects, and creates barcode images. + /// Entry point of the application. Reads Mailmark data from a CSV file, + /// creates a MailmarkCodetext for each record, and saves the resulting PNG images. /// static void Main() { - const string csvPath = "mailmark_data.csv"; - - // Collection to hold each CSV record as an array of fields - List records = new List(); + // Path to the input CSV file containing Mailmark fields. + string csvPath = "mailmark_data.csv"; - // Attempt to read data from the CSV file if it exists - if (File.Exists(csvPath)) + // Ensure a sample CSV exists if the file is missing. + if (!File.Exists(csvPath)) { - // Read all lines and split each line by commas (simple parsing, no quoted fields) - foreach (var line in File.ReadAllLines(csvPath)) + // Create a small safe sample (5 rows) with required fields. + // Format is fixed to 4 for 4‑state Mailmark. + // DestinationPostCodePlusDPS uses the required trailing space. + string[] sampleLines = new[] { - // Skip empty or whitespace-only lines - if (string.IsNullOrWhiteSpace(line)) continue; - - // Split the line into individual fields - var parts = line.Split(','); - - // Ensure the line has at least the expected number of columns - if (parts.Length >= 6) - records.Add(parts); - } + "VersionID,Class,SupplychainID,ItemID,DestinationPostCodePlusDPS", + "1,0,384224,16563762,EF61AH8T ", + "1,1,384224,16563763,EF61AH8T ", + "1,2,384224,16563764,EF61AH8T ", + "1,3,384224,16563765,EF61AH8T ", + "1,0,384224,16563766,EF61AH8T " + }; + File.WriteAllLines(csvPath, sampleLines); } - else + + // Output directory for generated barcode images. + string outputDir = "Barcodes"; + if (!Directory.Exists(outputDir)) { - // CSV not found – use hard‑coded sample data (5 rows) - records.Add(new[] { "4", "1", "0", "384224", "16563762", "EF61AH8T " }); - records.Add(new[] { "4", "1", "1", "384224", "16563763", "EF61AH8T " }); - records.Add(new[] { "4", "1", "2", "384224", "16563764", "EF61AH8T " }); - records.Add(new[] { "4", "1", "3", "384224", "16563765", "EF61AH8T " }); - records.Add(new[] { "4", "1", "4", "384224", "16563766", "EF61AH8T " }); + Directory.CreateDirectory(outputDir); } - int index = 0; // Counter for generated files + // Read all lines from the CSV file and skip the header row. + string[] lines = File.ReadAllLines(csvPath); + if (lines.Length <= 1) + { + Console.WriteLine("CSV file contains no data rows."); + return; + } - // Process each record and generate a barcode - foreach (var fields in records) + // Process each data row in the CSV. + for (int i = 1; i < lines.Length; i++) { - try + string line = lines[i]; + if (string.IsNullOrWhiteSpace(line)) + continue; // Skip empty lines. + + // Split the line into individual fields. + string[] parts = line.Split(','); + + // Validate the expected number of fields (5). + if (parts.Length != 5) + { + Console.WriteLine($"Skipping malformed line {i + 1}: {line}"); + continue; + } + + // Parse VersionID. + if (!int.TryParse(parts[0].Trim(), out int versionId)) + { + Console.WriteLine($"Invalid VersionID on line {i + 1}"); + continue; + } + + // Class is a string value (e.g., "0", "1"). + string classValue = parts[1].Trim(); + + // Parse SupplychainID. + if (!int.TryParse(parts[2].Trim(), out int supplyChainId)) { - // Parse numeric and string fields from the CSV record - int format = int.Parse(fields[0].Trim()); - int versionId = int.Parse(fields[1].Trim()); - string classValue = fields[2].Trim(); // Class is a string property - int supplyChainId = int.Parse(fields[3].Trim()); - int itemId = int.Parse(fields[4].Trim()); - string destinationPostCodePlusDps = fields[5].Trim(); - - // Populate a MailmarkCodetext object with the parsed values - var mailmark = new MailmarkCodetext - { - Format = format, - VersionID = versionId, - Class = classValue, - SupplychainID = supplyChainId, - ItemID = itemId, - DestinationPostCodePlusDPS = destinationPostCodePlusDps - }; - - // Generate the barcode image using Aspose ComplexBarcodeGenerator - using (var generator = new ComplexBarcodeGenerator(mailmark)) - { - // Construct a unique filename for each barcode - string outputFile = $"Mailmark_{itemId}_{index}.png"; - - // Save the barcode as a PNG file - generator.Save(outputFile, BarCodeImageFormat.Png); - - // Inform the user that the file was created - Console.WriteLine($"Generated: {outputFile}"); - } + Console.WriteLine($"Invalid SupplychainID on line {i + 1}"); + continue; } - catch (Exception ex) + + // Parse ItemID. + if (!int.TryParse(parts[3].Trim(), out int itemId)) { - // Report any errors encountered while processing the current record - Console.WriteLine($"Error processing record #{index}: {ex.Message}"); + Console.WriteLine($"Invalid ItemID on line {i + 1}"); + continue; } - index++; // Increment the file counter + // DestinationPostCodePlusDPS may contain trailing spaces, which are required. + string destination = parts[4]; + + // Build the Mailmark codetext object with the parsed values. + var mailmark = new MailmarkCodetext + { + Format = 4, // 4‑state Mailmark. + VersionID = versionId, + Class = classValue, + SupplychainID = supplyChainId, + ItemID = itemId, + DestinationPostCodePlusDPS = destination + }; + + // Generate the barcode using ComplexBarcodeGenerator. + using (var generator = new ComplexBarcodeGenerator(mailmark)) + { + string outPath = Path.Combine(outputDir, $"Mailmark_{itemId}.png"); + generator.Save(outPath, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode for ItemID {itemId} -> {outPath}"); + } } + + Console.WriteLine("Batch generation completed."); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/batch-read-multiple-mailmark-barcode-images-from-directory-and-output-their-decoded-data-to-csv.cs b/mailmark-two-dimensional-barcode/batch-read-multiple-mailmark-barcode-images-from-directory-and-output-their-decoded-data-to-csv.cs index 6ae58c0..e4c8fc2 100644 --- a/mailmark-two-dimensional-barcode/batch-read-multiple-mailmark-barcode-images-from-directory-and-output-their-decoded-data-to-csv.cs +++ b/mailmark-two-dimensional-barcode/batch-read-multiple-mailmark-barcode-images-from-directory-and-output-their-decoded-data-to-csv.cs @@ -1,135 +1,105 @@ +// Title: Batch Mailmark Barcode Reader to CSV +// Description: Reads Mailmark barcodes from images in a folder and writes decoded data to a CSV file. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, demonstrating how to use BarCodeReader with DecodeType.Mailmark to process multiple images. Typical use cases include bulk scanning of Mailmark symbols for mail sorting or inventory tracking, where developers need to extract barcode data and export it for further analysis. The example showcases file handling, supported image filtering, and CSV output generation, common tasks for batch barcode processing solutions. +// Prompt: Batch read multiple Mailmark barcode images from a directory and output their decoded data to CSV. +// Tags: mailmark, barcode, batch, csv, reading, aspose.barcode, decode + using System; -using System.Collections.Generic; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.BarCodeRecognition; -using Aspose.BarCode.ComplexBarcode; /// -/// Reads Mailmark barcodes from image files in a directory and writes the extracted data to a CSV file. +/// Demonstrates batch reading of Mailmark barcodes from a directory and exporting results to a CSV file. /// class Program { /// - /// Application entry point. + /// Entry point of the application. Scans a folder for supported image files, decodes Mailmark barcodes, + /// and writes the extracted information to a CSV file. /// - /// - /// Optional command‑line arguments: - /// args[0] – input directory containing barcode images (default: "Barcodes"). - /// args[1] – output CSV file path (default: "output.csv"). - /// - static void Main(string[] args) + static void Main() { - // Determine input directory (first argument or default) - string inputDirectory = args.Length > 0 ? args[0] : "Barcodes"; + // Input directory containing Mailmark barcode images. + string inputDir = "MailmarkImages"; - // Determine output CSV file path (second argument or default) - string outputCsvPath = args.Length > 1 ? args[1] : "output.csv"; + // Output CSV file path. + string outputCsv = "MailmarkResults.csv"; - // Verify that the input directory exists - if (!Directory.Exists(inputDirectory)) + // Verify that the input directory exists. + if (!Directory.Exists(inputDir)) { - Console.WriteLine($"Input directory does not exist: {inputDirectory}"); + Console.WriteLine($"Input directory does not exist: {inputDir}"); return; } - // Prepare CSV lines collection and add header row - var csvLines = new List(); - csvLines.Add("FileName,Format,VersionID,Class,SupplychainID,ItemID,DestinationPostCodePlusDPS,RawCodeText"); + // Retrieve all files in the directory (any extension) and filter by supported image extensions. + string[] imageFiles = Directory.GetFiles(inputDir, "*.*", SearchOption.TopDirectoryOnly); + var supportedExtensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff" }; + var filesToProcess = new System.Collections.Generic.List(); - // Define supported image file extensions - string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff" }; + foreach (var file in imageFiles) + { + // Include file only if its extension matches one of the supported image types. + if (Array.Exists(supportedExtensions, ext => ext.Equals(Path.GetExtension(file), StringComparison.OrdinalIgnoreCase))) + filesToProcess.Add(file); + } - // Enumerate all files in the input directory - var files = Directory.GetFiles(inputDirectory); - foreach (var filePath in files) + // If no supported image files were found, inform the user and exit. + if (filesToProcess.Count == 0) { - // Skip files that do not have a supported image extension - if (Array.IndexOf(extensions, Path.GetExtension(filePath).ToLowerInvariant()) < 0) - continue; + Console.WriteLine("No image files found to process."); + return; + } - // Ensure the file actually exists (defensive check) - if (!File.Exists(filePath)) - { - Console.WriteLine($"File not found (skipped): {filePath}"); - continue; - } + // Create (or overwrite) the CSV file and write the header row. + using (var writer = new StreamWriter(outputCsv, false)) + { + writer.WriteLine("FileName,CodeText,CodeType,Confidence,ReadingQuality"); - // Open a barcode reader for Mailmark type on the current image file - using (var reader = new BarCodeReader(filePath, DecodeType.Mailmark)) + // Process each image file individually. + foreach (var filePath in filesToProcess) { - // Read all barcodes present in the image - var results = reader.ReadBarCodes(); - - // If no barcodes were found, write an empty CSV entry for the file - if (results == null || results.Length == 0) + // Double‑check that the file still exists before attempting to read it. + if (!File.Exists(filePath)) { - csvLines.Add($"{Path.GetFileName(filePath)},,,,,,,"); + Console.WriteLine($"File not found (skipped): {filePath}"); continue; } - // Process each detected barcode - foreach (var result in results) + try { - // Attempt to decode the complex Mailmark codetext into its components - MailmarkCodetext mailmark = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); - - // Extract individual fields, handling possible null values - string format = mailmark?.Format.ToString() ?? ""; - string versionId = mailmark?.VersionID.ToString() ?? ""; - string classValue = mailmark?.Class ?? ""; - string supplychainId = mailmark?.SupplychainID.ToString() ?? ""; - string itemId = mailmark?.ItemID.ToString() ?? ""; - string destination = mailmark?.DestinationPostCodePlusDPS ?? ""; - string rawCode = result.CodeText ?? ""; - - // Build a CSV line with proper escaping for each field - string line = $"{Path.GetFileName(filePath)}," + - $"{EscapeCsv(format)}," + - $"{EscapeCsv(versionId)}," + - $"{EscapeCsv(classValue)}," + - $"{EscapeCsv(supplychainId)}," + - $"{EscapeCsv(itemId)}," + - $"{EscapeCsv(destination)}," + - $"{EscapeCsv(rawCode)}"; - - csvLines.Add(line); + // Initialize the barcode reader for the Mailmark symbology. + using (var reader = new BarCodeReader(filePath, DecodeType.Mailmark)) + { + // Attempt to read all barcodes present in the image. + var results = reader.ReadBarCodes(); + + // If no barcodes were detected, write an empty data line for this file. + if (results.Length == 0) + { + writer.WriteLine($"{Path.GetFileName(filePath)},,,," ); + continue; + } + + // Write a CSV line for each detected barcode. + foreach (var result in results) + { + // Replace commas in the decoded text to preserve CSV column integrity. + string codeText = result.CodeText?.Replace(",", " "); + writer.WriteLine($"{Path.GetFileName(filePath)},{codeText},{result.CodeTypeName},{result.Confidence},{result.ReadingQuality}"); + } + } + } + catch (Exception ex) + { + // Log any processing errors and write an error entry to the CSV. + Console.WriteLine($"Error processing file {filePath}: {ex.Message}"); + writer.WriteLine($"{Path.GetFileName(filePath)},Error,,," ); } } } - // Attempt to write all collected CSV lines to the output file - try - { - File.WriteAllLines(outputCsvPath, csvLines); - Console.WriteLine($"CSV output written to: {outputCsvPath}"); - } - catch (Exception ex) - { - Console.WriteLine($"Failed to write CSV file: {ex.Message}"); - } - } - - /// - /// Escapes a CSV field by surrounding it with quotes if it contains commas, quotes, or newlines. - /// Internal quotes are doubled per CSV specification. - /// - /// The field value to escape. - /// The escaped field string. - private static string EscapeCsv(string field) - { - if (field == null) - return ""; - - // Check for characters that require quoting - if (field.Contains(",") || field.Contains("\"") || field.Contains("\n")) - { - // Double any existing quotes and wrap the field in quotes - string escaped = field.Replace("\"", "\"\""); - return $"\"{escaped}\""; - } - - // No escaping needed - return field; + // Inform the user that processing has completed. + Console.WriteLine($"Processing complete. Results saved to {outputCsv}"); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/cache-generated-barcode-images-in-memory-to-avoid-redundant-regeneration-for-identical-field-sets.cs b/mailmark-two-dimensional-barcode/cache-generated-barcode-images-in-memory-to-avoid-redundant-regeneration-for-identical-field-sets.cs index 28bcc3c..5c3e6d8 100644 --- a/mailmark-two-dimensional-barcode/cache-generated-barcode-images-in-memory-to-avoid-redundant-regeneration-for-identical-field-sets.cs +++ b/mailmark-two-dimensional-barcode/cache-generated-barcode-images-in-memory-to-avoid-redundant-regeneration-for-identical-field-sets.cs @@ -1,68 +1,92 @@ +// Title: In-Memory Barcode Image Caching Example +// Description: Demonstrates how to cache generated barcode images in memory to avoid regenerating identical barcodes, improving performance. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, BaseEncodeType, and image handling classes. Developers often need to generate multiple barcodes with repeated data, and caching reduces redundant processing and resource usage. Ideal for batch processing, reporting, or any scenario where the same barcode may be requested multiple times. +// Prompt: Cache generated barcode images in memory to avoid redundant regeneration for identical field sets. +// Tags: barcode, caching, memory, code128, qr, datamatrix, aspnet, aspose.barcode, image generation + using System; using System.Collections.Generic; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates in‑memory caching of barcode images generated with Aspose.BarCode. +/// Demonstrates in‑memory caching of barcode images to prevent duplicate generation. /// class Program { - // Simple in‑memory cache: key = symbology + code text, value = PNG bytes - private static readonly Dictionary _barcodeCache = new Dictionary(); - /// - /// Entry point. Generates barcodes and shows cache behavior. + /// Retrieves a barcode image from the cache or generates a new one if it does not exist. /// - static void Main() + /// The barcode symbology to use. + /// The text or data to encode. + /// Dictionary that stores previously generated images keyed by symbology and text. + /// A containing the generated barcode. + static Bitmap GetBarcodeImage(BaseEncodeType encodeType, string codeText, Dictionary cache) { - // First request – should generate a new image - byte[] img1 = GetBarcodeImage(EncodeTypes.Code128, "Sample123"); - Console.WriteLine($"Generated image size: {img1.Length} bytes"); + // Build a unique cache key from the encode type and the text. + string key = $"{encodeType}:{codeText}"; - // Second request with identical parameters – should hit the cache - byte[] img2 = GetBarcodeImage(EncodeTypes.Code128, "Sample123"); - Console.WriteLine($"Cached image size: {img2.Length} bytes"); + // Return the cached image if it already exists. + if (cache.TryGetValue(key, out Bitmap cachedImage)) + { + Console.WriteLine($"Cache hit for key: {key}"); + return cachedImage; + } - // Different barcode – new generation - byte[] img3 = GetBarcodeImage(EncodeTypes.QR, "https://example.com"); - Console.WriteLine($"Generated QR image size: {img3.Length} bytes"); + // No cached image – generate a new barcode. + Console.WriteLine($"Generating barcode for key: {key}"); + using (var generator = new BarcodeGenerator(encodeType, codeText)) + { + Bitmap image = generator.GenerateBarCodeImage(); + cache[key] = image; // Store the newly generated image for future requests. + return image; + } } - // Returns PNG bytes for the requested barcode, using the cache when possible - private static byte[] GetBarcodeImage(BaseEncodeType encodeType, string codeText) + /// + /// Entry point of the example. Generates several barcodes, some of which are duplicates, + /// to demonstrate caching. Saves each image to disk and disposes resources afterwards. + /// + static void Main() { - // Build a unique cache key from the encode type and the text to encode - string cacheKey = $"{encodeType.GetHashCode()}|{codeText}"; + // In‑memory cache: maps a unique key to a barcode bitmap. + var barcodeCache = new Dictionary(); - // Try to retrieve a cached image - if (_barcodeCache.TryGetValue(cacheKey, out byte[] cachedBytes)) + // Define a set of barcode requests; duplicates are intentional to test caching. + var requests = new (BaseEncodeType type, string text)[] { - Console.WriteLine("Cache hit for key: " + cacheKey); - return cachedBytes; - } + (EncodeTypes.Code128, "123ABC"), + (EncodeTypes.QR, "https://example.com"), + (EncodeTypes.Code128, "123ABC"), // duplicate + (EncodeTypes.DataMatrix, "DataMatrixSample"), + (EncodeTypes.QR, "https://example.com") // duplicate + }; - // Cache miss – generate a new barcode image - Console.WriteLine("Cache miss – generating barcode for key: " + cacheKey); - using (var generator = new BarcodeGenerator(encodeType, codeText)) + // Process each request, retrieving from cache or generating as needed. + for (int i = 0; i < requests.Length; i++) { - // Set a modest image size and resolution - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - generator.Parameters.Resolution = 300f; + var (type, text) = requests[i]; + Bitmap barcodeImage = GetBarcodeImage(type, text, barcodeCache); - using (var ms = new MemoryStream()) + // Save each image with a unique filename for verification. + string fileName = $"barcode_{i + 1}.png"; + using (var fileStream = System.IO.File.OpenWrite(fileName)) { - // Save directly to the stream in PNG format - generator.Save(ms, BarCodeImageFormat.Png); - byte[] imageBytes = ms.ToArray(); - - // Store the generated image in the cache for future requests - _barcodeCache[cacheKey] = imageBytes; - return imageBytes; + barcodeImage.Save(fileStream, ImageFormat.Png); } + + Console.WriteLine($"Saved barcode to {fileName}"); } + + // Dispose all cached bitmaps before exiting to free unmanaged resources. + foreach (var kvp in barcodeCache) + { + kvp.Value.Dispose(); + } + + Console.WriteLine("All barcodes processed. Press any key to exit."); + Console.ReadKey(); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/compare-generation-time-and-image-size-between-mailmark-type-7-and-type-29-barcodes.cs b/mailmark-two-dimensional-barcode/compare-generation-time-and-image-size-between-mailmark-type-7-and-type-29-barcodes.cs index af0610f..0694064 100644 --- a/mailmark-two-dimensional-barcode/compare-generation-time-and-image-size-between-mailmark-type-7-and-type-29-barcodes.cs +++ b/mailmark-two-dimensional-barcode/compare-generation-time-and-image-size-between-mailmark-type-7-and-type-29-barcodes.cs @@ -1,79 +1,121 @@ +// Title: Mailmark 2D Barcode Generation Time and Image Size Comparison +// Description: Demonstrates how to generate Mailmark type 7 and type 29 barcodes, measuring the time taken and the resulting PNG file size. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex 2‑D symbologies. It showcases the use of Mailmark2DCodetext, ComplexBarcodeGenerator, and AutoSizeMode to create Mailmark barcodes, a common requirement for postal and logistics applications where performance and payload size matter. Developers often need to benchmark different Mailmark matrix types to choose the optimal configuration for their workflow. +// Prompt: Compare generation time and image size between Mailmark type 7 and type 29 barcodes. +// Tags: mailmark, barcode, generation, performance, image size, aspose.barcode, complexbarcode, 2d symbology + using System; using System.Diagnostics; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; -using Aspose.Drawing.Imaging; /// -/// Demonstrates generation and timing of Mailmark 2D barcodes (Type 7 and Type 29) using Aspose.BarCode. +/// Provides an entry point that compares the generation time and PNG image size of +/// Mailmark type 7 (24×24) and type 29 (16×48) barcodes using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. Generates two Mailmark barcodes, measures generation time, - /// and outputs the elapsed time and image size for each type. + /// Prepares common Mailmark fields and invokes the comparison for both matrix types. /// static void Main() { - // Prepare two Mailmark 2D codetext objects: one for Type 7 and one for Type 29 - var mailmark7 = CreateMailmark2DCodetext(Mailmark2DType.Type_7); - var mailmark29 = CreateMailmark2DCodetext(Mailmark2DType.Type_29); + // Common Mailmark2D fields shared by both barcode types + const string versionId = "1"; + const string informationTypeId = "0"; + const string classCode = "0"; + const string rtsFlag = "0"; + int supplyChainId = 384224; + int itemId = 16563762; + const string destinationPostCodePlusDps = "EF61AH8T "; - // Generate barcode for Type 7, measure time and size, then display results - var result7 = GenerateAndMeasure(mailmark7); - Console.WriteLine($"Mailmark Type 7 - Generation Time: {result7.timeMs} ms, Image Size: {result7.sizeBytes} bytes"); + // Compare Type 7 (24x24) and Type 29 (16x48) matrix configurations + CompareMailmark2D( + Mailmark2DType.Type_7, + "Type 7 (24x24)", + versionId, + informationTypeId, + classCode, + rtsFlag, + supplyChainId, + itemId, + destinationPostCodePlusDps); - // Generate barcode for Type 29, measure time and size, then display results - var result29 = GenerateAndMeasure(mailmark29); - Console.WriteLine($"Mailmark Type 29 - Generation Time: {result29.timeMs} ms, Image Size: {result29.sizeBytes} bytes"); + CompareMailmark2D( + Mailmark2DType.Type_29, + "Type 29 (16x48)", + versionId, + informationTypeId, + classCode, + rtsFlag, + supplyChainId, + itemId, + destinationPostCodePlusDps); } - // Creates a Mailmark2DCodetext instance with required fields and the specified DataMatrix type. - private static Mailmark2DCodetext CreateMailmark2DCodetext(Mailmark2DType matrixType) + /// + /// Generates a Mailmark barcode of the specified matrix type, measures the generation time, + /// and reports the resulting PNG image size. + /// + /// The Mailmark matrix type (e.g., Type_7 or Type_29). + /// A friendly label used in console output. + /// Version identifier for the Mailmark. + /// Information type identifier. + /// Class code of the Mailmark. + /// RTS flag value. + /// Supply chain identifier. + /// Item identifier. + /// Destination postcode plus DPS. + static void CompareMailmark2D( + Mailmark2DType matrixType, + string label, + string versionId, + string informationTypeId, + string classCode, + string rtsFlag, + int supplyChainId, + int itemId, + string destinationPostCodePlusDps) { + // Build the Mailmark2DCodetext object with all required fields var mailmark = new Mailmark2DCodetext { - // Required integer fields - ItemID = 16563762, - SupplyChainID = 384224, - - // Required string fields - VersionID = "1", - InformationTypeID = "0", - DestinationPostCodeAndDPS = "EF61AH8T ", - RTSFlag = "0", - - // Set the 2D Mailmark size (type) + VersionID = versionId, + InformationTypeID = informationTypeId, + Class = classCode, + RTSFlag = rtsFlag, + SupplyChainID = supplyChainId, + ItemID = itemId, + DestinationPostCodeAndDPS = destinationPostCodePlusDps, DataMatrixType = matrixType }; - // Optional: leave CustomerContent empty (default) and use default encode mode - return mailmark; - } - - // Generates the barcode image, measures elapsed time, and returns both the time (ms) and image size (bytes). - private static (long timeMs, long sizeBytes) GenerateAndMeasure(Mailmark2DCodetext mailmark) - { + // Start timing the barcode generation process var stopwatch = new Stopwatch(); + stopwatch.Start(); - // Use a memory stream to avoid writing to disk - using (var ms = new MemoryStream()) + // Generate the barcode using ComplexBarcodeGenerator + using (var generator = new ComplexBarcodeGenerator(mailmark)) { - stopwatch.Start(); + // Explicitly set auto‑size mode to interpolation (default, but clarified) + generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - // Generate the barcode and save it as PNG directly into the memory stream - using (var generator = new ComplexBarcodeGenerator(mailmark)) + // Save the barcode to a memory stream in PNG format + using (var ms = new MemoryStream()) { generator.Save(ms, BarCodeImageFormat.Png); - } + stopwatch.Stop(); // Stop timing after the image is saved - stopwatch.Stop(); + long imageSize = ms.Length; // Size in bytes of the generated PNG - // Determine the size of the generated image in bytes - long size = ms.Length; - return (stopwatch.ElapsedMilliseconds, size); + // Output the results to the console + Console.WriteLine($"{label}:"); + Console.WriteLine($" Generation time: {stopwatch.ElapsedMilliseconds} ms"); + Console.WriteLine($" Image size: {imageSize} bytes"); + Console.WriteLine(); + } } } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/configure-complexbarcodegenerator-to-produce-300-dpi-png-image-with-custom-dimensions-for-printing.cs b/mailmark-two-dimensional-barcode/configure-complexbarcodegenerator-to-produce-300-dpi-png-image-with-custom-dimensions-for-printing.cs index 7788911..2c4012c 100644 --- a/mailmark-two-dimensional-barcode/configure-complexbarcodegenerator-to-produce-300-dpi-png-image-with-custom-dimensions-for-printing.cs +++ b/mailmark-two-dimensional-barcode/configure-complexbarcodegenerator-to-produce-300-dpi-png-image-with-custom-dimensions-for-printing.cs @@ -1,46 +1,50 @@ +// Title: Generate Swiss QR Bill Barcode with Custom DPI and Size +// Description: Demonstrates configuring ComplexBarcodeGenerator to create a 300 dpi PNG image with specific dimensions for printing a Swiss QR Bill. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use ComplexBarcodeGenerator and SwissQRCodetext to produce high‑resolution, printable barcodes. It highlights setting image resolution, custom dimensions, and colors—common tasks when integrating QR‑based payment codes into invoices or documents. Developers often need these settings to meet printing standards and branding requirements. +// Prompt: Configure ComplexBarcodeGenerator to produce a 300 dpi PNG image with custom dimensions for printing. +// Tags: swissqr, qr, barcode, generation, png, resolution, dimensions, complexbarcodegenerator, aspose.barcode + using System; -using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates generating a Swiss QR bill barcode image using Aspose.BarCode. +/// Example program that generates a Swiss QR Bill barcode with custom DPI and image size. /// class Program { /// - /// Entry point of the application. Creates a Swiss QR bill, configures barcode parameters, - /// and saves the generated barcode as a PNG file. + /// Entry point. Builds the Swiss QR codetext, configures the generator, and saves a PNG image. /// static void Main() { - // Create a Swiss QR code text object and populate required bill fields. + // Prepare SwissQR codetext with mandatory fields var swissQr = new SwissQRCodetext(); - swissQr.Bill.Creditor.Name = "John Doe"; // Creditor's name - swissQr.Bill.Creditor.CountryCode = "CH"; // Creditor's country (Switzerland) - swissQr.Bill.Account = "CH9300762011623852957"; // IBAN account number - swissQr.Bill.Amount = 199.95m; // Invoice amount - swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; // QR bill version + swissQr.Bill.Creditor.Name = "John Doe"; + swissQr.Bill.Creditor.CountryCode = "CH"; + swissQr.Bill.Account = "CH9300762011623852957"; + swissQr.Bill.Amount = 199.95m; + swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; - // Determine the output file path in the current working directory. - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "SwissQR.png"); - - // Initialize the complex barcode generator with the Swiss QR code data. + // Create ComplexBarcodeGenerator using the codetext using (var generator = new ComplexBarcodeGenerator(swissQr)) { - // Set the image resolution to 300 dots per inch (dpi) for high-quality output. + // Set image resolution to 300 dpi for high‑quality printing generator.Parameters.Resolution = 300f; - // Define custom image dimensions in points (1 point = 1/72 inch). - generator.Parameters.ImageWidth.Point = 300f; // Width of the barcode image - generator.Parameters.ImageHeight.Point = 150f; // Height of the barcode image + // Define custom image dimensions in points (1 point = 1/72 inch) + generator.Parameters.ImageWidth.Point = 600f; // approx 8.33 in + generator.Parameters.ImageHeight.Point = 400f; // approx 5.55 in + + // Optional: set background and barcode colors + generator.Parameters.BackColor = Color.White; + generator.Parameters.Barcode.BarColor = Color.Black; - // Save the generated barcode as a PNG file to the specified path. - generator.Save(outputPath, BarCodeImageFormat.Png); + // Save the barcode as a PNG file + generator.Save("SwissQR.png"); } - // Inform the user where the barcode image has been saved. - Console.WriteLine($"Barcode image saved to: {outputPath}"); + Console.WriteLine("Barcode image generated: SwissQR.png"); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/configure-complexbarcodegenerator-to-use-specific-module-size-for-higher-density-barcodes.cs b/mailmark-two-dimensional-barcode/configure-complexbarcodegenerator-to-use-specific-module-size-for-higher-density-barcodes.cs index b30ec47..6cedfc8 100644 --- a/mailmark-two-dimensional-barcode/configure-complexbarcodegenerator-to-use-specific-module-size-for-higher-density-barcodes.cs +++ b/mailmark-two-dimensional-barcode/configure-complexbarcodegenerator-to-use-specific-module-size-for-higher-density-barcodes.cs @@ -1,48 +1,47 @@ +// Title: Configure ComplexBarcodeGenerator with custom module size for high-density Swiss QR codes +// Description: Demonstrates setting a smaller XDimension on ComplexBarcodeGenerator to produce a higher density Swiss QR barcode. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, illustrating how to customize barcode parameters such as module size, resolution, and codetext using classes like ComplexBarcodeGenerator, SwissQRCodetext, and BarcodeParameters. Developers often need to adjust these settings to meet specific printing or scanning requirements, especially for QR codes used in financial documents. +// Prompt: Configure ComplexBarcodeGenerator to use a specific module size for higher density barcodes. +// Tags: barcode, complex barcode, module size, high density, swissqr, aspose.barcode, generation + using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.Drawing; /// -/// Demonstrates generating a Swiss QR code using Aspose.BarCode's ComplexBarcodeGenerator. +/// Demonstrates configuring a ComplexBarcodeGenerator to use a specific module size for higher density Swiss QR barcodes. /// class Program { /// - /// Entry point of the application. Creates a Swiss QR codetext, configures the generator, - /// and saves the resulting barcode image to a file. + /// Entry point of the example. Generates a Swiss QR code with a reduced XDimension for higher density and saves it as an image. /// static void Main() { - // Create a Swiss QR codetext object which holds bill information + // Prepare SwissQR codetext with required fields var swissQr = new SwissQRCodetext(); - - // Populate creditor details swissQr.Bill.Creditor.Name = "John Doe"; swissQr.Bill.Creditor.CountryCode = "CH"; - - // Set account number, amount, and QR bill version swissQr.Bill.Account = "CH9300762011623852957"; swissQr.Bill.Amount = 199.95m; swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; - // Initialize the ComplexBarcodeGenerator with the prepared codetext + // Create ComplexBarcodeGenerator with the codetext using (var generator = new ComplexBarcodeGenerator(swissQr)) { - // Configure a smaller XDimension (module size) for higher barcode density - generator.Parameters.Barcode.XDimension.Point = 0.5f; // 0.5 point per module + // Set a smaller module size (higher density) using XDimension + generator.Parameters.Barcode.XDimension.Point = 0.5f; - // Optionally increase the image resolution for better visual quality - generator.Parameters.Resolution = 300f; + // Optional: set image resolution + generator.Parameters.Resolution = 300; - // Define output file path + // Save the generated barcode image string outputPath = "SwissQR_HighDensity.png"; - - // Save the generated barcode as a PNG image - generator.Save(outputPath, BarCodeImageFormat.Png); - - // Inform the user where the file was saved - Console.WriteLine($"Barcode saved to {outputPath}"); + generator.Save(outputPath); + Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}"); } } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/create-console-application-that-prompts-users-for-mailmark-fields-and-saves-resulting-barcode-as-png.cs b/mailmark-two-dimensional-barcode/create-console-application-that-prompts-users-for-mailmark-fields-and-saves-resulting-barcode-as-png.cs index 33fc28a..d7d1760 100644 --- a/mailmark-two-dimensional-barcode/create-console-application-that-prompts-users-for-mailmark-fields-and-saves-resulting-barcode-as-png.cs +++ b/mailmark-two-dimensional-barcode/create-console-application-that-prompts-users-for-mailmark-fields-and-saves-resulting-barcode-as-png.cs @@ -1,93 +1,74 @@ +// Title: Generate Mailmark 4‑state barcode and save as PNG +// Description: Demonstrates prompting (or using command‑line) for Mailmark fields, creating a Mailmark barcode, and saving it as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Mailmark. It showcases the use of Aspose.BarCode.ComplexBarcode.MailmarkCodetext and ComplexBarcodeGenerator classes to encode postal data. Developers creating shipping labels, postal automation, or logistics solutions often need to generate Mailmark barcodes for UK postal services. +// Prompt: Create a console application that prompts users for Mailmark fields and saves the resulting barcode as PNG. +// Tags: mailmark, barcode, generation, png, console, aspose.barcode, complexbarcode + using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; -using Aspose.Drawing.Imaging; /// -/// Demonstrates generation of a Mailmark barcode using Aspose.BarCode. +/// Console application that creates a Mailmark 4‑state barcode from user‑provided data +/// and saves the result as a PNG file. /// class Program { /// - /// Entry point of the application. - /// Parses optional command‑line arguments, validates input, creates a MailmarkCodetext, - /// generates the barcode, and saves it to a PNG file. + /// Entry point. Parses command‑line arguments (or uses defaults), builds a MailmarkCodetext, + /// generates the barcode, and writes it to "mailmark.png" in the current directory. /// - /// - /// Optional arguments in the following order: - /// format versionId class supplyChainId itemId destinationPostCodePlusDps outputPath - /// + /// Optional arguments: format versionId class supplyChainId itemId destinationPostCodePlusDps static void Main(string[] args) { - // -------------------------------------------------------------------- - // Default Mailmark values (valid sample) - // -------------------------------------------------------------------- - int format = 4; // 4 – unspecified/default (4‑state) + // Default sample values for Mailmark 4‑state barcode + int format = 4; // 4 = unspecified/default int versionId = 1; - string mailClass = "0"; // string property + string classValue = "0"; // "0" – Null or Test int supplyChainId = 384224; int itemId = 16563762; - string destinationPostCodePlusDps = "EF61AH8T "; // 9‑char string with trailing spaces - string outputPath = "mailmark.png"; + string destinationPostCodePlusDps = "EF61AH8T "; - // -------------------------------------------------------------------- - // Parse command‑line arguments if provided. - // Expected order: format versionId class supplyChainId itemId destinationPostCodePlusDps outputPath - // -------------------------------------------------------------------- - try - { - if (args.Length >= 7) - { - format = int.Parse(args[0]); - versionId = int.Parse(args[1]); - mailClass = args[2]; - supplyChainId = int.Parse(args[3]); - itemId = int.Parse(args[4]); - destinationPostCodePlusDps = args[5]; - outputPath = args[6]; - } - } - catch (Exception ex) + // If command‑line arguments are provided, try to parse them. + // Expected order: format versionId class supplyChainId itemId destinationPostCodePlusDps + if (args.Length >= 6) { - // Inform the user about parsing errors and fall back to defaults. - Console.WriteLine($"Argument parsing error: {ex.Message}"); - Console.WriteLine("Using default values."); + int.TryParse(args[0], out format); + int.TryParse(args[1], out versionId); + classValue = args[2]; + int.TryParse(args[3], out supplyChainId); + int.TryParse(args[4], out itemId); + destinationPostCodePlusDps = args[5]; } - // -------------------------------------------------------------------- - // Validate required string length (basic check) - // -------------------------------------------------------------------- - if (destinationPostCodePlusDps.Length != 9) + // Validate that the destination postcode plus DPS is not empty. + if (string.IsNullOrWhiteSpace(destinationPostCodePlusDps)) { - Console.WriteLine("DestinationPostCodePlusDPS must be exactly 9 characters. Using default value."); + Console.WriteLine("Invalid DestinationPostCodePlusDPS. Using default value."); destinationPostCodePlusDps = "EF61AH8T "; } - // -------------------------------------------------------------------- - // Build Mailmark codetext object with the collected parameters - // -------------------------------------------------------------------- + // Create and populate the MailmarkCodetext object. var mailmark = new MailmarkCodetext { Format = format, VersionID = versionId, - Class = mailClass, + Class = classValue, SupplychainID = supplyChainId, ItemID = itemId, DestinationPostCodePlusDPS = destinationPostCodePlusDps }; - // -------------------------------------------------------------------- - // Generate and save the Mailmark barcode - // -------------------------------------------------------------------- + // Generate the barcode and save it as PNG. + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "mailmark.png"); using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Save the generated barcode as a PNG file. + // Save directly to file in PNG format. generator.Save(outputPath, BarCodeImageFormat.Png); } - // Output the full path of the saved file for user confirmation. - Console.WriteLine($"Mailmark barcode saved to: {Path.GetFullPath(outputPath)}"); + Console.WriteLine($"Mailmark barcode saved to: {outputPath}"); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/create-mailmark2dcodetext-instance-and-assign-routing-service-and-customer-data-values.cs b/mailmark-two-dimensional-barcode/create-mailmark2dcodetext-instance-and-assign-routing-service-and-customer-data-values.cs index ab44437..1dfca33 100644 --- a/mailmark-two-dimensional-barcode/create-mailmark2dcodetext-instance-and-assign-routing-service-and-customer-data-values.cs +++ b/mailmark-two-dimensional-barcode/create-mailmark2dcodetext-instance-and-assign-routing-service-and-customer-data-values.cs @@ -1,61 +1,56 @@ +// Title: Generate Mailmark 2D Barcode with Routing, Service, and Customer Data +// Description: Demonstrates creating a Mailmark2DCodetext instance, assigning routing, service, and customer data, and generating a PNG barcode image. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator and Mailmark2DCodetext to produce Mailmark 2D barcodes, a common requirement for postal automation and tracking solutions. Developers often need to set routing, service, and custom payload fields before rendering the barcode in various image formats. +// Prompt: Create a Mailmark2DCodetext instance and assign routing, service, and customer data values. +// Tags: mailmark, 2d, barcode, generation, png, aspose.barcode, complexbarcode, codetext, dataencoding + using System; using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; /// -/// Demonstrates generation of a Mailmark 2D barcode using Aspose.BarCode. +/// Example program that builds a Mailmark 2D barcode by populating routing, +/// service, and customer data fields, then saves the result as a PNG image. /// class Program { /// - /// Entry point of the application. Creates a Mailmark2DCodetext, configures its fields, - /// generates the barcode, and saves it as a PNG file. + /// Entry point of the example. Creates a Mailmark2DCodetext, sets required + /// properties, generates the barcode, and writes it to disk. /// static void Main() { // Instantiate a Mailmark2DCodetext object to hold barcode data. var mailmark2d = new Mailmark2DCodetext(); - // ------------------------- - // Routing information - // ------------------------- - // Post code and DPS (Delivery Point Suffix) – note the trailing space is required. + // Set routing information: destination postcode plus DPS (trailing space required). mailmark2d.DestinationPostCodeAndDPS = "EF61AH8T "; - // ------------------------- - // Service / class information - // ------------------------- - mailmark2d.VersionID = "1"; // Version identifier - mailmark2d.InformationTypeID = "0"; // Information type identifier - mailmark2d.Class = "1"; // Class of the item - mailmark2d.RTSFlag = "0"; // Return‑to‑sender flag - - // ------------------------- - // Customer data - // ------------------------- - mailmark2d.SupplyChainID = 1234567; // Supply chain identifier - mailmark2d.ItemID = 12345678; // Unique item identifier - mailmark2d.CustomerContent = "CUSTOMER123"; // Optional customer content - // Encoding mode for the customer content (C40 is a compact alphanumeric mode). + // Set service information: information type ID, class, version, and RTS flag. + mailmark2d.InformationTypeID = "0"; // example service type + mailmark2d.Class = "1"; // example class + mailmark2d.VersionID = "1"; // version identifier + mailmark2d.RTSFlag = "0"; // return‑to‑sender flag + + // Set customer-specific data and its encoding mode. + mailmark2d.CustomerContent = "CUSTOMER123"; mailmark2d.CustomerContentEncodeMode = DataMatrixEncodeMode.C40; - // Determines the size of the DataMatrix barcode; Auto lets the library choose. - mailmark2d.DataMatrixType = Mailmark2DType.Auto; - // ------------------------- - // Barcode generation and saving - // ------------------------- - string outputPath = "mailmark2d.png"; + // Populate additional required fields with sample values. + mailmark2d.SupplyChainID = 384224; + mailmark2d.ItemID = 16563762; + mailmark2d.UPUCountryID = "GB"; - // Use ComplexBarcodeGenerator to create the barcode image. + // Use ComplexBarcodeGenerator to create the barcode based on the codetext. using (var generator = new ComplexBarcodeGenerator(mailmark2d)) { - // Save the generated barcode as a PNG file. + // Define output file path and save the barcode as a PNG image. + const string outputPath = "mailmark2d.png"; generator.Save(outputPath, BarCodeImageFormat.Png); - } - // Output the full path of the saved file for user confirmation. - Console.WriteLine($"Mailmark 2D barcode saved to: {Path.GetFullPath(outputPath)}"); + // Inform the user where the file was saved. + Console.WriteLine($"Mailmark 2D barcode saved to {Path.GetFullPath(outputPath)}"); + } } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/deserialize-json-back-into-mailmark2dcodetext-instance-and-generate-corresponding-barcode.cs b/mailmark-two-dimensional-barcode/deserialize-json-back-into-mailmark2dcodetext-instance-and-generate-corresponding-barcode.cs index 3336cde..317e6ab 100644 --- a/mailmark-two-dimensional-barcode/deserialize-json-back-into-mailmark2dcodetext-instance-and-generate-corresponding-barcode.cs +++ b/mailmark-two-dimensional-barcode/deserialize-json-back-into-mailmark2dcodetext-instance-and-generate-corresponding-barcode.cs @@ -1,80 +1,86 @@ +// Title: Generate Mailmark 2D barcode from JSON data +// Description: Demonstrates deserializing a Mailmark2DCodetext JSON payload and creating the corresponding 2‑D barcode image. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of Aspose.BarCode.ComplexBarcode.ComplexBarcodeGenerator together with Aspose.BarCode.ComplexBarcode.Mailmark2DCodetext to produce Mailmark 2D symbols. Developers working with postal services, logistics, or any scenario requiring Mailmark encoding can follow similar patterns for serialization, deserialization, and barcode rendering. +// Prompt: Deserialize JSON back into a Mailmark2DCodetext instance and generate the corresponding barcode. +// Tags: mailmark,2d barcode,serialization,deserialization,aspose.barcode,generation,json + using System; using System.IO; using System.Text.Json; +using System.Text.Json.Serialization; using Aspose.BarCode; -using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; +using Aspose.BarCode.ComplexBarcode; +using Aspose.Drawing; /// -/// Demonstrates generating a Mailmark 2D barcode from JSON data using Aspose.BarCode. +/// Example program that deserializes a Mailmark2DCodetext JSON string +/// and generates a Mailmark 2D barcode image using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Performs JSON deserialization, + /// creates a ComplexBarcodeGenerator, and saves the barcode image. /// static void Main() { - // Sample JSON representing a Mailmark2DCodetext object. - // In a real scenario this could be read from a file or other source. + // Sample JSON representing a Mailmark2DCodetext. string json = @"{ - ""VersionID"": ""1"", - ""InformationTypeID"": ""0"", ""Class"": ""1"", - ""RTSFlag"": ""0"", - ""SupplyChainID"": 384224, - ""ItemID"": 16563762, + ""CustomerContent"": ""SampleCustomer"", + ""CustomerContentEncodeMode"": ""C40"", ""DestinationPostCodeAndDPS"": ""EF61AH8T "", + ""InformationTypeID"": ""0"", + ""ItemID"": 16563762, ""ReturnToSenderPostCode"": ""SW1A1AA"", + ""RTSFlag"": ""0"", + ""SupplyChainID"": 384224, ""UPUCountryID"": ""GB"", - ""DataMatrixType"": 0, - ""CustomerContent"": ""Sample customer data"", - ""CustomerContentEncodeMode"": 0 + ""VersionID"": ""1"" }"; - // Deserialize JSON into a Mailmark2DCodetext instance. - Mailmark2DCodetext mailmark2d; + // Configure JSON options to handle enums as strings and ignore case. + var options = new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + // Deserialize JSON into the Aspose Mailmark2DCodetext object. + Mailmark2DCodetext mailmark; try { - mailmark2d = JsonSerializer.Deserialize(json); - if (mailmark2d == null) - throw new ArgumentException("Deserialization resulted in null."); + mailmark = JsonSerializer.Deserialize(json, options); + if (mailmark == null) + throw new InvalidOperationException("Deserialization returned null."); } catch (Exception ex) { - // Output error and abort if JSON cannot be deserialized. Console.WriteLine($"Failed to deserialize JSON: {ex.Message}"); return; } - // Validate that required single‑character string properties meet API constraints. - if (mailmark2d.VersionID?.Length != 1 || - mailmark2d.InformationTypeID?.Length != 1 || - mailmark2d.Class?.Length != 1 || - mailmark2d.RTSFlag?.Length != 1) - { - Console.WriteLine("One of the required single‑character string properties is invalid."); - return; - } - // Define the output file path for the generated barcode image. string outputPath = "mailmark2d.png"; // Generate the Mailmark 2D barcode using ComplexBarcodeGenerator. try { - using (var generator = new ComplexBarcodeGenerator(mailmark2d)) + using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Save the barcode image to a PNG file. - generator.Save(outputPath, BarCodeImageFormat.Png); + // Optional: set foreground and background colors. + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Save the barcode image to the specified file. + generator.Save(outputPath); } - // Inform the user where the barcode image was saved. Console.WriteLine($"Barcode generated and saved to '{Path.GetFullPath(outputPath)}'."); } catch (Exception ex) { - // Output any errors that occur during barcode generation. Console.WriteLine($"Barcode generation failed: {ex.Message}"); } } diff --git a/mailmark-two-dimensional-barcode/develop-reusable-helper-method-that-accepts-mailmark-fields-and-returns-generated-barcode-image-stream.cs b/mailmark-two-dimensional-barcode/develop-reusable-helper-method-that-accepts-mailmark-fields-and-returns-generated-barcode-image-stream.cs index ff4fef0..9e05cd6 100644 --- a/mailmark-two-dimensional-barcode/develop-reusable-helper-method-that-accepts-mailmark-fields-and-returns-generated-barcode-image-stream.cs +++ b/mailmark-two-dimensional-barcode/develop-reusable-helper-method-that-accepts-mailmark-fields-and-returns-generated-barcode-image-stream.cs @@ -1,92 +1,81 @@ +// Title: Generate Mailmark barcode and return image stream +// Description: Demonstrates creating a Mailmark barcode using Aspose.BarCode and returning it as a MemoryStream for further processing or saving. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on Mailmark symbology. It showcases the use of ComplexBarcodeGenerator and MailmarkCodetext classes to encode required fields, a common task for developers integrating postal barcode solutions into .NET applications. +// Prompt: Develop a reusable helper method that accepts Mailmark fields and returns a generated barcode image stream. +// Tags: mailmark, barcode, generation, stream, aspose.barcode, complexbarcodegenerator, png + using System; using System.IO; using Aspose.BarCode; -using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; +using Aspose.BarCode.ComplexBarcode; -namespace MailmarkBarcodeExample +/// +/// Provides an example of generating a Mailmark barcode and saving it as an image file. +/// +class Program { - /// - /// Demonstrates generation of a Mailmark barcode using Aspose.BarCode. - /// - class Program + // Helper method that creates a Mailmark barcode and returns the image as a MemoryStream. + // Parameters correspond to the required Mailmark fields. + static MemoryStream GenerateMailmarkBarcode(int format, int versionId, string @class, + int supplychainId, int itemId, string destinationPostCodePlusDps) { - /// - /// Entry point of the application. Generates a Mailmark barcode and saves it as a PNG file. - /// - static void Main() - { - // Sample Mailmark data - int format = 4; // 4‑state format - int versionId = 1; - string classCode = "0"; // Test class - int supplyChainId = 384224; - int itemId = 16563762; - string destinationPostCodePlusDPS = "EF61AH8T "; + // Validate required string parameters. + if (string.IsNullOrWhiteSpace(@class)) + throw new ArgumentException("Class cannot be null or empty.", nameof(@class)); + if (string.IsNullOrWhiteSpace(destinationPostCodePlusDps)) + throw new ArgumentException("DestinationPostCodePlusDPS cannot be null or empty.", nameof(destinationPostCodePlusDps)); - // Generate the barcode image as a memory stream - using (MemoryStream barcodeStream = GenerateMailmarkBarcode( - format, - versionId, - classCode, - supplyChainId, - itemId, - destinationPostCodePlusDPS)) - { - // Save the stream to a file for verification - using (FileStream file = File.Create("mailmark.png")) - { - barcodeStream.CopyTo(file); - } + // Populate the MailmarkCodetext object with the mandatory fields. + var mailmark = new MailmarkCodetext + { + Format = format, // 1 = Letter, 2 = Large Letter, 4 = unspecified/default + VersionID = versionId, // typically 1 + Class = @class, // e.g., "0" + SupplychainID = supplychainId, // up to 999999 + ItemID = itemId, // up to 99999999 + DestinationPostCodePlusDPS = destinationPostCodePlusDps // e.g., "EF61AH8T " + }; - Console.WriteLine("Mailmark barcode generated and saved as 'mailmark.png'."); - } + // Generate the barcode image into a memory stream. + var stream = new MemoryStream(); + using (var generator = new ComplexBarcodeGenerator(mailmark)) + { + generator.Save(stream, BarCodeImageFormat.Png); } - /// - /// Generates a Mailmark barcode image and returns it as a . - /// - /// Mailmark format (e.g., 4 for 4‑state). - /// Version identifier. - /// Class code as a string. - /// Supply chain identifier. - /// Item identifier. - /// Destination postcode plus DPS (9‑character string). - /// MemoryStream containing the PNG image of the generated barcode. - public static MemoryStream GenerateMailmarkBarcode( - int format, - int versionId, - string classCode, - int supplyChainId, - int itemId, - string destinationPostCodePlusDPS) - { - // Validate required string parameters - if (string.IsNullOrEmpty(classCode)) - throw new ArgumentException("Class code must be provided.", nameof(classCode)); - if (string.IsNullOrEmpty(destinationPostCodePlusDPS)) - throw new ArgumentException("DestinationPostCodePlusDPS must be provided.", nameof(destinationPostCodePlusDPS)); + // Reset stream position for callers. + stream.Position = 0; + return stream; + } - // Populate the MailmarkCodetext object with supplied values - MailmarkCodetext mailmark = new MailmarkCodetext - { - Format = format, - VersionID = versionId, - Class = classCode, - SupplychainID = supplyChainId, - ItemID = itemId, - DestinationPostCodePlusDPS = destinationPostCodePlusDPS - }; + /// + /// Entry point demonstrating the GenerateMailmarkBarcode helper and saving the result to a file. + /// + static void Main() + { + // Sample data based on the documented valid example. + int format = 4; // unspecified/default (4-state) + int versionId = 1; + string @class = "0"; + int supplychainId = 384224; + int itemId = 16563762; + string destinationPostCodePlusDps = "EF61AH8T "; + + // Generate the barcode. + using (MemoryStream barcodeStream = GenerateMailmarkBarcode(format, versionId, @class, + supplychainId, itemId, destinationPostCodePlusDps)) + { + // For demonstration, write the stream length and optionally save to a file. + Console.WriteLine($"Generated Mailmark barcode image size: {barcodeStream.Length} bytes"); - // Generate the barcode using ComplexBarcodeGenerator - using (ComplexBarcodeGenerator generator = new ComplexBarcodeGenerator(mailmark)) + // Save to a file named "mailmark.png" in the current directory. + using (FileStream file = new FileStream("mailmark.png", FileMode.Create, FileAccess.Write)) { - MemoryStream ms = new MemoryStream(); - // Save as PNG; BarCodeImageFormat is defined in Aspose.BarCode.Generation - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for reading by the caller - return ms; + barcodeStream.CopyTo(file); } + + Console.WriteLine("Barcode image saved as 'mailmark.png'."); } } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/encode-customer-information-with-alternative-encoding-and-assess-its-impact-on-barcode-capacity.cs b/mailmark-two-dimensional-barcode/encode-customer-information-with-alternative-encoding-and-assess-its-impact-on-barcode-capacity.cs index 0fe221d..e589653 100644 --- a/mailmark-two-dimensional-barcode/encode-customer-information-with-alternative-encoding-and-assess-its-impact-on-barcode-capacity.cs +++ b/mailmark-two-dimensional-barcode/encode-customer-information-with-alternative-encoding-and-assess-its-impact-on-barcode-capacity.cs @@ -1,65 +1,60 @@ +// Title: Encode Customer Information with UTF-8 and Compare QR Code Capacity +// Description: Demonstrates generating QR codes using the default Unicode (UTF-16) encoding and an alternative UTF-8 encoding, then compares their byte counts to evaluate the impact on barcode data capacity. +// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on QR code creation and text encoding manipulation. It showcases the BarcodeGenerator class, EncodeTypes enumeration, and SetCodeText method—common tools for developers who need to optimize barcode size, support international characters, or assess encoding effects on data capacity. +// Prompt: Encode customer information with an alternative encoding and assess its impact on barcode capacity. +// Tags: qr, encoding, capacity, aspose.barcode, generation + using System; +using System.Text; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Demonstrates generating Australia Post barcodes with different -/// values. +/// Generates QR codes from a sample customer string using default Unicode encoding and UTF-8 encoding, +/// then compares the byte counts to illustrate how encoding choice affects barcode capacity. /// class Program { /// - /// Entry point that creates barcodes for each test case and prints results. + /// Entry point of the example. Creates two QR codes with different text encodings and prints capacity analysis. /// static void Main() { - // Define test cases: each tuple contains the encoding type, the text to encode, and the output file name. - var testCases = new (CustomerInformationInterpretingType Encoding, string CodeText, string FileName)[] - { - (CustomerInformationInterpretingType.CTable, "ABC123XYZ", "AustraliaPost_CTable.png"), - (CustomerInformationInterpretingType.NTable, "1234567890", "AustraliaPost_NTable.png"), - (CustomerInformationInterpretingType.Other, "12", "AustraliaPost_Other.png") - }; + // Sample customer information to encode + string customerInfo = "John Doe 12345"; - // Iterate over each test case and attempt to generate the corresponding barcode. - foreach (var (encoding, codeText, fileName) in testCases) + // File paths for the generated barcode images + string defaultPath = "qr_default.png"; + string utf8Path = "qr_utf8.png"; + + // Generate QR code using the default encoding (Unicode/UTF-16 internal representation) + using (var generator = new BarcodeGenerator(EncodeTypes.QR)) { - try - { - // Create a barcode generator for the Australia Post symbology with the specified code text. - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText)) - { - // Apply the selected customer information interpreting type (alternative encoding table). - generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = encoding; + generator.CodeText = customerInfo; // Assign text with default encoding + generator.Save(defaultPath); // Save image to file + } - // Set a white background to make the generated images easier to view. - generator.Parameters.BackColor = Color.White; + // Generate QR code using an alternative UTF-8 encoding via SetCodeText + using (var generatorUtf8 = new BarcodeGenerator(EncodeTypes.QR)) + { + generatorUtf8.SetCodeText(customerInfo, Encoding.UTF8); // Explicit UTF-8 encoding + generatorUtf8.Save(utf8Path); // Save image to file + } - // Save the generated barcode image to the specified file. - generator.Save(fileName); + // Assess the impact on barcode capacity by comparing byte counts of each encoding + int defaultByteCount = Encoding.Unicode.GetByteCount(customerInfo); // UTF-16 byte count + int utf8ByteCount = Encoding.UTF8.GetByteCount(customerInfo); // UTF-8 byte count - // Write details about the successful generation to the console. - Console.WriteLine($"Generated {fileName}"); - Console.WriteLine($" Encoding type : {encoding}"); - Console.WriteLine($" CodeText length: {codeText.Length}"); - Console.WriteLine($" CodeText value : {codeText}"); - Console.WriteLine(); - } - } - catch (Exception ex) - { - // If generation fails (e.g., invalid code text for the chosen encoding), report the error. - Console.WriteLine($"Failed to generate {fileName} with encoding {encoding}"); - Console.WriteLine($" Reason: {ex.Message}"); - Console.WriteLine(); - } - } + // Output the original data and byte count comparison + Console.WriteLine("Customer Information: " + customerInfo); + Console.WriteLine("Default (UTF-16) byte count: " + defaultByteCount); + Console.WriteLine("Alternative (UTF-8) byte count: " + utf8ByteCount); + Console.WriteLine("Impact on capacity: " + (utf8ByteCount < defaultByteCount + ? "UTF-8 uses fewer bytes, allowing more data in the same QR version." + : "UTF-8 uses equal or more bytes, potentially reducing capacity.")); - // Provide a brief assessment of how each encoding type impacts data capacity. - Console.WriteLine("Capacity Impact Assessment:"); - Console.WriteLine("- CTable allows alphanumeric characters, enabling longer mixed strings."); - Console.WriteLine("- NTable restricts to digits only, limiting the character set but still supports long numeric strings."); - Console.WriteLine("- Other permits only a few symbols (0‑3 characters), resulting in the smallest capacity."); + // Inform the user where the barcode images have been saved + Console.WriteLine("QR code with default encoding saved to: " + defaultPath); + Console.WriteLine("QR code with UTF-8 encoding saved to: " + utf8Path); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/extract-individual-fields-such-as-routing-and-service-code-from-decoded-mailmark2dcodetext.cs b/mailmark-two-dimensional-barcode/extract-individual-fields-such-as-routing-and-service-code-from-decoded-mailmark2dcodetext.cs index ead1941..f17cfc9 100644 --- a/mailmark-two-dimensional-barcode/extract-individual-fields-such-as-routing-and-service-code-from-decoded-mailmark2dcodetext.cs +++ b/mailmark-two-dimensional-barcode/extract-individual-fields-such-as-routing-and-service-code-from-decoded-mailmark2dcodetext.cs @@ -1,65 +1,78 @@ +// Title: Extract fields from Mailmark2D barcode codetext +// Description: Demonstrates creating a Mailmark2D codetext, generating a barcode image, decoding the codetext, and extracting individual fields such as routing and service code. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode operations collection. It showcases the use of Aspose.BarCode.ComplexBarcode classes (Mailmark2DCodetext, ComplexBarcodeGenerator, ComplexCodetextReader) for generating and recognizing Mailmark2D barcodes. Typical scenarios include postal automation, logistics tracking, and mail sorting where developers need to encode, decode, and manipulate individual data elements within a Mailmark2D symbol. +// Prompt: Extract individual fields such as routing and service code from the decoded Mailmark2DCodetext. +// Tags: mailmark2d, barcode, extraction, complexbarcode, generation, recognition, c# + using System; +using System.IO; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates encoding and decoding of a Mailmark2D codetext using Aspose.BarCode. +/// Example program that creates a Mailmark2D barcode, decodes it, and extracts its individual data fields. /// class Program { /// - /// Entry point of the application. Creates a sample Mailmark2D object, encodes it, - /// decodes the resulting string, and prints all fields to the console. + /// Entry point of the example. Performs the full lifecycle: construct codetext, generate barcode, decode, and display fields. /// static void Main() { - // -------------------------------------------------------------------- - // 1. Create a sample Mailmark2DCodetext object with known values. - // -------------------------------------------------------------------- + // ------------------------------------------------------------ + // 1. Create a Mailmark2D codetext object and populate its fields. + // ------------------------------------------------------------ var mailmark2d = new Mailmark2DCodetext { + InformationTypeID = "0", // Domestic Sorted & Unsorted (routing) VersionID = "1", - InformationTypeID = "0", - Class = "1", // Service code + Class = "1", // Example class (service code) RTSFlag = "0", - SupplyChainID = 384224, // Routing code - ItemID = 16563762, - DestinationPostCodeAndDPS = "EF61AH8T " + DestinationPostCodeAndDPS = "EC1A1BB", // Sample postcode + DPS + SupplyChainID = 1234567, + ItemID = 7654321, + UPUCountryID = "GBR" }; - // -------------------------------------------------------------------- - // 2. Construct the encoded codetext string from the object. - // -------------------------------------------------------------------- - string encodedCodetext = mailmark2d.GetConstructedCodetext(); + // ------------------------------------------------------------ + // 2. Construct the raw codetext string from the populated object. + // ------------------------------------------------------------ + string constructedCodetext = mailmark2d.GetConstructedCodetext(); - // -------------------------------------------------------------------- - // 3. Decode the codetext back to a Mailmark2DCodetext object. - // -------------------------------------------------------------------- - Mailmark2DCodetext decoded = ComplexCodetextReader.TryDecodeMailmark2D(encodedCodetext); + // ------------------------------------------------------------ + // 3. (Optional) Generate a barcode image to demonstrate full lifecycle. + // ------------------------------------------------------------ + using (var generator = new ComplexBarcodeGenerator(mailmark2d)) + { + using (var ms = new MemoryStream()) + { + generator.Save(ms, BarCodeImageFormat.Png); + // The MemoryStream now contains PNG data; it is not used further in this example. + } + } - // -------------------------------------------------------------------- - // 4. Verify decoding succeeded; if not, report the failure and exit. - // -------------------------------------------------------------------- + // ------------------------------------------------------------ + // 4. Decode the constructed codetext back into a Mailmark2DCodetext object. + // ------------------------------------------------------------ + Mailmark2DCodetext decoded = ComplexCodetextReader.TryDecodeMailmark2D(constructedCodetext); if (decoded == null) { Console.WriteLine("Failed to decode Mailmark2D codetext."); return; } - // -------------------------------------------------------------------- + // ------------------------------------------------------------ // 5. Extract and display individual fields from the decoded object. - // -------------------------------------------------------------------- + // ------------------------------------------------------------ Console.WriteLine("Decoded Mailmark2D fields:"); - Console.WriteLine($"VersionID: {decoded.VersionID}"); - Console.WriteLine($"InformationTypeID: {decoded.InformationTypeID}"); + Console.WriteLine($"Information Type ID (Routing): {decoded.InformationTypeID}"); + Console.WriteLine($"Version ID: {decoded.VersionID}"); Console.WriteLine($"Class (Service Code): {decoded.Class}"); - Console.WriteLine($"RTSFlag: {decoded.RTSFlag}"); - Console.WriteLine($"SupplyChainID (Routing Code): {decoded.SupplyChainID}"); - Console.WriteLine($"ItemID: {decoded.ItemID}"); - Console.WriteLine($"DestinationPostCodeAndDPS: {decoded.DestinationPostCodeAndDPS}"); - Console.WriteLine($"ReturnToSenderPostCode: {decoded.ReturnToSenderPostCode}"); - Console.WriteLine($"UPUCountryID: {decoded.UPUCountryID}"); - Console.WriteLine($"CustomerContent: {decoded.CustomerContent}"); - Console.WriteLine($"CustomerContentEncodeMode: {decoded.CustomerContentEncodeMode}"); - Console.WriteLine($"DataMatrixType: {decoded.DataMatrixType}"); + Console.WriteLine($"RTS Flag: {decoded.RTSFlag}"); + Console.WriteLine($"Destination Postcode + DPS: {decoded.DestinationPostCodeAndDPS}"); + Console.WriteLine($"Supply Chain ID: {decoded.SupplyChainID}"); + Console.WriteLine($"Item ID: {decoded.ItemID}"); + Console.WriteLine($"UPU Country ID: {decoded.UPUCountryID}"); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/generate-barcode-with-transparent-background-for-overlaying-on-other-graphics.cs b/mailmark-two-dimensional-barcode/generate-barcode-with-transparent-background-for-overlaying-on-other-graphics.cs index 4780b7a..e6a08e2 100644 --- a/mailmark-two-dimensional-barcode/generate-barcode-with-transparent-background-for-overlaying-on-other-graphics.cs +++ b/mailmark-two-dimensional-barcode/generate-barcode-with-transparent-background-for-overlaying-on-other-graphics.cs @@ -1,4 +1,11 @@ +// Title: Generate a Code128 barcode with transparent background +// Description: Demonstrates how to create a barcode image with a transparent background, suitable for overlaying on other graphics. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and drawing parameters to control visual appearance. Developers often need to produce barcodes that blend into existing UI or printed material without a solid background, and this snippet shows the typical steps for setting background transparency and saving as PNG. +// Prompt: Generate a barcode with a transparent background for overlaying on other graphics. +// Tags: code128, barcode, transparent background, png, aspose.barcode, image generation + using System; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; @@ -8,31 +15,30 @@ class Program { /// - /// Entry point of the application. Generates a barcode image and saves it to disk. + /// Entry point of the example. Creates a barcode, sets transparent background, and saves it as PNG. /// static void Main() { - // Define the output file path for the generated barcode image. + // Output file path string outputPath = "transparent_barcode.png"; - // Initialize a BarcodeGenerator for the Code128 symbology. - // The 'using' statement ensures the generator is properly disposed after use. + // Initialize the barcode generator for Code128 symbology using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Set the data to be encoded in the barcode. - generator.CodeText = "123ABC"; + // Text to encode into the barcode + generator.CodeText = "Sample123"; - // Configure the barcode appearance: - // - Make the background fully transparent. - // - Set the bar (foreground) color to black (optional, default is black). + // Set background to transparent so the image can be overlaid generator.Parameters.BackColor = Color.Transparent; + + // Optional: define the bar (foreground) color; default is black generator.Parameters.Barcode.BarColor = Color.Black; - // Save the generated barcode as a PNG file at the specified path. + // Save the barcode as PNG, which supports transparency generator.Save(outputPath); } - // Inform the user that the barcode has been saved successfully. + // Inform the user where the file was saved Console.WriteLine($"Barcode saved to {outputPath}"); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/generate-mailmark-type-7-barcode-image-using-specified-routing-and-service-code-fields.cs b/mailmark-two-dimensional-barcode/generate-mailmark-type-7-barcode-image-using-specified-routing-and-service-code-fields.cs index c272a23..76877aa 100644 --- a/mailmark-two-dimensional-barcode/generate-mailmark-type-7-barcode-image-using-specified-routing-and-service-code-fields.cs +++ b/mailmark-two-dimensional-barcode/generate-mailmark-type-7-barcode-image-using-specified-routing-and-service-code-fields.cs @@ -1,57 +1,53 @@ +// Title: Generate Mailmark Type 7 Barcode Image +// Description: Creates a Mailmark type 7 barcode with routing and service code fields and saves it as a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, demonstrating how to use MailmarkCodetext and ComplexBarcodeGenerator to produce Mailmark symbology. Developers commonly use these APIs to encode routing, service, and item information for postal automation and tracking systems. +// Prompt: Generate a Mailmark type 7 barcode image using specified routing and service code fields. +// Tags: mailmark, barcode, generation, png, aspose.barcode, complexbarcodegenerator + using System; -using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates generation of a Mailmark type 7 (24x24 modules) barcode using Aspose.BarCode. +/// Demonstrates creation of a Mailmark type 7 barcode image using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. Generates a Mailmark 2D barcode and saves it as a PNG file. + /// Entry point. Builds a MailmarkCodetext, generates the barcode, and saves it as a PNG file. /// static void Main() { - // Define the output file path in the current working directory. - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "mailmark_type7.png"); - - // Create and populate a Mailmark2DCodetext instance with required data. - var mailmark = new Mailmark2DCodetext + // Initialize Mailmark codetext with required fields + var mailmark = new MailmarkCodetext { - // Version identifier (string) - VersionID = "1", - // Information type identifier (string) - InformationTypeID = "0", - // Service class code (string) + // Mailmark 4‑state format (type 7) + Format = 4, + // Version identifier (typically 1) + VersionID = 1, + // Class identifier as a string Class = "0", - // Return to sender flag (string) - RTSFlag = "0", - // Supply chain identifier (int) - SupplyChainID = 384224, - // Unique item identifier (int) + // Routing / supply chain identifier + SupplychainID = 384224, + // Unique item identifier ItemID = 16563762, - // Destination postcode plus DPS (must be 9 characters, padded with spaces if needed) - DestinationPostCodeAndDPS = "EF61AH8T ", - // Optional customer content (left empty) - CustomerContent = string.Empty, - // UPU country identifier (optional, set to GB) - UPUCountryID = "GB", - // Define the 2D Mailmark type (type 7 = 24x24 modules) - DataMatrixType = Mailmark2DType.Type_7, - // Use default encoding mode for customer content - CustomerContentEncodeMode = DataMatrixEncodeMode.C40 + // Destination postcode + DPS (trailing space required by spec) + DestinationPostCodePlusDPS = "EF61AH8T " }; - // Generate the barcode image using ComplexBarcodeGenerator. + // Generate the barcode using ComplexBarcodeGenerator using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Save the generated barcode as a PNG file. - generator.Save(outputPath, BarCodeImageFormat.Png); + // Optional visual settings: black bars on white background + generator.Parameters.Barcode.BarColor = Color.Black; + generator.Parameters.BackColor = Color.White; + + // Save the barcode image to a PNG file + generator.Save("mailmark.png"); } - // Inform the user where the barcode image has been saved. - Console.WriteLine($"Mailmark type 7 barcode saved to: {outputPath}"); + // Inform the user that the image has been saved + Console.WriteLine("Mailmark barcode image saved as 'mailmark.png'."); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/handle-cases-where-customer-information-uses-unsupported-characters-by-logging-warning-and-skipping-generation.cs b/mailmark-two-dimensional-barcode/handle-cases-where-customer-information-uses-unsupported-characters-by-logging-warning-and-skipping-generation.cs index 5388ed5..31c8e1d 100644 --- a/mailmark-two-dimensional-barcode/handle-cases-where-customer-information-uses-unsupported-characters-by-logging-warning-and-skipping-generation.cs +++ b/mailmark-two-dimensional-barcode/handle-cases-where-customer-information-uses-unsupported-characters-by-logging-warning-and-skipping-generation.cs @@ -1,105 +1,103 @@ +// Title: Australia Post Barcode Generation with Customer Info Validation +// Description: Demonstrates generating Australia Post barcodes while validating customer information and handling unsupported characters. +// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on the EncodeTypes.AustraliaPost symbology. It showcases the use of BarcodeGenerator, encoding tables (CustomerInformationInterpretingType), and common validation patterns required when creating postal barcodes. Developers often need to ensure that customer data conforms to specific character sets before barcode creation, making this a typical use case for postal applications. +// Prompt: Handle cases where customer information uses unsupported characters by logging a warning and skipping generation. +// Tags: barcode, australia post, generation, validation, customer information, aspose.barcode, encoding table + using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Demonstrates generation of Australia Post barcodes with various customer information -/// validation based on the selected . +/// Generates Australia Post barcodes for a set of sample data, validating the customer information +/// part according to the selected . Invalid data +/// triggers a warning and the barcode generation is skipped. /// class Program { /// - /// Entry point of the application. Iterates over sample data, validates customer information, - /// and generates barcode images when validation succeeds. + /// Entry point of the example. Iterates through sample codes, validates customer information, + /// and creates barcode images when the data is supported. /// static void Main() { - // Sample data: each tuple contains (codeText, encodingType, customerInfo) - var samples = new (string CodeText, CustomerInformationInterpretingType Encoding, string CustomerInfo)[] + // Sample data: each tuple contains the full code text and the interpreting type to use. + var samples = new (string CodeText, CustomerInformationInterpretingType Interpreting)[] { - ("5912345678ABCde", CustomerInformationInterpretingType.CTable, "ABC 123#"), // valid CTable - ("5912345678ABCde", CustomerInformationInterpretingType.NTable, "123456"), // valid NTable - ("5912345678ABCde", CustomerInformationInterpretingType.Other, "AB"), // valid Other (<=3 chars) - ("5912345678ABCde", CustomerInformationInterpretingType.CTable, "Invalid@!"), // invalid CTable - ("5912345678ABCde", CustomerInformationInterpretingType.NTable, "12A34"), // invalid NTable - ("5912345678ABCde", CustomerInformationInterpretingType.Other, "ABCD") // invalid Other (>3 chars) + ("5912345678ABCde", CustomerInformationInterpretingType.CTable), // valid CTable + ("591234567812345", CustomerInformationInterpretingType.NTable), // valid NTable (digits only) + ("5912345678# #", CustomerInformationInterpretingType.CTable), // valid CTable (space and #) + ("5912345678XYZ@", CustomerInformationInterpretingType.CTable), // invalid CTable (contains '@') + ("5912345678AB12", CustomerInformationInterpretingType.Other), // invalid Other (contains 'A','B') + ("591234567800123", CustomerInformationInterpretingType.Other) // valid Other (only 0,1,2,3) }; int index = 0; - foreach (var sample in samples) + foreach (var (codeText, interpreting) in samples) { - index++; + // Customer information part is everything after the first 10 characters (postal part). + string customerInfo = codeText.Length > 10 ? codeText.Substring(10) : string.Empty; - // Validate the customer information according to the selected encoding type. - if (!IsCustomerInfoValid(sample.CustomerInfo, sample.Encoding)) + // Validate the customer information according to the selected interpreting type. + if (!IsCustomerInfoValid(customerInfo, interpreting)) { - Console.WriteLine($"Warning: Sample {index} has unsupported characters for {sample.Encoding}. Skipping generation."); + // Log a warning and skip barcode generation for invalid data. + Console.WriteLine($"Warning: Customer information \"{customerInfo}\" is invalid for {interpreting}. Skipping generation."); continue; } - // Define output file name for the generated barcode image. - string outputPath = $"AustraliaPost_{index}.png"; - - // Create a barcode generator for Australia Post format. - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, sample.CodeText)) + // Generate Australia Post barcode using the valid code text. + using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText)) { - // Set the specific encoding table (CTable, NTable, or Other). - generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = sample.Encoding; + // Apply the appropriate encoding table for the customer information. + generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = interpreting; - // Append customer information to the code text for demonstration purposes. - generator.CodeText = sample.CodeText + sample.CustomerInfo; - - try - { - // Save the generated barcode image to the specified path. - generator.Save(outputPath); - Console.WriteLine($"Generated barcode saved to {outputPath}"); - } - catch (Exception ex) - { - // Report any errors that occur during barcode generation. - Console.WriteLine($"Error generating barcode for sample {index}: {ex.Message}"); - } + // Save the barcode image to a PNG file. + string fileName = $"AustraliaPost_{index}.png"; + generator.Save(fileName); + Console.WriteLine($"Generated barcode saved to {Path.GetFullPath(fileName)}"); } + + index++; } } - /// - /// Validates customer information based on the selected . - /// - /// The customer information string to validate. - /// The interpreting type that defines allowed characters. - /// True if the information conforms to the rules of the specified type; otherwise, false. + // Validation according to the interpreting type. static bool IsCustomerInfoValid(string info, CustomerInformationInterpretingType type) { switch (type) { case CustomerInformationInterpretingType.CTable: - // CTable allows letters, digits, space, and '#'. - foreach (char c in info) + // Allows A-Z, a-z, 1-9, space and '#'. + foreach (char ch in info) { - if (!(char.IsLetterOrDigit(c) || c == ' ' || c == '#')) - return false; + if (char.IsLetter(ch) || (ch >= '1' && ch <= '9') || ch == ' ' || ch == '#') + continue; + return false; } return true; case CustomerInformationInterpretingType.NTable: - // NTable allows digits only. - foreach (char c in info) + // Allows digits only. + foreach (char ch in info) { - if (!char.IsDigit(c)) + if (!char.IsDigit(ch)) return false; } return true; case CustomerInformationInterpretingType.Other: - // Other allows any characters but limits length to 3 symbols. - return info.Length <= 3; - } + // Allows only symbols '0', '1', '2', '3'. + foreach (char ch in info) + { + if (ch != '0' && ch != '1' && ch != '2' && ch != '3') + return false; + } + return true; - // If an unknown type is encountered, treat as invalid. - return false; + default: + return false; + } } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/implement-dependency-injection-to-provide-barcode-generation-service-throughout-application.cs b/mailmark-two-dimensional-barcode/implement-dependency-injection-to-provide-barcode-generation-service-throughout-application.cs index 4cfaff3..7acdc65 100644 --- a/mailmark-two-dimensional-barcode/implement-dependency-injection-to-provide-barcode-generation-service-throughout-application.cs +++ b/mailmark-two-dimensional-barcode/implement-dependency-injection-to-provide-barcode-generation-service-throughout-application.cs @@ -1,75 +1,95 @@ +// Title: Barcode Generation with Dependency Injection using Aspose.BarCode +// Description: Demonstrates registering a barcode generation service in a DI container and using it to create a Code128 PNG image. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to leverage Microsoft.Extensions.DependencyInjection to inject a barcode service. It highlights key API classes such as BarcodeGenerator, EncodeTypes, and the IBarcodeService contract. Developers often need to generate barcodes in various formats across different layers of an application; this pattern provides a clean, testable approach for such scenarios. +// Prompt: Implement dependency injection to provide a barcode generation service throughout the application. +// Tags: barcode symbology, generation, png, aspose.barcode, dependency injection, csharp + using System; -using System.IO; using Microsoft.Extensions.DependencyInjection; using Aspose.BarCode; using Aspose.BarCode.Generation; namespace BarcodeDIExample { - // Service interface for barcode generation + /// + /// Service contract for barcode generation. + /// public interface IBarcodeService { - void GenerateBarcode(BaseEncodeType type, string codeText, string outputPath); + /// + /// Generates a barcode image from the specified text and saves it to the given path. + /// + /// The text to encode in the barcode. + /// The file path where the barcode image will be saved. + void Generate(string codeText, string outputPath); } /// - /// Implementation of using Aspose.BarCode. + /// Concrete implementation of using Aspose.BarCode. /// - public class BarcodeService : IBarcodeService + public class BarcodeService : IBarcodeService, IDisposable { - /// - /// Generates a barcode image of the specified type and saves it to the given path. - /// - /// The barcode encoding type (e.g., Code128). - /// The text to encode in the barcode. - /// The full file path where the barcode image will be saved. - public void GenerateBarcode(BaseEncodeType type, string codeText, string outputPath) + private bool _disposed = false; + + /// + public void Generate(string codeText, string outputPath) { - // Ensure the output directory exists before attempting to save the file - string directory = Path.GetDirectoryName(outputPath); - if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) + // Use Code128 as an example symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) { - Directory.CreateDirectory(directory); + generator.CodeText = codeText; + // Save the generated barcode as a PNG file. + generator.Save(outputPath); } + } - // Create a BarcodeGenerator, configure its parameters, and save the image - using (var generator = new BarcodeGenerator(type, codeText)) + /// + /// Disposes the service. Currently no unmanaged resources are held, but the pattern is kept for future extensibility. + /// + public void Dispose() + { + if (!_disposed) { - // Example: set a higher resolution for better image quality - generator.Parameters.Resolution = 300f; - - // Save the barcode image as PNG to the specified path - generator.Save(outputPath); + // No unmanaged resources to release. + _disposed = true; } } } /// - /// Entry point of the application demonstrating dependency injection with the barcode service. + /// Application entry point demonstrating DI-based barcode generation. /// class Program { /// - /// Configures services, resolves the barcode service, and generates a sample barcode. + /// Configures the DI container, resolves the barcode service, and generates a sample barcode. /// - static void Main() + /// Command‑line arguments (not used). + static void Main(string[] args) { - // Set up the dependency injection container + // Set up a simple DI container. var services = new ServiceCollection(); - services.AddSingleton(); - var serviceProvider = services.BuildServiceProvider(); - // Resolve the barcode service from the DI container - var barcodeService = serviceProvider.GetRequiredService(); + // Register the barcode service as a transient dependency. + services.AddTransient(); + + // Build the service provider and resolve services within a using block to ensure disposal. + using (var provider = services.BuildServiceProvider()) + { + // Resolve the barcode service. + var barcodeService = provider.GetRequiredService(); - // Define the output file path for the generated barcode image - string outputFile = Path.Combine(Directory.GetCurrentDirectory(), "code128.png"); + // Sample data and output file. + string sampleText = "123ABC456"; + string outputFile = "sample_code128.png"; - // Generate a Code128 barcode with sample text and save it to the output file - barcodeService.GenerateBarcode(EncodeTypes.Code128, "Sample12345", outputFile); + // Generate the barcode image. + barcodeService.Generate(sampleText, outputFile); + + Console.WriteLine($"Barcode generated and saved to '{outputFile}'."); + } - // Inform the user where the barcode image has been saved - Console.WriteLine($"Barcode generated and saved to: {outputFile}"); + // Program exits automatically. } } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/implement-error-handling-to-manage-cases-where-barcode-decoding-fails-or-returns-incomplete-data.cs b/mailmark-two-dimensional-barcode/implement-error-handling-to-manage-cases-where-barcode-decoding-fails-or-returns-incomplete-data.cs index 7b780dc..f2efe06 100644 --- a/mailmark-two-dimensional-barcode/implement-error-handling-to-manage-cases-where-barcode-decoding-fails-or-returns-incomplete-data.cs +++ b/mailmark-two-dimensional-barcode/implement-error-handling-to-manage-cases-where-barcode-decoding-fails-or-returns-incomplete-data.cs @@ -1,110 +1,106 @@ +// Title: Barcode Generation and Decoding with Error Handling +// Description: Demonstrates generating a Code128 barcode, saving it to a temporary file, and decoding it while handling possible failures. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader for decoding them. Developers often need to generate barcodes for labeling and later read them from images or scanned documents; this snippet illustrates typical API usage, quality settings, and robust error handling for such scenarios. +// Prompt: Implement error handling to manage cases where barcode decoding fails or returns incomplete data. +// Tags: barcode symbology, generation, recognition, error handling, code128, png, aspose.barcode, qualitysettings + using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Demonstrates generating a barcode image, reading it back, and cleaning up the temporary file. +/// Generates a Code128 barcode, saves it to a temporary PNG file, and then decodes it +/// while handling possible errors such as missing files, unreadable barcodes, or incomplete data. /// class Program { /// - /// Entry point of the application. - /// Generates a Code128 barcode, saves it to a temporary file, reads it back, - /// displays detection results, and finally deletes the temporary file. + /// Entry point of the example. Executes barcode creation, decoding, and cleanup with comprehensive error handling. /// static void Main() { - // Define the path for the temporary barcode image. - string barcodePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png"); + // Define a temporary file path for the generated barcode image + string imagePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png"); // ------------------------------------------------------------ - // Generate a sample barcode image and save it to the temporary path. + // Generate a sample barcode (Code128) and save it to the file // ------------------------------------------------------------ - try - { - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789012")) - { - // Optional: configure generator settings such as resolution here. - generator.Save(barcodePath); - Console.WriteLine($"Barcode image saved to: {barcodePath}"); - } - } - catch (Exception ex) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - Console.WriteLine($"Failed to generate barcode: {ex.Message}"); - return; + // Optional: configure generator parameters here if needed + generator.Save(imagePath, BarCodeImageFormat.Png); } - // Verify that the image file exists before attempting to read it. - if (!File.Exists(barcodePath)) + // Verify that the image file was created successfully + if (!File.Exists(imagePath)) { - Console.WriteLine("Barcode image file does not exist."); + Console.WriteLine($"Error: Barcode image file not found at '{imagePath}'."); return; } // ------------------------------------------------------------ - // Read the barcode from the saved image with error handling. + // Attempt to read the barcode with error handling // ------------------------------------------------------------ try { - using (var reader = new BarCodeReader(barcodePath, DecodeType.AllSupportedTypes)) + using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - // Enable checksum validation (optional). - reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; - // Allow recognition of barcodes with incorrect checksum or damaged data. - reader.QualitySettings.AllowIncorrectBarcodes = true; + // Use a high‑performance quality preset for faster processing + reader.QualitySettings = QualitySettings.HighPerformance; - // Perform the barcode detection. - BarCodeResult[] results = reader.ReadBarCodes(); + // Perform the recognition + var results = reader.ReadBarCodes(); - // Check if any barcodes were detected. + // No barcodes detected if (results == null || results.Length == 0) { - Console.WriteLine("No barcodes were detected in the image."); + Console.WriteLine("No barcode detected in the image."); + return; } - else + + // Process each detected barcode + foreach (var result in results) { - // Iterate through each detected barcode and display its details. - foreach (var result in results) + // Check for missing or empty CodeText (incomplete data) + if (string.IsNullOrEmpty(result.CodeText)) { - // Handle cases where the decoded text is missing or incomplete. - if (string.IsNullOrEmpty(result.CodeText)) - { - Console.WriteLine($"Detected barcode of type '{result.CodeTypeName}' but CodeText is missing or incomplete."); - } - else - { - Console.WriteLine($"Detected barcode type: {result.CodeTypeName}"); - Console.WriteLine($"CodeText: {result.CodeText}"); - Console.WriteLine($"Confidence: {result.Confidence}"); - Console.WriteLine($"ReadingQuality: {result.ReadingQuality}"); - } + Console.WriteLine($"Detected barcode of type '{result.CodeTypeName}' but CodeText is missing or empty."); + continue; } + + // Output basic information about the decoded barcode + Console.WriteLine($"Barcode Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + Console.WriteLine($"Confidence : {result.Confidence}"); + Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); + Console.WriteLine($"Region Angle : {result.Region.Angle}"); + Console.WriteLine($"Region Bounds : {result.Region.Rectangle}"); + Console.WriteLine(new string('-', 40)); } } } catch (Exception ex) { - Console.WriteLine($"Error during barcode decoding: {ex.Message}"); + // General exception handling for unexpected errors during decoding + Console.WriteLine($"An error occurred while decoding the barcode: {ex.Message}"); } finally { // ------------------------------------------------------------ - // Clean up the temporary file regardless of success or failure. + // Clean up the temporary image file // ------------------------------------------------------------ try { - if (File.Exists(barcodePath)) + if (File.Exists(imagePath)) { - File.Delete(barcodePath); + File.Delete(imagePath); } } catch { - // Ignored - cleanup failure should not affect program flow. + // Ignored – cleanup failure should not affect program flow } } } diff --git a/mailmark-two-dimensional-barcode/implement-retry-mechanism-for-barcode-generation-when-transient-errors-occur-during-image-saving.cs b/mailmark-two-dimensional-barcode/implement-retry-mechanism-for-barcode-generation-when-transient-errors-occur-during-image-saving.cs index dc0c18e..6b5c079 100644 --- a/mailmark-two-dimensional-barcode/implement-retry-mechanism-for-barcode-generation-when-transient-errors-occur-during-image-saving.cs +++ b/mailmark-two-dimensional-barcode/implement-retry-mechanism-for-barcode-generation-when-transient-errors-occur-during-image-saving.cs @@ -1,90 +1,87 @@ +// Title: Barcode generation with retry on transient errors +// Description: Demonstrates generating a Code128 barcode and saving it as PNG with a retry mechanism for transient I/O or generation errors. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, set visual parameters, and handle transient failures during image saving. Developers often need to implement retry logic when working with file systems or network shares to ensure reliable barcode creation in production environments. +// Prompt: Implement a retry mechanism for barcode generation when transient errors occur during image saving. +// Tags: barcode, code128, retry, io, exception handling, png, aspose.barcode, generation + using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates generating a barcode image with retry logic using Aspose.BarCode. +/// Example program that creates a Code128 barcode image with retry logic for transient errors. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode and saves it to a file, handling transient errors with retries. + /// Entry point. Generates a barcode, saves it to a PNG file, and retries on transient failures. /// static void Main() { - // Define barcode settings: symbology type and text to encode. - BaseEncodeType encodeType = EncodeTypes.Code128; - string codeText = "123ABC"; - - // Determine the full output file path (current directory + filename). - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png"); + // Define the output file path for the barcode image + string outputPath = "barcode.png"; - // Ensure the directory for the output file exists. - string outputDir = Path.GetDirectoryName(outputPath); - if (!Directory.Exists(outputDir)) + // Ensure the target directory exists before attempting to save + string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(directory)) { - Directory.CreateDirectory(outputDir); + Directory.CreateDirectory(directory); } - // Generate the barcode image with up to 3 attempts on transient failures. - bool success = GenerateBarcodeWithRetry(encodeType, codeText, outputPath, maxAttempts: 3); - - // Inform the user of the result. - Console.WriteLine(success - ? $"Barcode saved successfully to '{outputPath}'." - : $"Failed to save barcode after multiple attempts."); - } + // Configure retry parameters + const int maxAttempts = 3; // maximum number of retry attempts + int attempt = 0; // current attempt counter + bool success = false; // flag indicating successful save - /// - /// Generates a barcode image and saves it to the specified path. - /// Retries the save operation when a transient exception occurs. - /// - /// The barcode symbology. - /// The text to encode. - /// File path for the saved image. - /// Maximum number of attempts. - /// True if the image was saved successfully; otherwise false. - private static bool GenerateBarcodeWithRetry(BaseEncodeType type, string codeText, string outputPath, int maxAttempts) - { - // Loop through the allowed number of attempts. - for (int attempt = 1; attempt <= maxAttempts; attempt++) + // Retry loop: continue until success or max attempts reached + while (attempt < maxAttempts && !success) { + attempt++; try { - // Create a barcode generator with the specified type and text. - using (var generator = new BarcodeGenerator(type, codeText)) + // Create and configure the barcode generator + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) { - // Optional: set image resolution (dots per inch). - generator.Parameters.Resolution = 300f; + // Set visual appearance (optional) + generator.Parameters.Barcode.BarColor = Color.Black; + generator.Parameters.BackColor = Color.White; - // Save the generated barcode image to the target path. - generator.Save(outputPath); + // Save the generated barcode image to the specified path + generator.Save(outputPath, BarCodeImageFormat.Png); } - // If we reach this point, the save succeeded; exit with success. - return true; + // If no exception, mark as successful and inform the user + success = true; + Console.WriteLine($"Barcode saved successfully on attempt {attempt}."); } catch (IOException ioEx) { - // Transient I/O error (e.g., file locked). Log and retry. - Console.WriteLine($"Attempt {attempt}: I/O error while saving barcode - {ioEx.Message}"); + // Handle transient I/O errors (e.g., file lock, network share issues) + Console.WriteLine($"I/O error on attempt {attempt}: {ioEx.Message}"); + if (attempt >= maxAttempts) + { + Console.WriteLine("Maximum retry attempts reached. Operation failed."); + } } catch (BarCodeException bcEx) { - // Transient barcode generation error. Log and retry. - Console.WriteLine($"Attempt {attempt}: Barcode generation error - {bcEx.Message}"); + // Handle transient barcode generation errors + Console.WriteLine($"Barcode generation error on attempt {attempt}: {bcEx.Message}"); + if (attempt >= maxAttempts) + { + Console.WriteLine("Maximum retry attempts reached. Operation failed."); + } } catch (Exception ex) { - // Non-transient error; log and abort further retries. - Console.WriteLine($"Attempt {attempt}: Unexpected error - {ex.Message}"); + // Handle non‑transient, unexpected errors and abort further retries + Console.WriteLine($"Unexpected error: {ex.Message}"); break; } } - // All attempts exhausted without success. - return false; + // Exit code 0 indicates normal termination (implicit) } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/integrate-barcode-generation-into-aspnet-mvc-controller-and-return-image-as-fileresult.cs b/mailmark-two-dimensional-barcode/integrate-barcode-generation-into-aspnet-mvc-controller-and-return-image-as-fileresult.cs index 93ca6c5..56245b0 100644 --- a/mailmark-two-dimensional-barcode/integrate-barcode-generation-into-aspnet-mvc-controller-and-return-image-as-fileresult.cs +++ b/mailmark-two-dimensional-barcode/integrate-barcode-generation-into-aspnet-mvc-controller-and-return-image-as-fileresult.cs @@ -1,53 +1,42 @@ +// Title: Generate Code128 barcode and save as PNG +// Description: Demonstrates creating a Code128 barcode image using Aspose.BarCode and saving it to disk, which can be adapted to return as a FileResult in ASP.NET MVC. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class to encode data, customize colors, and output images. Developers working on web applications often need to generate barcodes on-the-fly for reports, tickets, or inventory systems, and then return the image via an MVC controller action as a FileResult. +// Prompt: Integrate barcode generation into an ASP.NET MVC controller and return the image as a FileResult. +// Tags: code128, barcode generation, png, aspnet mvc, filereturn, aspose.barcode + using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing.Imaging; +using Aspose.BarCode; +using Aspose.Drawing; /// -/// Demonstrates barcode generation using Aspose.BarCode in a console application. -/// This logic can be reused in an ASP.NET MVC controller to return the image as a FileResult. +/// Demonstrates barcode generation using Aspose.BarCode. /// class Program { /// - /// Entry point of the console application. - /// Generates a Code128 barcode, converts it to a Base64 string, and writes it to the console. + /// Entry point for the console demonstration. In an MVC app this logic would reside in a controller action returning a FileResult. /// static void Main() { - // Generate a Code128 barcode and obtain the image bytes. - byte[] barcodeBytes = GenerateBarcodeBytes(EncodeTypes.Code128, "1234567890"); - - // Convert the image bytes to a Base64 string for easy display. - string base64 = Convert.ToBase64String(barcodeBytes); - Console.WriteLine("Barcode PNG (Base64):"); - Console.WriteLine(base64); - } + // Define the output file path for the generated barcode image. + string outputPath = "barcode.png"; - /// - /// Generates a barcode image in PNG format and returns it as a byte array. - /// - /// The type of barcode to generate (e.g., Code128). - /// The text to encode in the barcode. - /// Byte array containing the PNG image of the generated barcode. - static byte[] GenerateBarcodeBytes(BaseEncodeType encodeType, string codeText) - { - // Initialize the barcode generator with the specified type and text. - using (var generator = new BarcodeGenerator(encodeType, codeText)) + // Create a BarcodeGenerator for Code128 symbology with the desired data. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789")) { - // Enable checksum calculation for the barcode (if applicable). - generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; + // Set the barcode's foreground (bar) color. + generator.Parameters.Barcode.BarColor = Color.Black; - // Use a memory stream to hold the generated image. - using (var ms = new MemoryStream()) - { - // Save the barcode image to the memory stream in PNG format. - generator.Save(ms, BarCodeImageFormat.Png); - // Return the image data as a byte array. - return ms.ToArray(); - } + // Set the background color of the image. + generator.Parameters.BackColor = Color.White; + + // Save the generated barcode image to the specified file path. + generator.Save(outputPath); } + + // Output the full path of the saved barcode image for verification. + Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/log-detailed-decoding-information-including-field-names-and-values-to-assist-troubleshooting.cs b/mailmark-two-dimensional-barcode/log-detailed-decoding-information-including-field-names-and-values-to-assist-troubleshooting.cs index 7d8f5c3..83038ca 100644 --- a/mailmark-two-dimensional-barcode/log-detailed-decoding-information-including-field-names-and-values-to-assist-troubleshooting.cs +++ b/mailmark-two-dimensional-barcode/log-detailed-decoding-information-including-field-names-and-values-to-assist-troubleshooting.cs @@ -1,36 +1,39 @@ +// Title: Generate and Decode a Code128 Barcode with Detailed Logging +// Description: This example creates a Code128 barcode image, saves it to disk, then reads the image back while logging all decoding fields to aid troubleshooting. +// Category-Description: Demonstrates Aspose.BarCode generation and recognition workflows. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader for decoding them, covering typical scenarios such as visual customization, multi‑symbology support, and detailed result inspection. Developers working with barcode imaging, inventory systems, or document automation often need these APIs to produce and validate barcodes programmatically. +// Prompt: Log detailed decoding information, including field names and values, to assist troubleshooting. +// Tags: code128, barcode generation, barcode recognition, decoding, logging, aspose.barcode + using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Demonstrates generating a Code128 barcode, saving it to a file, -/// and then reading it back to display detailed decoding information. +/// Demonstrates how to generate a Code128 barcode, save it as an image, +/// and then read it back while outputting detailed decoding information. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode image, verifies its creation, and reads the barcode data. + /// Entry point of the example. Generates a barcode, saves it, and logs + /// all available decoding details for each detected barcode. /// static void Main() { - // Define the output path for the generated barcode image. - string imagePath = "barcode.png"; + // Define the file name for the generated barcode image. + string imagePath = "sample_barcode.png"; - // ------------------------------------------------- - // Generate a sample Code128 barcode - // ------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Generate a simple Code128 barcode and save it to a PNG file. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Enable checksum for demonstration purposes. - generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; + // Optional: set visual properties for better contrast. + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Save the generated barcode image to the specified file. - generator.Save(imagePath); + // Save the barcode image. + generator.Save(imagePath, BarCodeImageFormat.Png); } // Verify that the image file was successfully created. @@ -40,53 +43,43 @@ static void Main() return; } - // ------------------------------------------------- - // Read the barcode and log detailed decoding info - // ------------------------------------------------- + // Read the barcode from the generated image and log detailed information. using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - // Read all barcodes found in the image. - BarCodeResult[] results = reader.ReadBarCodes(); - - // If no barcodes were detected, inform the user and exit. - if (results.Length == 0) - { - Console.WriteLine("No barcodes were detected."); - return; - } - - // Iterate through each detected barcode and display its properties. - foreach (BarCodeResult result in results) + // Iterate through all detected barcodes in the image. + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine("=== Barcode Detected ==="); - Console.WriteLine($"Type : {result.CodeTypeName}"); - Console.WriteLine($"CodeText : {result.CodeText}"); - Console.WriteLine($"Confidence : {result.Confidence}"); - Console.WriteLine($"ReadingQuality : {result.ReadingQuality}"); + Console.WriteLine("=== Detected Barcode ==="); + Console.WriteLine($"Type Name : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + Console.WriteLine($"Confidence : {result.Confidence}"); + Console.WriteLine($"Reading Quality : {result.ReadingQuality}"); - // Extract region bounds (X, Y, Width, Height) and round to integers. + // Output the region bounds of the detected barcode. var rect = result.Region.Rectangle; - int x = (int)Math.Round((double)rect.X); - int y = (int)Math.Round((double)rect.Y); - int width = (int)Math.Round((double)rect.Width); - int height = (int)Math.Round((double)rect.Height); - Console.WriteLine($"Region (X,Y,W,H) : X={x}, Y={y}, Width={width}, Height={height}"); - - // Output the orientation angle of the detected barcode. - Console.WriteLine($"Orientation Angle : {result.Region.Angle}"); + Console.WriteLine($"Region X : {rect.X}"); + Console.WriteLine($"Region Y : {rect.Y}"); + Console.WriteLine($"Region Width : {rect.Width}"); + Console.WriteLine($"Region Height : {rect.Height}"); - // If the barcode is a 1D type, display extended 1D-specific parameters. - if (result.Extended?.OneD != null) + // Output extended information if it is available. + if (result.Extended != null) { - Console.WriteLine($"OneD Value : {result.Extended.OneD.Value}"); - Console.WriteLine($"OneD CheckSum : {result.Extended.OneD.CheckSum}"); - } + // Example for 1D barcodes (e.g., Code128). + var oneD = result.Extended.OneD; + if (oneD != null) + { + Console.WriteLine($"Extended Value : {oneD.Value}"); + Console.WriteLine($"Extended CheckSum: {oneD.CheckSum}"); + } - // If the barcode is a QR code, display extended QR-specific parameters. - if (result.Extended?.QR != null) - { - Console.WriteLine($"QR Version : {result.Extended.QR.Version}"); - Console.WriteLine($"QR ErrorLevel : {result.Extended.QR.ErrorLevel}"); + // Example for QR codes (if a QR code were present). + var qr = result.Extended.QR; + if (qr != null) + { + Console.WriteLine($"QR Version : {qr.Version}"); + Console.WriteLine($"QR Error Level : {qr.ErrorLevel}"); + } } Console.WriteLine(); diff --git a/mailmark-two-dimensional-barcode/parallelize-barcode-generation-for-large-datasets-using-task-parallel-library-to-improve-performance.cs b/mailmark-two-dimensional-barcode/parallelize-barcode-generation-for-large-datasets-using-task-parallel-library-to-improve-performance.cs index 4aeca14..8facc16 100644 --- a/mailmark-two-dimensional-barcode/parallelize-barcode-generation-for-large-datasets-using-task-parallel-library-to-improve-performance.cs +++ b/mailmark-two-dimensional-barcode/parallelize-barcode-generation-for-large-datasets-using-task-parallel-library-to-improve-performance.cs @@ -1,22 +1,27 @@ +// Title: Parallel Barcode Generation Using TPL +// Description: Demonstrates generating Code128 barcodes in parallel for a list of strings, improving throughput for large datasets. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class with the EncodeTypes enumeration to create barcode images. Typical use cases include batch processing of inventory codes, ticket numbers, or any high‑volume identifier set where performance matters. Developers often need to parallelize generation to reduce overall processing time while ensuring thread‑safety of the generator instances. +// Prompt: Parallelize barcode generation for large datasets using Task Parallel Library to improve performance. +// Tags: barcode symbology, generation, parallel, task parallel library, png, aspose.barcode, encode types, code128 + using System; -using System.IO; using System.Collections.Generic; using System.Threading.Tasks; -using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode; /// -/// Demonstrates generating Code128 barcodes for a list of items and saving them as PNG files. +/// Example program that generates Code128 barcodes in parallel using the Task Parallel Library (TPL). /// class Program { /// - /// Entry point of the application. Generates barcodes in parallel and writes them to disk. + /// Entry point of the application. Generates barcodes for each item in the data set concurrently. /// static void Main() { - // Sample dataset of code texts to be encoded as barcodes - var data = new List + // Sample data set (replace with real data in production) + List dataSet = new List { "Item001", "Item002", @@ -25,32 +30,28 @@ static void Main() "Item005" }; - // Define the output directory for generated barcode images - string outputDir = "Barcodes"; - - // Ensure the output directory exists; create it if it does not - if (!Directory.Exists(outputDir)) - { - Directory.CreateDirectory(outputDir); - } + // Output directory (current folder) + string outputFolder = AppDomain.CurrentDomain.BaseDirectory; - // Generate barcodes in parallel to improve performance on multi-core systems - Parallel.ForEach(data, codeText => + // Parallel generation of barcodes using TPL + Parallel.ForEach(dataSet, (codeText) => { - // Each parallel task creates its own BarcodeGenerator instance to avoid thread‑safety issues + // Each task creates its own generator instance because BarcodeGenerator is not thread‑safe using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Set image resolution (dots per inch) for higher quality output - generator.Parameters.Resolution = 300f; + // Optional: customize appearance of the barcode + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.DarkBlue; + generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial"; + generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f; - // Build the full file path for the PNG image - string filePath = Path.Combine(outputDir, $"{codeText}.png"); + // Build output file name (e.g., Item001.png) + string filePath = System.IO.Path.Combine(outputFolder, $"{codeText}.png"); - // Save the generated barcode image to the specified path + // Save the barcode image to the specified path generator.Save(filePath); - // Log progress to the console - Console.WriteLine($"Generated barcode for {codeText} at {filePath}"); + // Log the successful generation to the console + Console.WriteLine($"Generated barcode for '{codeText}' -> {filePath}"); } }); diff --git a/mailmark-two-dimensional-barcode/read-mailmark-2d-barcode-from-image-file-using-barcodereader-with-decodetypedatamatrix.cs b/mailmark-two-dimensional-barcode/read-mailmark-2d-barcode-from-image-file-using-barcodereader-with-decodetypedatamatrix.cs index 6137b4b..c46c7ce 100644 --- a/mailmark-two-dimensional-barcode/read-mailmark-2d-barcode-from-image-file-using-barcodereader-with-decodetypedatamatrix.cs +++ b/mailmark-two-dimensional-barcode/read-mailmark-2d-barcode-from-image-file-using-barcodereader-with-decodetypedatamatrix.cs @@ -1,71 +1,74 @@ +// Title: Read Mailmark 2D barcode from image using BarCodeReader +// Description: Demonstrates how to load an image containing a Mailmark 2D (DataMatrix) barcode, detect it with Aspose.BarCode, and decode its structured fields. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on reading complex 2D symbologies such as Mailmark. It showcases the BarCodeReader with DecodeType.DataMatrix and the ComplexCodetextReader for parsing Mailmark 2D codetext into a strongly‑typed object. Developers working with postal or logistics solutions often need to extract Mailmark information from scanned images, making this pattern a common use case. +// Prompt: Read a Mailmark 2D barcode from an image file using BarCodeReader with DecodeType.DataMatrix. +// Tags: mailmark, datamatrix, barcode, reading, aspose.barcode, complexcodetext + using System; using System.IO; using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode.ComplexBarcode; /// -/// Demonstrates how to read and decode a Mailmark 2D barcode from an image file using Aspose.BarCode. +/// Demonstrates reading a Mailmark 2D barcode from an image file and decoding its fields. /// class Program { /// - /// Entry point of the application. + /// Entry point. Loads the image, detects Mailmark 2D barcode, and prints decoded information. /// static void Main() { - // Path to the image containing the Mailmark 2D barcode. + // Path to the image containing the Mailmark 2D barcode string imagePath = "mailmark2d.png"; - // Verify that the file exists before attempting to read it. + // Verify that the file exists before attempting to read it if (!File.Exists(imagePath)) { - Console.WriteLine($"File not found: {imagePath}"); + Console.WriteLine($"Image file not found: {imagePath}"); return; } - // Create a BarCodeReader configured for DataMatrix (Mailmark 2D uses DataMatrix). + // Initialize the reader for DataMatrix symbology (Mailmark 2D is encoded in a DataMatrix) using (var reader = new BarCodeReader(imagePath, DecodeType.DataMatrix)) { - // Perform the recognition and retrieve all detected barcodes. + // Perform the recognition var results = reader.ReadBarCodes(); - // If no barcodes were found, inform the user and exit. + // Check if any barcodes were detected if (results.Length == 0) { Console.WriteLine("No barcode detected in the image."); return; } - // Iterate through each detected barcode result. + // Iterate through all detected barcodes (typically only one Mailmark 2D) foreach (var result in results) { - // Output basic barcode information. + // Output basic barcode information Console.WriteLine($"Detected barcode type: {result.CodeTypeName}"); Console.WriteLine($"Raw CodeText: {result.CodeText}"); - // Attempt to decode the Mailmark 2D complex codetext into its constituent fields. + // Attempt to decode the Mailmark 2D codetext into a strongly‑typed object var mailmark = ComplexCodetextReader.TryDecodeMailmark2D(result.CodeText); if (mailmark != null) { - // Display each decoded field of the Mailmark 2D barcode. - Console.WriteLine("Decoded Mailmark2D fields:"); - Console.WriteLine($"VersionID: {mailmark.VersionID}"); - Console.WriteLine($"InformationTypeID: {mailmark.InformationTypeID}"); - Console.WriteLine($"Class: {mailmark.Class}"); - Console.WriteLine($"RTSFlag: {mailmark.RTSFlag}"); - Console.WriteLine($"SupplyChainID: {mailmark.SupplyChainID}"); - Console.WriteLine($"ItemID: {mailmark.ItemID}"); - Console.WriteLine($"DestinationPostCodeAndDPS: {mailmark.DestinationPostCodeAndDPS}"); - Console.WriteLine($"ReturnToSenderPostCode: {mailmark.ReturnToSenderPostCode}"); - Console.WriteLine($"UPUCountryID: {mailmark.UPUCountryID}"); + // Print each decoded field of the Mailmark 2D structure + Console.WriteLine("Decoded Mailmark 2D codetext:"); + Console.WriteLine($" VersionID: {mailmark.VersionID}"); + Console.WriteLine($" InformationTypeID: {mailmark.InformationTypeID}"); + Console.WriteLine($" Class: {mailmark.Class}"); + Console.WriteLine($" ItemID: {mailmark.ItemID}"); + Console.WriteLine($" DestinationPostCodeAndDPS: {mailmark.DestinationPostCodeAndDPS}"); + Console.WriteLine($" SupplyChainID: {mailmark.SupplyChainID}"); + Console.WriteLine($" RTSFlag: {mailmark.RTSFlag}"); + Console.WriteLine($" ReturnToSenderPostCode: {mailmark.ReturnToSenderPostCode}"); } else { - // Notify the user if decoding the complex codetext failed. - Console.WriteLine("Failed to decode Mailmark2D complex codetext."); + // Decoding failed – inform the user + Console.WriteLine("Failed to decode Mailmark 2D codetext."); } - - Console.WriteLine(); // Blank line between results for readability. } } } diff --git a/mailmark-two-dimensional-barcode/rotate-generated-mailmark-barcode-by-90-degrees-to-satisfy-specific-layout-requirements.cs b/mailmark-two-dimensional-barcode/rotate-generated-mailmark-barcode-by-90-degrees-to-satisfy-specific-layout-requirements.cs index 47496e6..d5c999c 100644 --- a/mailmark-two-dimensional-barcode/rotate-generated-mailmark-barcode-by-90-degrees-to-satisfy-specific-layout-requirements.cs +++ b/mailmark-two-dimensional-barcode/rotate-generated-mailmark-barcode-by-90-degrees-to-satisfy-specific-layout-requirements.cs @@ -1,46 +1,50 @@ +// Title: Rotate Mailmark barcode by 90 degrees +// Description: Generates a Mailmark barcode, rotates the image 90° clockwise, and saves it as a PNG. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It demonstrates how to use the MailmarkCodetext class together with ComplexBarcodeGenerator to create a Mailmark symbology, apply image transformations (rotation), and export the result. Developers working with postal barcodes, custom layouts, or needing image manipulation in barcode workflows will find this pattern useful. +/// Prompt: Rotate the generated Mailmark barcode by 90 degrees to satisfy specific layout requirements. +/// Tags: mailmark, barcode, rotation, png, aspose.barcode, complexbarcodegenerator, imageprocessing + using System; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates generation of a rotated Mailmark barcode and saves it as a PNG file. +/// Demonstrates generating a Mailmark barcode, rotating it 90° clockwise, and saving the result as a PNG file. /// class Program { /// - /// Entry point of the application. - /// Generates a Mailmark barcode, rotates it 90 degrees, and writes the image to disk. + /// Entry point of the example. Prepares Mailmark codetext, creates the barcode image, rotates it, and writes the output file. /// static void Main() { - // Define the output file name for the generated barcode image. - string outputPath = "mailmark_rotated.png"; - - // Create a MailmarkCodetext instance and populate its properties. - // This example uses a 4‑state format with specific identifiers. + // Prepare Mailmark codetext with required fields var mailmark = new MailmarkCodetext { - Format = 4, // 4‑state format identifier - VersionID = 1, // Version of the Mailmark specification - Class = "0", // Class as a string (required by the API) - SupplychainID = 384224, // Supply chain identifier - ItemID = 16563762, // Item identifier - DestinationPostCodePlusDPS = "EF61AH8T " // Nine‑character postcode + DP suffix + Format = 4, // 4‑state barcode + VersionID = 1, + Class = "0", // service type / class + SupplychainID = 384224, + ItemID = 16563762, // customer reference + DestinationPostCodePlusDPS = "EF61AH8T " // valid postcode + DPS }; - // Initialize the ComplexBarcodeGenerator with the prepared Mailmark codetext. + // Generate the Mailmark barcode image using ComplexBarcodeGenerator using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Set the rotation angle to 90 degrees to rotate the barcode. - generator.Parameters.RotationAngle = 90f; + using (Image barcodeImage = generator.GenerateBarCodeImage()) + { + // Rotate the image 90 degrees clockwise (no flip) + barcodeImage.RotateFlip(RotateFlipType.Rotate90FlipNone); - // Save the rotated barcode image in PNG format to the specified path. - generator.Save(outputPath, BarCodeImageFormat.Png); + // Save the rotated barcode to a PNG file + const string outputPath = "MailmarkRotated.png"; + barcodeImage.Save(outputPath, ImageFormat.Png); + Console.WriteLine($"Rotated Mailmark barcode saved to: {outputPath}"); + } } - - // Output the full path of the saved barcode image to the console. - Console.WriteLine($"Mailmark barcode saved to: {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/save-generated-mailmark-barcode-as-jpeg-file-to-specified-output-folder.cs b/mailmark-two-dimensional-barcode/save-generated-mailmark-barcode-as-jpeg-file-to-specified-output-folder.cs index ca5de57..8ac6619 100644 --- a/mailmark-two-dimensional-barcode/save-generated-mailmark-barcode-as-jpeg-file-to-specified-output-folder.cs +++ b/mailmark-two-dimensional-barcode/save-generated-mailmark-barcode-as-jpeg-file-to-specified-output-folder.cs @@ -1,49 +1,51 @@ +// Title: Generate and Save Mailmark Barcode as JPEG +// Description: Creates a Mailmark barcode using Aspose.BarCode and saves it as a JPEG image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, demonstrating how to work with complex barcode types such as Mailmark. It showcases the use of ComplexBarcodeGenerator and MailmarkCodetext classes to encode postal data, a common requirement for logistics and mailing applications. Developers often need to generate Mailmark barcodes and export them to image formats for printing or digital distribution. +// Prompt: Save the generated Mailmark barcode as a JPEG file to a specified output folder. +// Tags: mailmark, barcode, generation, jpeg, aspose.barcode, complexbarcode, codetext + using System; using System.IO; -using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.ComplexBarcode; /// -/// Demonstrates generation of a Mailmark barcode and saves it as a JPEG image. +/// Demonstrates generating a Mailmark barcode and saving it as a JPEG file. /// class Program { /// - /// Entry point of the application. Generates a Mailmark barcode and writes it to the output folder. + /// Entry point of the example. Generates the barcode and writes it to the output folder. /// static void Main() { - // Determine the output directory relative to the current working directory - string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "output"); - - // Ensure the output directory exists; create it if it does not + // Define the output folder and ensure it exists. + string outputFolder = "Output"; if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } - // Build the full file path for the resulting JPEG image - string outputPath = Path.Combine(outputFolder, "mailmark.jpg"); - - // Configure the Mailmark codetext with the required fields + // Populate the Mailmark codetext with required fields. var mailmark = new MailmarkCodetext { - Format = 4, // 4‑state Mailmark format - VersionID = 1, // Version identifier - Class = "0", // Null/Test class - SupplychainID = 384224, // Supply chain identifier - ItemID = 16563762, // Item identifier - DestinationPostCodePlusDPS = "EF61AH8T " // Valid postcode plus DPS + Format = 4, // 4-state format + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762, + DestinationPostCodePlusDPS = "EF61AH8T " }; - // Generate the barcode using the configured Mailmark codetext + // Generate the Mailmark barcode and save it as JPEG. using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Save the generated barcode as a JPEG image to the specified path + string outputPath = Path.Combine(outputFolder, "mailmark.jpeg"); generator.Save(outputPath, BarCodeImageFormat.Jpeg); } - // Inform the user where the barcode image has been saved - Console.WriteLine($"Mailmark barcode saved to: {outputPath}"); + // Inform the user where the barcode image was saved. + Console.WriteLine("Mailmark barcode saved to: " + Path.Combine(outputFolder, "mailmark.jpeg")); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/serialize-mailmark2dcodetext-object-to-json-for-storage-and-later-reconstruction-in-applications.cs b/mailmark-two-dimensional-barcode/serialize-mailmark2dcodetext-object-to-json-for-storage-and-later-reconstruction-in-applications.cs index ff8af10..0faf2ca 100644 --- a/mailmark-two-dimensional-barcode/serialize-mailmark2dcodetext-object-to-json-for-storage-and-later-reconstruction-in-applications.cs +++ b/mailmark-two-dimensional-barcode/serialize-mailmark2dcodetext-object-to-json-for-storage-and-later-reconstruction-in-applications.cs @@ -1,3 +1,9 @@ +// Title: Serialize Mailmark2D Code Text to JSON +// Description: Demonstrates how to serialize a Mailmark2DCodetext object to JSON, store it in a file, and later reconstruct it for barcode generation. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode operations category, focusing on Mailmark 2D code handling. It showcases the use of Aspose.BarCode.ComplexBarcode classes such as Mailmark2DCodetext and related enums, combined with .NET System.Text.Json for serialization. Developers working with postal barcodes often need to persist code text configurations, and this pattern provides a reusable approach for storage and retrieval. +// Prompt: Serialize a Mailmark2DCodetext object to JSON for storage and later reconstruction in applications. +// Tags: barcode, serialization, json, mailmark2d, aspose.barcode + using System; using System.IO; using System.Text.Json; @@ -5,21 +11,19 @@ using Aspose.BarCode.Generation; /// -/// Demonstrates serialization of a Mailmark2DCodetext object to JSON, -/// deserialization back to an object, and generation of a barcode image -/// using Aspose.BarCode. +/// Example program that serializes and deserializes a object using JSON. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Creates a Mailmark2DCodetext, writes it to JSON, reads it back, and prints the values. /// static void Main() { // ------------------------------------------------------------ - // 1. Create a sample Mailmark2DCodetext object with valid data + // 1. Create and populate a Mailmark2DCodetext instance // ------------------------------------------------------------ - var mailmark2d = new Mailmark2DCodetext + var mailmark2D = new Mailmark2DCodetext { UPUCountryID = "JGB ", InformationTypeID = "0", @@ -27,60 +31,55 @@ static void Main() Class = "1", SupplyChainID = 123, ItemID = 1234, - DestinationPostCodeAndDPS = "EF61AH8T ", + DestinationPostCodeAndDPS = "QWE1", RTSFlag = "0", - ReturnToSenderPostCode = "SW1A1AA", + ReturnToSenderPostCode = "QWE2", DataMatrixType = Mailmark2DType.Type_7, CustomerContent = "CUSTOM", CustomerContentEncodeMode = DataMatrixEncodeMode.C40 }; // ------------------------------------------------------------ - // 2. Serialize the object to a formatted JSON string and write to file + // 2. Serialize the object to a formatted JSON string // ------------------------------------------------------------ var jsonOptions = new JsonSerializerOptions { WriteIndented = true }; - string json = JsonSerializer.Serialize(mailmark2d, jsonOptions); - const string jsonPath = "mailmark2d.json"; - File.WriteAllText(jsonPath, json); - Console.WriteLine($"Serialized Mailmark2DCodetext to {jsonPath}"); + string json = JsonSerializer.Serialize(mailmark2D, jsonOptions); // ------------------------------------------------------------ - // 3. Read the JSON file back and deserialize to a Mailmark2DCodetext instance + // 3. Save the JSON string to a file // ------------------------------------------------------------ - if (!File.Exists(jsonPath)) + const string filePath = "mailmark2d.json"; + using (var writeStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) + using (var writer = new StreamWriter(writeStream)) { - Console.WriteLine("JSON file not found. Exiting."); - return; + writer.Write(json); } - string jsonRead = File.ReadAllText(jsonPath); - var deserialized = JsonSerializer.Deserialize(jsonRead); - if (deserialized == null) + // ------------------------------------------------------------ + // 4. Load the JSON from the file and deserialize back to an object + // ------------------------------------------------------------ + Mailmark2DCodetext deserialized; + using (var readStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) + using (var reader = new StreamReader(readStream)) { - Console.WriteLine("Failed to deserialize JSON. Exiting."); - return; + string jsonFromFile = reader.ReadToEnd(); + deserialized = JsonSerializer.Deserialize(jsonFromFile); } - Console.WriteLine("Deserialized Mailmark2DCodetext from JSON."); // ------------------------------------------------------------ - // 4. Generate a barcode image from the deserialized object and save as PNG + // 5. Output selected fields to verify successful reconstruction // ------------------------------------------------------------ - using (var generator = new ComplexBarcodeGenerator(deserialized)) - { - // Save barcode to a memory stream in PNG format - using (var ms = new MemoryStream()) - { - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for reading - - const string imagePath = "mailmark2d.png"; - // Write the memory stream contents to a file - using (var fileStream = new FileStream(imagePath, FileMode.Create, FileAccess.Write)) - { - ms.CopyTo(fileStream); - } - Console.WriteLine($"Barcode image saved to {imagePath}"); - } - } + Console.WriteLine($"UPUCountryID: {deserialized?.UPUCountryID}"); + Console.WriteLine($"InformationTypeID: {deserialized?.InformationTypeID}"); + Console.WriteLine($"VersionID: {deserialized?.VersionID}"); + Console.WriteLine($"Class: {deserialized?.Class}"); + Console.WriteLine($"SupplyChainID: {deserialized?.SupplyChainID}"); + Console.WriteLine($"ItemID: {deserialized?.ItemID}"); + Console.WriteLine($"DestinationPostCodeAndDPS: {deserialized?.DestinationPostCodeAndDPS}"); + Console.WriteLine($"RTSFlag: {deserialized?.RTSFlag}"); + Console.WriteLine($"ReturnToSenderPostCode: {deserialized?.ReturnToSenderPostCode}"); + Console.WriteLine($"DataMatrixType: {deserialized?.DataMatrixType}"); + Console.WriteLine($"CustomerContent: {deserialized?.CustomerContent}"); + Console.WriteLine($"CustomerContentEncodeMode: {deserialized?.CustomerContentEncodeMode}"); } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/set-barcodereaderdecodetype-to-decodetypedatamatrix-before-invoking-read-method-on-image.cs b/mailmark-two-dimensional-barcode/set-barcodereaderdecodetype-to-decodetypedatamatrix-before-invoking-read-method-on-image.cs index 8a37e68..d60a1a4 100644 --- a/mailmark-two-dimensional-barcode/set-barcodereaderdecodetype-to-decodetypedatamatrix-before-invoking-read-method-on-image.cs +++ b/mailmark-two-dimensional-barcode/set-barcodereaderdecodetype-to-decodetypedatamatrix-before-invoking-read-method-on-image.cs @@ -1,53 +1,52 @@ +// Title: Decode DataMatrix barcode from generated image +// Description: This example generates a DataMatrix barcode, saves it as PNG, then reads it back using BarCodeReader with DecodeType set to DataMatrix. +// Category-Description: Demonstrates Aspose.BarCode barcode generation and recognition focusing on DataMatrix symbology. It uses BarcodeGenerator to create the barcode and BarCodeReader with DecodeType to limit decoding. Developers working with specific symbologies often need to restrict decoding for performance or accuracy, making this pattern common in scanning applications. +// Prompt: Set BarCodeReader.DecodeType to DecodeType.DataMatrix before invoking the Read method on the image. +// Tags: datamatrix, decode, png, barcodegenerator, barcodereader, aspnet, csharp + using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates generating a DataMatrix barcode, saving it to a memory stream, -/// and then reading it back using Aspose.BarCode library. +/// Demonstrates generating a DataMatrix barcode, saving it as PNG, and reading it back with decoding limited to DataMatrix. /// class Program { /// - /// Entry point of the application. - /// Generates a DataMatrix barcode, writes it to a memory stream, - /// and reads the barcode back to display its type and text. + /// Entry point. Generates the barcode image, verifies its existence, and reads the barcode using BarCodeReader with DecodeType.DataMatrix. /// static void Main() { - // Define the text to encode in the DataMatrix barcode. - const string codeText = "Aspose.DataMatrix"; + // Define the file path for the sample DataMatrix barcode image. + string imagePath = "datamatrix.png"; - // Create a barcode generator for DataMatrix with the specified text. - using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, codeText)) + // Generate a DataMatrix barcode and save it to a PNG file. + using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "SampleData")) { - // Use a memory stream to hold the generated barcode image. - using (var ms = new MemoryStream()) - { - // Save the generated barcode as a PNG image into the memory stream. - generator.Save(ms, BarCodeImageFormat.Png); - - // Reset the stream position to the beginning for subsequent reading. - ms.Position = 0; + // Save the generated barcode image. + generator.Save(imagePath, BarCodeImageFormat.Png); + } - // Initialize a barcode reader with the image stream. - using (var reader = new BarCodeReader(ms)) - { - // Specify that we only want to decode DataMatrix barcodes. - reader.BarCodeReadType = DecodeType.DataMatrix; + // Verify that the image file was successfully created. + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Error: Barcode image '{imagePath}' was not found."); + return; + } - // Perform the barcode recognition and retrieve results. - var results = reader.ReadBarCodes(); + // Create a BarCodeReader to read the barcode from the image. + using (var reader = new BarCodeReader(imagePath)) + { + // Set the decode type to DataMatrix before reading to limit detection to this symbology. + reader.BarCodeReadType = DecodeType.DataMatrix; - // Iterate through each recognized barcode and output its details. - foreach (var result in results) - { - Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text: {result.CodeText}"); - } - } + // Perform barcode detection and iterate through any results. + foreach (var result in reader.ReadBarCodes()) + { + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Decoded Text: {result.CodeText}"); } } } diff --git a/mailmark-two-dimensional-barcode/stream-generated-barcode-directly-to-http-response-without-writing-to-disk.cs b/mailmark-two-dimensional-barcode/stream-generated-barcode-directly-to-http-response-without-writing-to-disk.cs index 80f845c..5979976 100644 --- a/mailmark-two-dimensional-barcode/stream-generated-barcode-directly-to-http-response-without-writing-to-disk.cs +++ b/mailmark-two-dimensional-barcode/stream-generated-barcode-directly-to-http-response-without-writing-to-disk.cs @@ -1,52 +1,48 @@ +// Title: Stream Barcode Directly to HTTP Response Using MemoryStream +// Description: Demonstrates generating a barcode image in memory and preparing it for direct HTTP response streaming without writing to disk. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator and BarCodeImageFormat to create barcode images on the fly. Developers often need to embed barcodes in web pages or APIs, requiring in‑memory image handling and response streaming. The snippet shows typical usage of the generator, memory streams, and Base64 encoding for web delivery. +// Prompt: Stream the generated barcode directly to an HTTP response without writing to disk. +// Tags: barcode generation, code128, png, memorystream, base64, aspnet, aspnetcore, aspose.barcode + using System; using System.IO; -using System.Net; -using System.Net.Http; +using System.Text; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing.Imaging; /// -/// Demonstrates generating a Code128 barcode, converting it to PNG, -/// and simulating an HTTP response containing the image. +/// Example program that generates a Code128 barcode, encodes it as Base64, +/// and writes the result to the console (simulating an HTTP response body). /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, wraps it in an HTTP response, and prints details to the console. + /// Entry point of the example. Generates a barcode in memory and outputs a Base64 data URI. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample text "123ABC" + // NOTE: The original request is to stream the barcode directly to an HTTP response. + // The snippet runner is a plain console application and cannot host an HTTP server. + // Therefore, we generate the barcode into a memory stream and output the image + // as a Base64 string to the console, which can be used as the response body in a real web scenario. + + // Create a barcode generator for Code128 with sample text. using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) { - // Create a memory stream to hold the generated PNG image + // Optional: customize barcode appearance here if needed. + // e.g., generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; + + // Generate the barcode image into a memory stream. using (var ms = new MemoryStream()) { - // Save the barcode image directly into the memory stream in PNG format generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position to the beginning - - // Convert the stream contents to a byte array for further processing - byte[] barcodeBytes = ms.ToArray(); - - // Simulate an HTTP response that would return the barcode image - using (var response = new HttpResponseMessage(HttpStatusCode.OK)) - { - // Set the response content to the barcode byte array - response.Content = new ByteArrayContent(barcodeBytes); - // Specify the MIME type as PNG image - response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png"); + byte[] imageBytes = ms.ToArray(); - // Output simulated response details to the console - Console.WriteLine($"HTTP Response Status: {response.StatusCode}"); - Console.WriteLine($"Content-Type: {response.Content.Headers.ContentType}"); - Console.WriteLine($"Barcode image size: {barcodeBytes.Length} bytes"); + // Convert the image bytes to a Base64 string. + string base64Image = Convert.ToBase64String(imageBytes); - // Optionally display the image as a Base64-encoded string for debugging or logging - Console.WriteLine($"Base64 Image: {Convert.ToBase64String(barcodeBytes)}"); - } + // Output the Base64 string to the console. + Console.WriteLine("data:image/png;base64," + base64Image); } } } diff --git a/mailmark-two-dimensional-barcode/use-complexcodetextreadertrydecodemailmark2d-to-obtain-mailmark2dcodetext-object-from-decoded-result.cs b/mailmark-two-dimensional-barcode/use-complexcodetextreadertrydecodemailmark2d-to-obtain-mailmark2dcodetext-object-from-decoded-result.cs index a5af2ba..186edc2 100644 --- a/mailmark-two-dimensional-barcode/use-complexcodetextreadertrydecodemailmark2d-to-obtain-mailmark2dcodetext-object-from-decoded-result.cs +++ b/mailmark-two-dimensional-barcode/use-complexcodetextreadertrydecodemailmark2d-to-obtain-mailmark2dcodetext-object-from-decoded-result.cs @@ -1,38 +1,78 @@ +// Title: Generate and Decode Mailmark2D Barcode +// Description: Demonstrates creating a Mailmark2D barcode, saving it as a PNG image in memory, reading it back, and decoding its individual fields. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode operations collection, showcasing the use of ComplexBarcodeGenerator for barcode creation, BarCodeReader for image recognition, and ComplexCodetextReader for parsing Mailmark2D codetext. Developers working with postal and logistics solutions often need to generate Mailmark2D symbols, extract their data, and integrate it into tracking systems. The snippet illustrates typical workflows involving these key API classes. +/// Prompt: Use ComplexCodetextReader.TryDecodeMailmark2D to obtain a Mailmark2DCodetext object from the decoded result. +/// Tags: mailmark2d, barcode generation, barcode recognition, png, complexbarcodegenerator, barcodereader, complexcodetextreader, mailmark2dcodetext + using System; +using System.IO; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode.ComplexBarcode; /// -/// Demonstrates decoding of a Mailmark 2D codetext using Aspose.BarCode. +/// Example program that generates a Mailmark2D barcode, reads it, and decodes its fields. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Generates a Mailmark2D barcode, reads it from a memory stream, + /// and uses ComplexCodetextReader to decode the codetext into a Mailmark2DCodetext object. /// static void Main() { - // Define a sample encoded Mailmark 2D codetext. - // Replace this placeholder with an actual encoded value when available. - string encodedCodetext = "SampleEncodedCodetext"; - - // Attempt to decode the provided codetext into a Mailmark2DCodetext object. - Mailmark2DCodetext mailmark2d = ComplexCodetextReader.TryDecodeMailmark2D(encodedCodetext); - - // Check if decoding was successful. - if (mailmark2d != null) + // Create a Mailmark2D codetext with required fields + var mailmark2d = new Mailmark2DCodetext { - // Output each decoded property to the console. - Console.WriteLine("Decoded Mailmark2D codetext:"); - Console.WriteLine($"VersionID: {mailmark2d.VersionID}"); - Console.WriteLine($"InformationTypeID: {mailmark2d.InformationTypeID}"); - Console.WriteLine($"Class: {mailmark2d.Class}"); - Console.WriteLine($"RTSFlag: {mailmark2d.RTSFlag}"); - Console.WriteLine($"DestinationPostCodeAndDPS: {mailmark2d.DestinationPostCodeAndDPS}"); - } - else + VersionID = "1", // single‑character string + InformationTypeID = "0", // single‑character string + Class = "1", // single‑character string + RTSFlag = "0", // single‑character string + SupplyChainID = 384224, // integer + ItemID = 16563762, // integer + DestinationPostCodeAndDPS = "EF61AH8T " // valid postcode+DPs + }; + + // Generate the Mailmark2D barcode image into a memory stream + using (var generator = new ComplexBarcodeGenerator(mailmark2d)) { - // Inform the user that decoding failed. - Console.WriteLine("Failed to decode Mailmark2D codetext."); + using (var ms = new MemoryStream()) + { + // Save the barcode as PNG into the stream + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; // Reset stream position for reading + + // Read the barcode from the generated image + using (var reader = new BarCodeReader()) + { + reader.SetBarCodeImage(ms); + var results = reader.ReadBarCodes(); + + // Process each detected barcode result + foreach (var result in results) + { + Console.WriteLine($"Detected CodeText: {result.CodeText}"); + + // Decode the codetext into a Mailmark2DCodetext object + Mailmark2DCodetext decoded = ComplexCodetextReader.TryDecodeMailmark2D(result.CodeText); + if (decoded != null) + { + Console.WriteLine("Decoded Mailmark2D fields:"); + Console.WriteLine($" VersionID: {decoded.VersionID}"); + Console.WriteLine($" InformationTypeID: {decoded.InformationTypeID}"); + Console.WriteLine($" Class: {decoded.Class}"); + Console.WriteLine($" RTSFlag: {decoded.RTSFlag}"); + Console.WriteLine($" SupplyChainID: {decoded.SupplyChainID}"); + Console.WriteLine($" ItemID: {decoded.ItemID}"); + Console.WriteLine($" DestinationPostCodeAndDPS: {decoded.DestinationPostCodeAndDPS}"); + } + else + { + Console.WriteLine("Failed to decode Mailmark2D codetext."); + } + } + } + } } } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/use-memorystream-to-hold-barcode-image-for-in-memory-processing-and-transmission.cs b/mailmark-two-dimensional-barcode/use-memorystream-to-hold-barcode-image-for-in-memory-processing-and-transmission.cs index 79edf86..eea9ab0 100644 --- a/mailmark-two-dimensional-barcode/use-memorystream-to-hold-barcode-image-for-in-memory-processing-and-transmission.cs +++ b/mailmark-two-dimensional-barcode/use-memorystream-to-hold-barcode-image-for-in-memory-processing-and-transmission.cs @@ -1,44 +1,52 @@ +// Title: Generate Code128 barcode and process it in-memory using MemoryStream +// Description: Demonstrates creating a Code128 barcode, saving it to a MemoryStream in PNG format, and accessing the image bytes for further processing or transmission. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to use BarcodeGenerator, set visual parameters, and save the barcode to a stream. Developers often need to generate barcodes on the fly and transmit them without writing to disk, such as in web APIs or email attachments. The snippet shows typical usage of EncodeTypes, BarCodeImageFormat, and stream handling for in‑memory operations. +// Prompt: Use a MemoryStream to hold the barcode image for in‑memory processing and transmission. +// Tags: code128, barcode generation, memorystream, png, in-memory processing, aspnet, aspose.barcode + using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates generating a Code128 barcode, saving it to a memory stream, -/// and displaying basic information about the generated image. +/// Demonstrates generating a Code128 barcode, storing it in a MemoryStream, +/// and performing in‑memory processing such as size reporting and Base64 conversion. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, writes it to a memory stream, and outputs its size and Base64 preview. + /// Entry point of the example. Creates a barcode, saves it to a MemoryStream, + /// and outputs image size and Base64 representation. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample text "123456789" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789")) + // Initialize a barcode generator for Code128 with the sample text "Sample123" + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Set the image resolution to 300 DPI (optional) - generator.Parameters.Resolution = 300f; + // Configure visual appearance: white background and black bars + generator.Parameters.BackColor = Color.White; + generator.Parameters.Barcode.BarColor = Color.Black; - // Create a memory stream to hold the generated PNG image - using (var ms = new MemoryStream()) + // Create a MemoryStream to hold the generated PNG image in memory + using (var memoryStream = new MemoryStream()) { - // Save the barcode image into the memory stream in PNG format - generator.Save(ms, BarCodeImageFormat.Png); + // Save the barcode image into the stream in PNG format + generator.Save(memoryStream, BarCodeImageFormat.Png); - // Reset the stream position to the beginning for subsequent reading - ms.Position = 0; + // Reset stream position to the beginning for reading + memoryStream.Position = 0; - // Retrieve the image bytes from the memory stream - byte[] imageBytes = ms.ToArray(); + // Extract the image bytes from the stream for further processing or transmission + byte[] imageBytes = memoryStream.ToArray(); - // Output the size of the generated image in bytes + // Display the size of the generated image in bytes Console.WriteLine($"Generated barcode image size: {imageBytes.Length} bytes"); - // Convert the image bytes to a Base64 string and display the first 100 characters + // Example of converting the image bytes to a Base64 string and displaying it string base64 = Convert.ToBase64String(imageBytes); - Console.WriteLine($"Base64 representation (first 100 chars): {base64.Substring(0, Math.Min(100, base64.Length))}"); + Console.WriteLine($"Base64: {base64}"); } } } diff --git a/mailmark-two-dimensional-barcode/validate-that-all-non-customer-fields-conform-to-c40-character-set-before-generation.cs b/mailmark-two-dimensional-barcode/validate-that-all-non-customer-fields-conform-to-c40-character-set-before-generation.cs index 422b3ab..5d98de8 100644 --- a/mailmark-two-dimensional-barcode/validate-that-all-non-customer-fields-conform-to-c40-character-set-before-generation.cs +++ b/mailmark-two-dimensional-barcode/validate-that-all-non-customer-fields-conform-to-c40-character-set-before-generation.cs @@ -1,94 +1,79 @@ +// Title: DataMatrix barcode generation with C40 encoding validation +// Description: Demonstrates validating non‑customer fields against the C40 character set before generating a DataMatrix barcode. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on DataMatrix symbology and character set validation. It showcases the use of BarcodeGenerator, EncodeTypes, and DataMatrixEncodeMode classes to produce PNG images, a common requirement for developers needing compliant barcode output in logistics and inventory systems. +// Prompt: Validate that all non‑customer fields conform to the C40 character set before generation. +// Tags: datamatrix, c40, validation, png, barcodegenerator, datamatrixencodemode, aspnet.barcode + using System; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates generation of a Code128 barcode after validating input against the C40 character set. +/// Generates a DataMatrix barcode using C40 encoding after validating the input string. /// class Program { /// - /// Determines whether the supplied text contains only characters allowed in the C40 character set (basic subset). + /// Entry point. Validates the code text against the C40 charset and creates a PNG barcode if valid. /// - /// The text to validate. - /// True if the text is null, empty, or contains only valid C40 characters; otherwise, false. - private static bool IsValidC40(string text) + static void Main() { - // Empty or null strings are considered valid. - if (string.IsNullOrEmpty(text)) - return true; + // Sample code text representing non‑customer fields + string codeText = "HELLO WORLD 123!"; - // Examine each character in the string. - foreach (char ch in text) + // Validate that the code text conforms to the C40 character set + if (!IsC40String(codeText)) { - // Digits 0‑9 are allowed. - if (ch >= '0' && ch <= '9') - continue; + Console.WriteLine("Warning: CodeText contains characters not allowed in the C40 charset. Generation skipped."); + return; + } - // Uppercase letters A‑Z are allowed. - if (ch >= 'A' && ch <= 'Z') - continue; + // Create a DataMatrix barcode generator with C40 encoding mode + using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, codeText)) + { + // Set the DataMatrix encode mode to C40 + generator.Parameters.Barcode.DataMatrix.EncodeMode = DataMatrixEncodeMode.C40; - // Space character is allowed. - if (ch == ' ') - continue; + // Optionally control image size (using unit members) + generator.Parameters.ImageWidth.Point = 200f; + generator.Parameters.ImageHeight.Point = 200f; - // Allow a set of common punctuation characters. - switch (ch) - { - case '-': - case '/': - case '.': - case ',': - case '+': - case '*': - case ':': - case ';': - case '?': - case '!': - continue; - default: - // Any other character is invalid for C40. - return false; - } + // Save the generated barcode image + string outputPath = "datamatrix_c40.png"; + generator.Save(outputPath); + Console.WriteLine($"Barcode saved to {outputPath}"); } - - // All characters passed validation. - return true; } - /// - /// Entry point of the application. Validates sample data and generates a Code128 barcode if validation succeeds. - /// - static void Main() + // Checks if every character in the string is allowed in the C40 charset + static bool IsC40String(string text) { - // Sample non‑customer data that needs C40 validation. - string nonCustomerData = "ABC-123/XYZ"; - - // Abort if the data contains characters outside the allowed C40 set. - if (!IsValidC40(nonCustomerData)) + foreach (char ch in text) { - Console.WriteLine("Non‑customer data contains characters outside the C40 set. Generation aborted."); - return; + if (!IsC40Char(ch)) + return false; } + return true; + } - // Construct the barcode's codetext, incorporating the validated data. - string codeText = $"NONCUST:{nonCustomerData}"; + // Determines whether a single character is part of the C40 charset + static bool IsC40Char(char ch) + { + // Uppercase letters + if (ch >= 'A' && ch <= 'Z') + return true; - // Generate a simple Code128 barcode using Aspose.BarCode. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) - { - // Set barcode height (in points) and enable anti‑aliasing for better visual quality. - generator.Parameters.Barcode.BarHeight.Point = 40f; - generator.Parameters.UseAntiAlias = true; + // Digits + if (ch >= '0' && ch <= '9') + return true; - // Determine the output file path in the current working directory. - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png"); + // Space + if (ch == ' ') + return true; - // Save the generated barcode image to disk. - generator.Save(outputPath); - Console.WriteLine($"Barcode generated and saved to: {outputPath}"); - } + // Basic punctuation allowed in C40 + const string punctuation = "!\"#%&'()*+,-./:;<=>?"; + return punctuation.IndexOf(ch) >= 0; } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/validate-that-customer-data-length-does-not-exceed-capacity-for-selected-mailmark-type.cs b/mailmark-two-dimensional-barcode/validate-that-customer-data-length-does-not-exceed-capacity-for-selected-mailmark-type.cs index 076f2c1..b60a162 100644 --- a/mailmark-two-dimensional-barcode/validate-that-customer-data-length-does-not-exceed-capacity-for-selected-mailmark-type.cs +++ b/mailmark-two-dimensional-barcode/validate-that-customer-data-length-does-not-exceed-capacity-for-selected-mailmark-type.cs @@ -1,148 +1,116 @@ +// Title: Validate Mailmark2D Customer Content Length +// Description: Demonstrates how to verify that customer data fits within the capacity limits of selected Mailmark 2D types before generating barcodes. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on Mailmark2D validation and image creation. It showcases key API classes such as Mailmark2DCodetext, ComplexBarcodeGenerator, and BarCodeImageFormat, which developers commonly use to produce Mailmark barcodes for postal services while ensuring data compliance. +// Prompt: Validate that customer data length does not exceed capacity for the selected Mailmark type. +// Tags: mailmark, validation, png, complexbarcode, generation, aspnet.barcode + using System; +using System.Collections.Generic; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing.Imaging; +using Aspose.Drawing; /// -/// Demonstrates generation and decoding of Mailmark and Mailmark2D barcodes using Aspose.BarCode. +/// Example program that validates customer content length for Mailmark2D types +/// and generates corresponding barcode images. /// class Program { - // Define capacity limits for different Mailmark types - private const int Mailmark2DCustomerContentMaxLength = 30; // example limit + // Mapping of Mailmark 2D type to maximum allowed customer content length. + private static readonly Dictionary MaxContentLengthByType = new() + { + { 7, 6 }, // Type 7: 6 characters + { 9, 45 }, // Type 9: 45 characters + { 29, 25 } // Type 29: 25 characters + }; /// - /// Entry point of the application. Generates a barcode based on the selected Mailmark type, - /// validates customer data, saves the barcode image, and optionally decodes it. + /// Entry point. Iterates over sample records, validates content length, + /// builds Mailmark2DCodetext objects, and saves barcode images. /// static void Main() { - // Sample inputs - string selectedMailmarkType = "Mailmark2D"; // could be "Mailmark" or "Mailmark2D" - string customerContent = "Sample customer data for Mailmark 2D barcode"; - - try + // Sample records: each tuple contains (Mailmark2D type, customer content) + var records = new List<(int Type, string Content)> { - // Validate the customer content against the selected Mailmark type's constraints - ValidateCustomerData(customerContent, selectedMailmarkType); - Console.WriteLine("Customer data validation passed."); + (7, "ABC123"), // exactly 6 chars – valid + (9, "THIS IS A LONGER CONTENT EXAMPLE THAT FITS"), // 45 chars – valid + (29, "TOO LONG CUSTOMER CONTENT EXCEEDING LIMIT") // exceeds 25 chars – invalid + }; - // Build the appropriate codetext object based on the selected type - if (selectedMailmarkType.Equals("Mailmark2D", StringComparison.OrdinalIgnoreCase)) + int index = 1; + foreach (var (type, content) in records) + { + try { - // Populate Mailmark2D codetext with required and optional fields - var mailmark2D = new Mailmark2DCodetext + // Validate that the content length is within the allowed limit for the type. + ValidateCustomerContent(content, type); + + // Build Mailmark2DCodetext with required fields and sample values. + var mailmark2d = new Mailmark2DCodetext { - VersionID = "1", + // Required fields: InformationTypeID, VersionID, Class, RTSFlag, SupplyChainID, ItemID, DestinationPostCodeAndDPS InformationTypeID = "0", + VersionID = "1", Class = "1", - SupplyChainID = 384224, - ItemID = 16563762, + RTSFlag = "0", + SupplyChainID = 1234567, + ItemID = 1000 + index, DestinationPostCodeAndDPS = "EF61AH8T ", - CustomerContent = customerContent, // Set after validation - CustomerContentEncodeMode = DataMatrixEncodeMode.C40 // Optional encoding mode + // Set the selected DataMatrix type (if needed). Assuming enum values match the integer. + // DataMatrixType = (DataMatrixType)type, // Uncomment if enum exists. + CustomerContent = content, + CustomerContentEncodeMode = DataMatrixEncodeMode.C40 // example encode mode }; - // Generate the barcode image and save it as PNG - using (var generator = new ComplexBarcodeGenerator(mailmark2D)) + // Generate barcode image and write it to a PNG file. + using (var generator = new ComplexBarcodeGenerator(mailmark2d)) { - string outputPath = "Mailmark2D.png"; - generator.Save(outputPath, BarCodeImageFormat.Png); - Console.WriteLine($"Mailmark2D barcode saved to {outputPath}"); - } - - // Demonstrate decoding the generated barcode (read back the image) - using (var imageStream = new FileStream("Mailmark2D.png", FileMode.Open, FileAccess.Read)) - using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes)) - { - foreach (var result in reader.ReadBarCodes()) + using (var ms = new MemoryStream()) { - // Decode the complex codetext from the raw code text - Mailmark2DCodetext decoded = ComplexCodetextReader.TryDecodeMailmark2D(result.CodeText); - if (decoded != null) - { - Console.WriteLine("Decoded Mailmark2D CustomerContent: " + decoded.CustomerContent); - } - else - { - Console.WriteLine("Failed to decode Mailmark2D codetext."); - } + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; + string fileName = $"Mailmark2D_{index}.png"; + File.WriteAllBytes(fileName, ms.ToArray()); + Console.WriteLine($"Record {index}: Barcode saved to {fileName}"); } } } - else if (selectedMailmarkType.Equals("Mailmark", StringComparison.OrdinalIgnoreCase)) + catch (ArgumentException ex) { - // Populate Mailmark (4‑state) codetext with required fields - var mailmark = new MailmarkCodetext - { - Format = 4, - VersionID = 1, - Class = "0", - SupplychainID = 384224, - ItemID = 16563762, - DestinationPostCodePlusDPS = "EF61AH8T " - }; - - // Generate the barcode image and save it as PNG - using (var generator = new ComplexBarcodeGenerator(mailmark)) - { - string outputPath = "Mailmark.png"; - generator.Save(outputPath, BarCodeImageFormat.Png); - Console.WriteLine($"Mailmark barcode saved to {outputPath}"); - } + // Handle validation errors (e.g., content too long or unsupported type). + Console.WriteLine($"Record {index}: Validation error – {ex.Message}"); } - else + catch (Exception ex) { - Console.WriteLine($"Unsupported Mailmark type: {selectedMailmarkType}"); + // Handle any unexpected errors during barcode generation. + Console.WriteLine($"Record {index}: Unexpected error – {ex.Message}"); } - } - catch (ArgumentException ex) - { - // Handle validation errors - Console.WriteLine("Validation error: " + ex.Message); - } - catch (Exception ex) - { - // Handle any unexpected errors - Console.WriteLine("Unexpected error: " + ex.Message); + + index++; } } - /// - /// Validates that the customer data length fits the capacity of the selected Mailmark type. - /// - /// Customer content to validate. - /// Selected Mailmark type (e.g., "Mailmark2D" or "Mailmark"). - /// Thrown when validation fails. - private static void ValidateCustomerData(string data, string mailmarkType) + // Validates that the customer content length does not exceed the capacity for the given Mailmark type. + private static void ValidateCustomerContent(string content, int mailmarkType) { - if (string.IsNullOrEmpty(data)) + // Ensure the Mailmark type is supported. + if (!MaxContentLengthByType.TryGetValue(mailmarkType, out int maxLength)) { - // Empty data is acceptable for both types - return; + throw new ArgumentException($"Unsupported Mailmark type '{mailmarkType}'."); } - if (mailmarkType.Equals("Mailmark2D", StringComparison.OrdinalIgnoreCase)) - { - // Ensure the content does not exceed the defined maximum length - if (data.Length > Mailmark2DCustomerContentMaxLength) - { - throw new ArgumentException( - $"Customer content length ({data.Length}) exceeds the maximum allowed ({Mailmark2DCustomerContentMaxLength}) for Mailmark2D."); - } - } - else if (mailmarkType.Equals("Mailmark", StringComparison.OrdinalIgnoreCase)) + // Ensure content is not null. + if (content == null) { - // 4‑state Mailmark does not have a CustomerContent field; any non‑empty data is invalid. - throw new ArgumentException("Customer content is not supported for the selected Mailmark type (4‑state)."); + throw new ArgumentException("Customer content cannot be null."); } - else + + // Ensure content length does not exceed the maximum allowed for the type. + if (content.Length > maxLength) { - // Unknown Mailmark type supplied - throw new ArgumentException($"Unknown Mailmark type: {mailmarkType}"); + throw new ArgumentException($"Customer content length ({content.Length}) exceeds maximum allowed ({maxLength}) for Mailmark type {mailmarkType}."); } } } \ No newline at end of file diff --git a/mailmark-two-dimensional-barcode/write-unit-tests-that-verify-generated-barcodes-contain-exact-routing-and-service-code-values.cs b/mailmark-two-dimensional-barcode/write-unit-tests-that-verify-generated-barcodes-contain-exact-routing-and-service-code-values.cs index d721e3c..5eee3c6 100644 --- a/mailmark-two-dimensional-barcode/write-unit-tests-that-verify-generated-barcodes-contain-exact-routing-and-service-code-values.cs +++ b/mailmark-two-dimensional-barcode/write-unit-tests-that-verify-generated-barcodes-contain-exact-routing-and-service-code-values.cs @@ -1,3 +1,9 @@ +// Title: Verify routing and service codes in generated Code128 barcode +// Description: Demonstrates generating a Code128 barcode containing routing and service codes, then reading it back to confirm the exact values. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to use BarcodeGenerator and BarCodeReader classes to create and validate barcodes. Typical use cases include encoding custom data strings such as routing and service identifiers and verifying them programmatically. Developers often need unit‑testable code that confirms the encoded content matches expectations. +// Prompt: Write unit tests that verify generated barcodes contain the exact routing and service code values. +// Tags: code128, barcode generation, barcode recognition, routing code, service code, unit test + using System; using System.IO; using Aspose.BarCode; @@ -6,65 +12,83 @@ using Aspose.Drawing; /// -/// Demonstrates generation and recognition of an Australia Post barcode using Aspose.BarCode. +/// Example program that generates a Code128 barcode containing routing and service codes, +/// then reads the barcode to verify the encoded text matches the expected values. /// class Program { /// - /// Entry point of the application. Generates a barcode, saves it to a memory stream, - /// then reads it back to verify the encoded text matches the original. + /// Entry point of the program. Executes the routing and service code verification test + /// and outputs the result to the console. /// static void Main() { - // Sample routing and service code values for AustraliaPost barcode - string originalCodeText = "5912345678ABCde"; // example includes routing/service info + // Run the test and output the result. + bool testResult = TestRoutingAndServiceCode(); + Console.WriteLine(testResult ? "Test Passed" : "Test Failed"); + } - // Create a barcode generator for Australia Post format with the original text - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, originalCodeText)) - { - // Optional: set the encoding table to CTable for customer information interpretation - generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable; + /// + /// Generates a barcode with predefined routing and service codes, saves it to a file, + /// reads it back, and verifies that the decoded text matches the expected concatenated value. + /// + /// True if the decoded barcode text matches the expected value; otherwise, false. + static bool TestRoutingAndServiceCode() + { + // Define expected routing and service codes. + string routingCode = "R12345"; + string serviceCode = "S67890"; - // Use a memory stream to hold the generated PNG image - using (var ms = new MemoryStream()) - { - // Save the barcode image into the memory stream - generator.Save(ms, BarCodeImageFormat.Png); - // Reset stream position to the beginning for reading - ms.Position = 0; + // Combine them into the barcode text (format can be adjusted as needed). + string expectedCodeText = routingCode + serviceCode; - // Initialize a barcode reader to decode the image from the memory stream - using (var reader = new BarCodeReader(ms, DecodeType.AustraliaPost)) - { - // Ensure checksum validation is enabled (default behavior) - reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; + // Prepare a temporary file path for the generated barcode image. + string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "routing_service.png"); - // Read all barcodes found in the image - var results = reader.ReadBarCodes(); + // Ensure any previous file is removed. + if (File.Exists(imagePath)) + { + File.Delete(imagePath); + } - // If no barcodes were detected, report failure and exit - if (results.Length == 0) - { - Console.WriteLine("FAIL: No barcode detected."); - return; - } + // Generate the barcode. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, expectedCodeText)) + { + // Optional: set image size via AutoSizeMode.Interpolation to avoid manual dimensions. + generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - // Take the first detected barcode result - var result = results[0]; + // Save the barcode image. + generator.Save(imagePath); + } - // Compare the recognized text with the original input - if (result.CodeText == originalCodeText) - { - Console.WriteLine("PASS: Recognized CodeText matches original."); - } - else - { - Console.WriteLine($"FAIL: Recognized CodeText '{result.CodeText}' does not match original '{originalCodeText}'."); - } + // Verify that the file was created. + if (!File.Exists(imagePath)) + { + Console.WriteLine("Failed to create barcode image."); + return false; + } - // Placeholder for additional verification of routing/service fields if needed + // Read the barcode back and compare the decoded text. + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Compare the decoded CodeText with the expected value. + if (result.CodeText == expectedCodeText) + { + // Success: exact routing and service codes are present. + return true; + } + else + { + Console.WriteLine($"Decoded text mismatch. Expected: {expectedCodeText}, Got: {result.CodeText}"); + return false; } } } + + // If no barcode was read, the test fails. + Console.WriteLine("No barcode detected in the image."); + return false; } } \ No newline at end of file From a782547b21afc8742ffdc8fe2c4cb071bf7852a0 Mon Sep 17 00:00:00 2001 From: agent-aspose-barcode-examples Date: Tue, 7 Jul 2026 22:10:03 +0500 Subject: [PATCH 2/2] =?UTF-8?q?feat(mailmark-two-dimensional-barcode):=20A?= =?UTF-8?q?dd=201=20Aspose.BarCode=20.NET=20C#=20examples=20for=20Mailmark?= =?UTF-8?q?=20Two=20Dimensional=20Barcode=20=E2=80=94=20Aspose.BarCode=20f?= =?UTF-8?q?or=20.NET=2026.6.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...t-regeneration-for-identical-field-sets.cs | 107 ++++++++++-------- 1 file changed, 57 insertions(+), 50 deletions(-) diff --git a/mailmark-two-dimensional-barcode/cache-generated-barcode-images-in-memory-to-avoid-redundant-regeneration-for-identical-field-sets.cs b/mailmark-two-dimensional-barcode/cache-generated-barcode-images-in-memory-to-avoid-redundant-regeneration-for-identical-field-sets.cs index 5c3e6d8..3cb2863 100644 --- a/mailmark-two-dimensional-barcode/cache-generated-barcode-images-in-memory-to-avoid-redundant-regeneration-for-identical-field-sets.cs +++ b/mailmark-two-dimensional-barcode/cache-generated-barcode-images-in-memory-to-avoid-redundant-regeneration-for-identical-field-sets.cs @@ -1,92 +1,99 @@ // Title: In-Memory Barcode Image Caching Example -// Description: Demonstrates how to cache generated barcode images in memory to avoid regenerating identical barcodes, improving performance. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, BaseEncodeType, and image handling classes. Developers often need to generate multiple barcodes with repeated data, and caching reduces redundant processing and resource usage. Ideal for batch processing, reporting, or any scenario where the same barcode may be requested multiple times. +// Description: Demonstrates caching of generated barcode images in memory to avoid redundant regeneration for identical barcode specifications. +// Category-Description: This example belongs to the Aspose.BarCode generation and caching category, showcasing how to use BarcodeGenerator, BaseEncodeType, and BarCodeImageFormat to create barcodes, store them in a dictionary, and reuse them. Developers often need to improve performance when generating many barcodes with repeated parameters, and this pattern provides a simple in‑process cache. // Prompt: Cache generated barcode images in memory to avoid redundant regeneration for identical field sets. -// Tags: barcode, caching, memory, code128, qr, datamatrix, aspnet, aspose.barcode, image generation +// Tags: barcode, caching, memory, code128, qr, datamatrix, generation, aspnet, aspose.barcode using System; using System.Collections.Generic; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; -using Aspose.Drawing.Imaging; +using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates in‑memory caching of barcode images to prevent duplicate generation. +/// Provides an in‑memory cache for barcode images generated with Aspose.BarCode. /// -class Program +class BarcodeCache { + // Internal dictionary that maps a unique key (encode type + text) to the generated PNG bytes. + private static readonly Dictionary _cache = new Dictionary(); + /// - /// Retrieves a barcode image from the cache or generates a new one if it does not exist. + /// Retrieves a cached barcode image or generates a new one if it does not exist. /// - /// The barcode symbology to use. - /// The text or data to encode. - /// Dictionary that stores previously generated images keyed by symbology and text. - /// A containing the generated barcode. - static Bitmap GetBarcodeImage(BaseEncodeType encodeType, string codeText, Dictionary cache) + /// The barcode symbology to use (e.g., Code128, QR). + /// The text or data to encode in the barcode. + /// A byte array containing the PNG image of the barcode. + public static byte[] GetOrCreate(BaseEncodeType encodeType, string codeText) { - // Build a unique cache key from the encode type and the text. - string key = $"{encodeType}:{codeText}"; + // Build a unique cache key based on the encode type's full name, its enum value, and the text. + string key = $"{encodeType.GetType().FullName}:{encodeType}:{codeText}"; // Return the cached image if it already exists. - if (cache.TryGetValue(key, out Bitmap cachedImage)) + if (_cache.TryGetValue(key, out byte[] cachedData)) { - Console.WriteLine($"Cache hit for key: {key}"); - return cachedImage; + Console.WriteLine($"Cache hit for [{encodeType}] \"{codeText}\""); + return cachedData; } - // No cached image – generate a new barcode. - Console.WriteLine($"Generating barcode for key: {key}"); + // Cache miss – generate a new barcode image. + Console.WriteLine($"Generating barcode for [{encodeType}] \"{codeText}\""); using (var generator = new BarcodeGenerator(encodeType, codeText)) { - Bitmap image = generator.GenerateBarCodeImage(); - cache[key] = image; // Store the newly generated image for future requests. - return image; + // Example: set a higher resolution for better image quality. + generator.Parameters.Resolution = 300; + + using (var ms = new MemoryStream()) + { + // Save the barcode to the memory stream in PNG format. + generator.Save(ms, BarCodeImageFormat.Png); + byte[] data = ms.ToArray(); + + // Store the generated image in the cache for future requests. + _cache[key] = data; + return data; + } } } +} +/// +/// Demonstrates the use of to generate and cache barcode images. +/// +class Program +{ /// - /// Entry point of the example. Generates several barcodes, some of which are duplicates, - /// to demonstrate caching. Saves each image to disk and disposes resources afterwards. + /// Entry point of the example. Generates a series of barcodes, some of which are duplicates, + /// to illustrate caching behavior, and writes the images to disk. /// static void Main() { - // In‑memory cache: maps a unique key to a barcode bitmap. - var barcodeCache = new Dictionary(); - - // Define a set of barcode requests; duplicates are intentional to test caching. - var requests = new (BaseEncodeType type, string text)[] + // Define a list of barcode generation requests; duplicates test the cache. + var requests = new List<(BaseEncodeType type, string text)> { - (EncodeTypes.Code128, "123ABC"), + (EncodeTypes.Code128, "ABC123"), (EncodeTypes.QR, "https://example.com"), - (EncodeTypes.Code128, "123ABC"), // duplicate + (EncodeTypes.Code128, "ABC123"), // duplicate (EncodeTypes.DataMatrix, "DataMatrixSample"), (EncodeTypes.QR, "https://example.com") // duplicate }; - // Process each request, retrieving from cache or generating as needed. - for (int i = 0; i < requests.Length; i++) + int index = 1; + foreach (var (type, text) in requests) { - var (type, text) = requests[i]; - Bitmap barcodeImage = GetBarcodeImage(type, text, barcodeCache); + // Retrieve the barcode image, using the cache when possible. + byte[] imageData = BarcodeCache.GetOrCreate(type, text); - // Save each image with a unique filename for verification. - string fileName = $"barcode_{i + 1}.png"; - using (var fileStream = System.IO.File.OpenWrite(fileName)) - { - barcodeImage.Save(fileStream, ImageFormat.Png); - } + // Construct a file name that includes the request order and barcode type. + string fileName = $"barcode_{index}_{type}.png"; + // Write the PNG bytes to disk. + File.WriteAllBytes(fileName, imageData); Console.WriteLine($"Saved barcode to {fileName}"); + index++; } - // Dispose all cached bitmaps before exiting to free unmanaged resources. - foreach (var kvp in barcodeCache) - { - kvp.Value.Dispose(); - } - - Console.WriteLine("All barcodes processed. Press any key to exit."); - Console.ReadKey(); + Console.WriteLine("Processing completed."); } } \ No newline at end of file