From e6dae34ef8e25368a312c6d714c5a880eb82df36 Mon Sep 17 00:00:00 2001 From: agent-aspose-barcode-examples Date: Fri, 7 Aug 2026 12:07:22 +0500 Subject: [PATCH] =?UTF-8?q?feat(mailmark-two-dimensional-barcode):=20Add?= =?UTF-8?q?=2034=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.7.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...-for-high-resolution-printing-on-labels.cs | 57 +++--- ...-barcode-image-using-generator-settings.cs | 52 +++--- ...-containing-multiple-rows-of-field-data.cs | 107 +++++------ ...ry-and-output-their-decoded-data-to-csv.cs | 129 ++++++------- ...t-regeneration-for-identical-field-sets.cs | 172 +++++++++++------- ...en-mailmark-type-7-and-type-29-barcodes.cs | 140 ++++++-------- ...age-with-custom-dimensions-for-printing.cs | 41 +++-- ...module-size-for-higher-density-barcodes.cs | 33 ++-- ...elds-and-saves-resulting-barcode-as-png.cs | 81 +++++---- ...outing-service-and-customer-data-values.cs | 70 +++---- ...ance-and-generate-corresponding-barcode.cs | 73 ++++---- ...-returns-generated-barcode-image-stream.cs | 139 ++++++++------ ...d-assess-its-impact-on-barcode-capacity.cs | 94 ++++++---- ...ce-code-from-decoded-mailmark2dcodetext.cs | 69 +++---- ...ground-for-overlaying-on-other-graphics.cs | 32 ++-- ...ecified-routing-and-service-code-fields.cs | 67 +++---- ...logging-warning-and-skipping-generation.cs | 103 +++++------ ...neration-service-throughout-application.cs | 94 ++++------ ...coding-fails-or-returns-incomplete-data.cs | 122 +++++++------ ...nsient-errors-occur-during-image-saving.cs | 74 ++++---- ...ntroller-and-return-image-as-fileresult.cs | 44 +++-- ...es-and-values-to-assist-troubleshooting.cs | 103 +++++------ ...parallel-library-to-improve-performance.cs | 76 ++++---- ...barcodereader-with-decodetypedatamatrix.cs | 43 ++--- ...to-satisfy-specific-layout-requirements.cs | 46 +++-- ...as-jpeg-file-to-specified-output-folder.cs | 31 ++-- ...nd-later-reconstruction-in-applications.cs | 98 +++++----- ...ix-before-invoking-read-method-on-image.cs | 39 ++-- ...o-http-response-without-writing-to-disk.cs | 65 ++++--- ...rk2dcodetext-object-from-decoded-result.cs | 109 ++++++----- ...r-in-memory-processing-and-transmission.cs | 61 +++---- ...-to-c40-character-set-before-generation.cs | 115 +++++++----- ...eed-capacity-for-selected-mailmark-type.cs | 141 ++++++-------- ...n-exact-routing-and-service-code-values.cs | 141 +++++++------- 34 files changed, 1418 insertions(+), 1443 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 1cb34f3..12131be 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,8 +1,8 @@ -// 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. +// Title: High‑Resolution Code128 Barcode Generation for Label Printing +// Description: Demonstrates configuring Aspose.BarCode to generate a 300 DPI Code128 barcode image suitable for high‑resolution label printing. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to adjust resolution, module size, bar height, colors, and auto‑size settings using the BarcodeGenerator, EncodeTypes, and Parameters classes. Typical use cases include creating printable barcodes for product labels, shipping tags, and inventory stickers where precise dimensions and high image quality are required. Developers often need to fine‑tune these settings to meet printer specifications and label design guidelines. // 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 +// Tags: code128, generation, png, barcodegenerator, encodetypes, parameters using System; using Aspose.BarCode; @@ -10,52 +10,39 @@ using Aspose.Drawing; /// -/// Generates a high‑resolution Code128 barcode image suitable for label printing. +/// Entry point for the high‑resolution barcode generation example. /// class Program { /// - /// Entry point. Configures barcode generator settings and saves the image. + /// Generates a Code128 barcode image with settings optimized for high‑resolution label printing. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample text "HIGHRES12345" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "HIGHRES12345")) + // Create a Code128 barcode generator with sample text + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Set the image resolution to 300 DPI, which is appropriate for high‑quality label printing + // Set image resolution to 300 DPI for crisp printing generator.Parameters.Resolution = 300; - // Use interpolation mode to allow explicit pixel dimensions for the output image - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + // Define a small module size (XDimension) for fine detail (0.5 points) + generator.Parameters.Barcode.XDimension.Point = 0.5f; - // 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 + // Set bar height appropriate for label size (50 points) + generator.Parameters.Barcode.BarHeight.Point = 50f; - // 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 - - // Set high‑contrast colors: black bars on a white background + // Use black bars on a white background for maximum contrast generator.Parameters.Barcode.BarColor = Color.Black; generator.Parameters.BackColor = Color.White; - // 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; - - // 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}"); + // Disable automatic resizing to preserve exact dimensions + generator.Parameters.AutoSizeMode = AutoSizeMode.None; + + // Save the barcode image as a PNG file + generator.Save("highres_label.png"); } + + // Inform the user that the image has been created + Console.WriteLine("Barcode image generated: highres_label.png"); } } \ 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 f71868d..6a8cd9e 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,40 +1,44 @@ -// 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. +// Title: Custom Foreground and Background Colors for a Code128 Barcode +// Description: Demonstrates how to set custom bar (foreground) and background colors when generating a Code128 barcode image using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize visual appearance of barcodes via the BarcodeGenerator and its Parameters API. Developers often need to match corporate branding or improve scan reliability by adjusting bar and background colors. Typical use cases include creating PNG, JPEG, or PDF barcode assets with specific color schemes. // Prompt: Apply custom foreground and background colors to the barcode image using generator settings. -// Tags: barcode, color, generation, png, aspose.barcode, csharp +// Tags: code128, color, png, barcodegenerator, generation using System; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -/// -/// Shows how to set custom foreground (bar) and background colors for a generated barcode image. -/// -class Program +namespace BarcodeColorExample { /// - /// Entry point of the example. Generates a Code128 barcode with blue bars on a light‑gray background and saves it as a PNG file. + /// Generates a Code128 barcode image with custom foreground (bar) and background colors. /// - static void Main() + class Program { - // Define the output file path for the generated barcode image. - string outputPath = "custom_color_barcode.png"; - - // Initialize a BarcodeGenerator for the Code128 symbology with sample text. - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + /// + /// Entry point of the example. Creates a barcode, applies color settings, and saves it as a PNG file. + /// + static void Main() { - // Set the foreground color (the color of the bars) to blue. - generator.Parameters.Barcode.BarColor = Color.Blue; + // Output file path for the generated barcode image + const string outputFile = "barcode.png"; - // Set the background color of the image to light gray. - generator.Parameters.BackColor = Color.LightGray; + // Initialize a BarcodeGenerator for the Code128 symbology with sample data + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + { + // Set the color of the barcode bars (foreground) + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; - // Save the generated barcode image to the specified file path (default format is PNG). - generator.Save(outputPath); - } + // Set the background color of the image + generator.Parameters.BackColor = Aspose.Drawing.Color.Yellow; - // Inform the user where the barcode image has been saved. - Console.WriteLine($"Barcode image saved to: {outputPath}"); + // Render and save the barcode as a PNG image + generator.Save(outputFile, BarCodeImageFormat.Png); + } + + // Output the location of the saved barcode image + Console.WriteLine($"Barcode image saved to: {outputFile}"); + } } } \ 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 52b6c95..50d6462 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,13 +1,13 @@ -// 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. +// Title: Batch generate Mailmark barcodes from CSV data +// Description: Demonstrates reading a CSV file with Mailmark field values and creating a PNG barcode for each record using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It shows how to work with the Mailmark symbology by populating a MailmarkCodetext object and using ComplexBarcodeGenerator to produce barcodes. Typical scenarios include bulk creation of Mailmark barcodes for mailing, logistics, or inventory systems. Developers often need to parse input data, validate fields, and save barcodes in common image formats such as PNG. // Prompt: Batch generate Mailmark barcodes from a CSV file containing multiple rows of field data. -// Tags: mailmark, barcode, csv, batch, generation, png, aspose.barcode +// Tags: mailmark, barcode, csv, batch, generation, aspose.barcode, complexbarcode, png using System; using System.IO; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; /// /// Generates Mailmark barcodes in batch from a CSV file. @@ -15,40 +15,35 @@ class Program { /// - /// Entry point of the application. Reads Mailmark data from a CSV file, - /// creates a MailmarkCodetext for each record, and saves the resulting PNG images. + /// Entry point. Reads the CSV, validates each row, creates a MailmarkCodetext object, + /// generates a PNG barcode, and saves it to the output folder. /// static void Main() { - // Path to the input CSV file containing Mailmark fields. - string csvPath = "mailmark_data.csv"; + // Define input CSV and output folder paths + string csvPath = "mailmark_input.csv"; + string outputFolder = "Output"; - // Ensure a sample CSV exists if the file is missing. + // Ensure the output folder exists + if (!Directory.Exists(outputFolder)) + { + Directory.CreateDirectory(outputFolder); + } + + // If the CSV does not exist, create a sample file with a few records if (!File.Exists(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[] + var sampleLines = new[] { - "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 " + "Format,VersionID,Class,SupplychainID,ItemID,DestinationPostCodePlusDPS", + "4,1,0,384224,16563760,EF61AH8T ", + "4,1,0,384224,16563761,EF61AH8T ", + "4,1,0,384224,16563762,EF61AH8T " }; File.WriteAllLines(csvPath, sampleLines); } - // Output directory for generated barcode images. - string outputDir = "Barcodes"; - if (!Directory.Exists(outputDir)) - { - Directory.CreateDirectory(outputDir); - } - - // Read all lines from the CSV file and skip the header row. + // Read all lines from the CSV, skipping the header row string[] lines = File.ReadAllLines(csvPath); if (lines.Length <= 1) { @@ -56,68 +51,62 @@ static void Main() return; } - // Process each data row in the CSV. + // Process each data row for (int i = 1; i < lines.Length; i++) { string line = lines[i]; if (string.IsNullOrWhiteSpace(line)) - continue; // Skip empty lines. + continue; // Skip empty lines - // Split the line into individual fields. + // Split by comma (simple CSV, no quoted commas) string[] parts = line.Split(','); - // Validate the expected number of fields (5). - if (parts.Length != 5) + if (parts.Length != 6) { - Console.WriteLine($"Skipping malformed line {i + 1}: {line}"); + Console.WriteLine($"Line {i + 1}: Incorrect number of fields. Skipping."); continue; } - // Parse VersionID. - if (!int.TryParse(parts[0].Trim(), out int versionId)) + // Parse numeric fields; if parsing fails, skip the row + if (!int.TryParse(parts[0].Trim(), out int format) || + !int.TryParse(parts[1].Trim(), out int versionId) || + !int.TryParse(parts[3].Trim(), out int supplyChainId) || + !int.TryParse(parts[4].Trim(), out int itemId)) { - Console.WriteLine($"Invalid VersionID on line {i + 1}"); + Console.WriteLine($"Line {i + 1}: Invalid numeric values. Skipping."); continue; } - // Class is a string value (e.g., "0", "1"). - string classValue = parts[1].Trim(); + // Remaining fields are strings; preserve trailing space for destination as required + string classValue = parts[2].Trim(); + string destination = parts[5]; - // Parse SupplychainID. - if (!int.TryParse(parts[2].Trim(), out int supplyChainId)) + // Validate that the format corresponds to 4‑state Mailmark (value 4) + if (format != 4) { - Console.WriteLine($"Invalid SupplychainID on line {i + 1}"); + Console.WriteLine($"Line {i + 1}: Unsupported Format {format}. Only 4‑state (value 4) is supported. Skipping."); continue; } - // Parse ItemID. - if (!int.TryParse(parts[3].Trim(), out int itemId)) - { - Console.WriteLine($"Invalid ItemID on line {i + 1}"); - continue; - } - - // DestinationPostCodePlusDPS may contain trailing spaces, which are required. - string destination = parts[4]; - - // Build the Mailmark codetext object with the parsed values. + // Build the MailmarkCodetext object with the parsed values var mailmark = new MailmarkCodetext { - Format = 4, // 4‑state Mailmark. + Format = format, VersionID = versionId, Class = classValue, SupplychainID = supplyChainId, ItemID = itemId, - DestinationPostCodePlusDPS = destination + DestinationPostCodePlusDPS = destination // preserve trailing space }; - // Generate the barcode using ComplexBarcodeGenerator. + // Generate the barcode and save it as a PNG file + string outputPath = Path.Combine(outputFolder, $"Mailmark_{i}.png"); 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}"); + generator.Save(outputPath, BarCodeImageFormat.Png); } + + Console.WriteLine($"Generated barcode for line {i + 1} -> {outputPath}"); } Console.WriteLine("Batch generation completed."); 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 e4c8fc2..6e3fd20 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,105 +1,88 @@ -// 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. +// Title: Batch read Mailmark barcodes from a directory and export results to CSV +// Description: Demonstrates how to generate sample Mailmark barcode images, read them in bulk, and write the decoded data to a CSV file. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation and recognition category. It showcases the use of ComplexBarcodeGenerator to create Mailmark symbols and BarCodeReader with DecodeType.Mailmark to decode them. Typical scenarios include bulk processing of Mailmark images for logistics, inventory tracking, or data extraction, where developers need to automate image generation, batch reading, and export of results to common formats like CSV. // 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 +// Tags: mailmark, barcode, batch-processing, csv, generation, recognition, aspose.barcode, complexbarcode using System; using System.IO; +using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates batch reading of Mailmark barcodes from a directory and exporting results to a CSV file. +/// Example program that generates sample Mailmark barcode images (if none exist), +/// reads all PNG images in a folder, decodes the Mailmark symbols, and writes the +/// results to a CSV file. /// class Program { /// - /// Entry point of the application. Scans a folder for supported image files, decodes Mailmark barcodes, - /// and writes the extracted information to a CSV file. + /// Entry point of the application. Performs image generation, batch decoding, + /// and CSV export. /// static void Main() { - // Input directory containing Mailmark barcode images. - string inputDir = "MailmarkImages"; + // Folder that holds Mailmark barcode images + string folderPath = "MailmarkImages"; - // Output CSV file path. - string outputCsv = "MailmarkResults.csv"; - - // Verify that the input directory exists. - if (!Directory.Exists(inputDir)) - { - Console.WriteLine($"Input directory does not exist: {inputDir}"); - return; - } - - // 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(); - - foreach (var file in imageFiles) + // Ensure the folder exists; create it if missing + if (!Directory.Exists(folderPath)) { - // 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); + Directory.CreateDirectory(folderPath); } - // If no supported image files were found, inform the user and exit. - if (filesToProcess.Count == 0) + // Generate sample Mailmark images when the folder is empty + string[] existingImages = Directory.GetFiles(folderPath, "*.png"); + if (existingImages.Length == 0) { - Console.WriteLine("No image files found to process."); - return; - } - - // 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"); - - // Process each image file individually. - foreach (var filePath in filesToProcess) + for (int i = 0; i < 5; i++) { - // Double‑check that the file still exists before attempting to read it. - if (!File.Exists(filePath)) + // Configure a valid MailmarkCodetext instance + var mailmark = new MailmarkCodetext { - Console.WriteLine($"File not found (skipped): {filePath}"); - continue; - } + Format = 4, // 4‑state Mailmark + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 1000 + i, // Unique ItemID per record + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space required + }; - try + // Generate the barcode image and save it as PNG + using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // 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(); + string imagePath = Path.Combine(folderPath, $"Mailmark_{i + 1}.png"); + generator.Save(imagePath); + } + } + } - // If no barcodes were detected, write an empty data line for this file. - if (results.Length == 0) - { - writer.WriteLine($"{Path.GetFileName(filePath)},,,," ); - continue; - } + // Path for the CSV output file + string csvPath = "MailmarkResults.csv"; - // 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) + // Write CSV header line + File.WriteAllText(csvPath, "FileName,CodeType,CodeText" + Environment.NewLine); + + // Process each PNG image in the folder + string[] pngFiles = Directory.GetFiles(folderPath, "*.png"); + foreach (string imageFile in pngFiles) + { + if (!File.Exists(imageFile)) + continue; + + // Initialize a reader for the Mailmark symbology + using (var reader = new BarCodeReader(imageFile, DecodeType.Mailmark)) + { + // Read all barcodes found in the image + foreach (var result in reader.ReadBarCodes()) { - // 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,,," ); + // Append decoded information as a CSV line + string csvLine = $"{Path.GetFileName(imageFile)},{result.CodeTypeName},{result.CodeText}"; + File.AppendAllText(csvPath, csvLine + Environment.NewLine); } } } - // Inform the user that processing has completed. - Console.WriteLine($"Processing complete. Results saved to {outputCsv}"); + Console.WriteLine($"Decoding completed. Results saved to {csvPath}"); } } \ 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 3cb2863..49200d7 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,99 +1,139 @@ -// Title: In-Memory Barcode Image Caching Example -// 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. +// Title: Barcode Image Caching with Aspose.BarCode +// Description: Demonstrates caching of generated PNG barcode images in memory to prevent redundant regeneration for identical barcode parameters. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, BarcodeCacheKey, and a simple in‑memory Dictionary cache. Developers often need to generate many barcodes with repeated settings, and caching improves performance and reduces CPU load. The pattern is useful for web services, batch processing, or any application that repeatedly renders the same barcodes. // Prompt: Cache generated barcode images in memory to avoid redundant regeneration for identical field sets. -// Tags: barcode, caching, memory, code128, qr, datamatrix, generation, aspnet, aspose.barcode +// Tags: barcode, symbology, caching, png, aspose.barcode, generation, memory cache using System; using System.Collections.Generic; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; -/// -/// Provides an in‑memory cache for barcode images generated with Aspose.BarCode. -/// -class BarcodeCache +namespace BarcodeCacheDemo { - // Internal dictionary that maps a unique key (encode type + text) to the generated PNG bytes. - private static readonly Dictionary _cache = new Dictionary(); - /// - /// Retrieves a cached barcode image or generates a new one if it does not exist. + /// Represents a unique set of barcode generation parameters. + /// For simplicity only symbology type and code text are considered. + /// Extend this class with additional properties (e.g., XDimension, colors) as needed. /// - /// 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) + class BarcodeCacheKey : IEquatable { - // 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}"; + public BaseEncodeType EncodeType { get; } + public string CodeText { get; } - // Return the cached image if it already exists. - if (_cache.TryGetValue(key, out byte[] cachedData)) + public BarcodeCacheKey(BaseEncodeType encodeType, string codeText) { - Console.WriteLine($"Cache hit for [{encodeType}] \"{codeText}\""); - return cachedData; + EncodeType = encodeType; + CodeText = codeText ?? string.Empty; } - // Cache miss – generate a new barcode image. - Console.WriteLine($"Generating barcode for [{encodeType}] \"{codeText}\""); - using (var generator = new BarcodeGenerator(encodeType, codeText)) + public bool Equals(BarcodeCacheKey other) { - // Example: set a higher resolution for better image quality. - generator.Parameters.Resolution = 300; + if (other is null) return false; + return EncodeType.Equals(other.EncodeType) && CodeText == other.CodeText; + } - using (var ms = new MemoryStream()) - { - // Save the barcode to the memory stream in PNG format. - generator.Save(ms, BarCodeImageFormat.Png); - byte[] data = ms.ToArray(); + public override bool Equals(object obj) => Equals(obj as BarcodeCacheKey); - // Store the generated image in the cache for future requests. - _cache[key] = data; - return data; + public override int GetHashCode() + { + unchecked + { + int hash = 17; + hash = hash * 31 + EncodeType.GetHashCode(); + hash = hash * 31 + CodeText.GetHashCode(); + return hash; } } } -} -/// -/// Demonstrates the use of to generate and cache barcode images. -/// -class Program -{ /// - /// 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. + /// Simple in‑memory cache for barcode PNG bytes keyed by . /// - static void Main() + class BarcodeCache { - // Define a list of barcode generation requests; duplicates test the cache. - var requests = new List<(BaseEncodeType type, string text)> - { - (EncodeTypes.Code128, "ABC123"), - (EncodeTypes.QR, "https://example.com"), - (EncodeTypes.Code128, "ABC123"), // duplicate - (EncodeTypes.DataMatrix, "DataMatrixSample"), - (EncodeTypes.QR, "https://example.com") // duplicate - }; - - int index = 1; - foreach (var (type, text) in requests) + // Cache stores the generated PNG bytes keyed by barcode parameters. + private readonly Dictionary _cache = new Dictionary(); + + /// + /// Returns PNG image bytes for the requested barcode, using the cache when possible. + /// + /// The barcode symbology. + /// The data to encode. + /// Byte array containing the PNG image. + public byte[] GetBarcodeImage(BaseEncodeType encodeType, string codeText) { - // Retrieve the barcode image, using the cache when possible. - byte[] imageData = BarcodeCache.GetOrCreate(type, text); + var key = new BarcodeCacheKey(encodeType, codeText); + if (_cache.TryGetValue(key, out var imageBytes)) + { + // Cache hit – return existing image. + Console.WriteLine($"Cache hit for type {encodeType} and text \"{codeText}\"."); + return imageBytes; + } - // Construct a file name that includes the request order and barcode type. - string fileName = $"barcode_{index}_{type}.png"; + // Cache miss – generate a new barcode image. + Console.WriteLine($"Generating barcode for type {encodeType} and text \"{codeText}\"."); + using (var generator = new BarcodeGenerator(encodeType, codeText)) + { + // Example of setting some common parameters. + generator.Parameters.Barcode.XDimension.Point = 2f; // module size + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + generator.Parameters.Resolution = 300; // DPI - // Write the PNG bytes to disk. - File.WriteAllBytes(fileName, imageData); - Console.WriteLine($"Saved barcode to {fileName}"); - index++; + using (var ms = new MemoryStream()) + { + generator.Save(ms, BarCodeImageFormat.Png); + imageBytes = ms.ToArray(); + } + } + + // Store the generated image in the cache for future reuse. + _cache[key] = imageBytes; + return imageBytes; } + } - Console.WriteLine("Processing completed."); + /// + /// Demonstrates barcode generation with caching and saves the resulting PNG files. + /// + class Program + { + /// + /// Entry point that demonstrates barcode caching and saves PNG files. + /// + static void Main() + { + var cache = new BarcodeCache(); + + // Sample data: some barcodes are duplicated to demonstrate caching. + var samples = new (BaseEncodeType type, string text)[] + { + (EncodeTypes.Code128, "ABC123"), + (EncodeTypes.QR, "https://example.com"), + (EncodeTypes.Code128, "ABC123"), // duplicate + (EncodeTypes.DataMatrix, "DataMatrixSample"), + (EncodeTypes.QR, "https://example.com") // duplicate + }; + + // Generate images and write them to files. + for (int i = 0; i < samples.Length; i++) + { + var (type, text) = samples[i]; + byte[] pngBytes = cache.GetBarcodeImage(type, text); + + string fileName = $"barcode_{i + 1}.png"; + using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) + { + fileStream.Write(pngBytes, 0, pngBytes.Length); + } + + Console.WriteLine($"Saved {fileName}"); + } + + // Program ends – no waiting for user input. + } } } \ 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 0694064..88f7680 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,8 +1,8 @@ -// 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. +// Title: Compare Mailmark Type 7 and Type 29 barcode generation performance +// Description: Demonstrates generating Mailmark 2‑D barcodes of type 7 and type 29, measuring the time taken and the resulting PNG image size. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex 2‑D symbologies such as Mailmark. It shows how to configure Mailmark2DCodetext, use ComplexBarcodeGenerator, and evaluate performance metrics—common tasks for developers creating high‑volume mailing solutions or optimizing barcode rendering. // 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 +// Tags: mailmark, barcode, generation, performance, png, aspose.barcode, complexbarcode using System; using System.Diagnostics; @@ -12,110 +12,82 @@ using Aspose.BarCode.ComplexBarcode; /// -/// 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. +/// Generates Mailmark type 7 and type 29 barcodes, measures generation time, +/// and reports the PNG image sizes. Useful for performance comparison of different +/// Mailmark module configurations. /// class Program { /// - /// Prepares common Mailmark fields and invokes the comparison for both matrix types. + /// Entry point of the example. Prepares Mailmark data, creates two barcode variants, + /// measures their generation times and output sizes, and writes the results to the console. /// static void Main() { - // Common Mailmark2D fields shared by both barcode types + // Prepare common Mailmark2D data (shared between both barcode types) + const string destinationPostCode = "EF61AH8T "; // trailing space required by the specification 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 "; + const string mailClass = "0"; + const int supplyChainId = 384224; + const int itemId = 16563762; - // Compare Type 7 (24x24) and Type 29 (16x48) matrix configurations - CompareMailmark2D( - Mailmark2DType.Type_7, - "Type 7 (24x24)", - versionId, - informationTypeId, - classCode, - rtsFlag, - supplyChainId, - itemId, - destinationPostCodePlusDps); - - CompareMailmark2D( - Mailmark2DType.Type_29, - "Type 29 (16x48)", - versionId, - informationTypeId, - classCode, - rtsFlag, - supplyChainId, - itemId, - destinationPostCodePlusDps); - } + // Configure Mailmark type 7 (24x24 modules) + var mailmark7 = new Mailmark2DCodetext + { + VersionID = versionId, + InformationTypeID = informationTypeId, + Class = mailClass, + SupplyChainID = supplyChainId, + ItemID = itemId, + DestinationPostCodeAndDPS = destinationPostCode, + DataMatrixType = Mailmark2DType.Type_7 + }; - /// - /// 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 + // Configure Mailmark type 29 (16x48 modules) + var mailmark29 = new Mailmark2DCodetext { VersionID = versionId, InformationTypeID = informationTypeId, - Class = classCode, - RTSFlag = rtsFlag, + Class = mailClass, SupplyChainID = supplyChainId, ItemID = itemId, - DestinationPostCodeAndDPS = destinationPostCodePlusDps, - DataMatrixType = matrixType + DestinationPostCodeAndDPS = destinationPostCode, + DataMatrixType = Mailmark2DType.Type_29 }; - // Start timing the barcode generation process + // Measure generation time and image size for Type 7 var stopwatch = new Stopwatch(); + long size7; stopwatch.Start(); - - // Generate the barcode using ComplexBarcodeGenerator - using (var generator = new ComplexBarcodeGenerator(mailmark)) + using (var generator7 = new ComplexBarcodeGenerator(mailmark7)) { - // Explicitly set auto‑size mode to interpolation (default, but clarified) - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - - // Save the barcode to a memory stream in PNG format - using (var ms = new MemoryStream()) + using (var ms7 = new MemoryStream()) { - generator.Save(ms, BarCodeImageFormat.Png); - stopwatch.Stop(); // Stop timing after the image is saved - - long imageSize = ms.Length; // Size in bytes of the generated PNG + generator7.Save(ms7, BarCodeImageFormat.Png); + size7 = ms7.Length; // capture PNG byte length + } + } + stopwatch.Stop(); + long time7 = stopwatch.ElapsedMilliseconds; - // Output the results to the console - Console.WriteLine($"{label}:"); - Console.WriteLine($" Generation time: {stopwatch.ElapsedMilliseconds} ms"); - Console.WriteLine($" Image size: {imageSize} bytes"); - Console.WriteLine(); + // Measure generation time and image size for Type 29 + stopwatch.Reset(); + long size29; + stopwatch.Start(); + using (var generator29 = new ComplexBarcodeGenerator(mailmark29)) + { + using (var ms29 = new MemoryStream()) + { + generator29.Save(ms29, BarCodeImageFormat.Png); + size29 = ms29.Length; // capture PNG byte length } } + stopwatch.Stop(); + long time29 = stopwatch.ElapsedMilliseconds; + + // Output the performance results + Console.WriteLine($"Mailmark Type 7: Generation time = {time7} ms, Image size = {size7} bytes"); + Console.WriteLine($"Mailmark Type 29: Generation time = {time29} ms, Image size = {size29} bytes"); } } \ 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 2c4012c..28f1c21 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,25 +1,29 @@ -// 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. +// Title: Generate Swiss QR Code as 300 dpi PNG with Custom Dimensions +// Description: Demonstrates creating a Swiss QR (QR‑Bill) barcode using Aspose.BarCode, configuring 300 dpi resolution and custom image size, then saving it as a PNG for printing. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator together with SwissQRCodetext to produce payment‑oriented QR codes. Developers commonly need to adjust resolution and image dimensions for high‑quality print output, making this pattern useful for invoicing, billing, and other financial document workflows. // 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 +// Tags: swissqr, generation, png, complexbarcodegenerator, swissqrcodetext using System; +using System.IO; +using Aspose.BarCode; using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Example program that generates a Swiss QR Bill barcode with custom DPI and image size. +/// Example program that generates a Swiss QR (QR‑Bill) barcode, +/// sets a 300 dpi resolution and custom image dimensions, +/// and saves the result as a PNG file. /// class Program { /// - /// Entry point. Builds the Swiss QR codetext, configures the generator, and saves a PNG image. + /// Entry point of the example. Builds the QR‑Bill data, + /// configures the generator, and writes the PNG image to disk. /// static void Main() { - // Prepare SwissQR codetext with mandatory fields + // Prepare Swiss QR codetext (complex barcode data) with creditor information and payment details. var swissQr = new SwissQRCodetext(); swissQr.Bill.Creditor.Name = "John Doe"; swissQr.Bill.Creditor.CountryCode = "CH"; @@ -27,24 +31,21 @@ static void Main() swissQr.Bill.Amount = 199.95m; swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; - // Create ComplexBarcodeGenerator using the codetext + // Create a ComplexBarcodeGenerator using the prepared Swiss QR codetext. using (var generator = new ComplexBarcodeGenerator(swissQr)) { - // Set image resolution to 300 dpi for high‑quality printing + // Set the image resolution to 300 dots per inch for high‑quality printing. generator.Parameters.Resolution = 300f; - // 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 + // Define custom image dimensions in points (e.g., 600 × 400 points). + generator.Parameters.ImageWidth.Point = 600f; + generator.Parameters.ImageHeight.Point = 400f; - // Optional: set background and barcode colors - generator.Parameters.BackColor = Color.White; - generator.Parameters.Barcode.BarColor = Color.Black; - - // Save the barcode as a PNG file - generator.Save("SwissQR.png"); + // Save the generated barcode as a PNG file. + generator.Save("SwissQR_300dpi.png"); } - Console.WriteLine("Barcode image generated: SwissQR.png"); + // Inform the user that the image has been created. + Console.WriteLine("Barcode image generated: SwissQR_300dpi.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 6cedfc8..3bdea3e 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,27 +1,25 @@ -// 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. +// Title: Generate Swiss QR Code with Custom Module Size +// Description: Demonstrates creating a Swiss QR bill barcode using Aspose.BarCode and configuring a smaller XDimension for higher density output. +// Category-Description: This example belongs to the Aspose.BarCode ComplexBarcode generation category, showcasing how to work with the ComplexBarcodeGenerator class to produce Swiss QR bill barcodes. Typical use cases include generating payment QR codes for invoices and financial documents, where developers often need to adjust barcode density, format, and visual parameters. The example highlights key API classes such as SwissQRCodetext, ComplexBarcodeGenerator, and BarCodeImageFormat, providing a reference for developers seeking to customize barcode appearance and export options. // 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 +// Tags: swissqr, barcode, complexbarcode, xdimension, png, aspose.barcode using System; using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; -using Aspose.Drawing; +using Aspose.BarCode.Generation; /// -/// Demonstrates configuring a ComplexBarcodeGenerator to use a specific module size for higher density Swiss QR barcodes. +/// Example program that generates a Swiss QR bill barcode with a custom module size (XDimension) for higher density. /// class Program { /// - /// Entry point of the example. Generates a Swiss QR code with a reduced XDimension for higher density and saves it as an image. + /// Entry point of the application. Builds the Swiss QR codetext, configures the generator, and saves the barcode as a PNG image. /// static void Main() { - // Prepare SwissQR codetext with required fields + // Initialize Swiss QR codetext with required billing fields var swissQr = new SwissQRCodetext(); swissQr.Bill.Creditor.Name = "John Doe"; swissQr.Bill.Creditor.CountryCode = "CH"; @@ -29,19 +27,18 @@ static void Main() swissQr.Bill.Amount = 199.95m; swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; - // Create ComplexBarcodeGenerator with the codetext + // Create a ComplexBarcodeGenerator instance using the prepared codetext using (var generator = new ComplexBarcodeGenerator(swissQr)) { - // Set a smaller module size (higher density) using XDimension + // Adjust the module size (XDimension) to 0.5 points for higher barcode density generator.Parameters.Barcode.XDimension.Point = 0.5f; - // Optional: set image resolution - generator.Parameters.Resolution = 300; + // Define output file name and save the generated barcode as a PNG image + string outputFile = "SwissQR.png"; + generator.Save(outputFile, BarCodeImageFormat.Png); - // Save the generated barcode image - string outputPath = "SwissQR_HighDensity.png"; - generator.Save(outputPath); - Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}"); + // Output the full path of the saved image for verification + Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputFile)}"); } } } \ 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 d7d1760..fc7319e 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,56 +1,62 @@ -// 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. +// Title: Generate Mailmark Barcode and Save as PNG +// Description: Creates a Mailmark barcode using provided or default values and saves it as a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It demonstrates how to use the MailmarkCodetext class with ComplexBarcodeGenerator to produce a Mailmark symbology barcode, a common requirement for postal and logistics applications. Developers often need to customize fields such as format, version, class, and supply‑chain identifiers, then export the result to an image format like PNG. // 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 +// Tags: mailmark, barcode, generation, png, aspose.barcode, complexbarcode, console using System; using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; /// -/// Console application that creates a Mailmark 4‑state barcode from user‑provided data -/// and saves the result as a PNG file. +/// Demonstrates generating a Mailmark barcode and saving it as a PNG image. /// class Program { /// - /// 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. + /// Entry point. Parses optional command‑line arguments, builds the Mailmark codetext, + /// generates the barcode and writes it to disk. /// - /// Optional arguments: format versionId class supplyChainId itemId destinationPostCodePlusDps + /// + /// Command‑line arguments in the following order: + /// format versionId class supplyChainId itemId destinationPostCodePlusDps + /// static void Main(string[] args) { - // Default sample values for Mailmark 4‑state barcode - int format = 4; // 4 = unspecified/default + // Default Mailmark values (valid sample) + int format = 4; // 4‑state Mailmark int versionId = 1; - string classValue = "0"; // "0" – Null or Test + string classValue = "0"; int supplyChainId = 384224; int itemId = 16563762; string destinationPostCodePlusDps = "EF61AH8T "; - // If command‑line arguments are provided, try to parse them. + // Parse command‑line arguments if provided // Expected order: format versionId class supplyChainId itemId destinationPostCodePlusDps - if (args.Length >= 6) + try { - 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]; - } + if (args.Length >= 6) + { + format = int.Parse(args[0]); + versionId = int.Parse(args[1]); + classValue = args[2]; + supplyChainId = int.Parse(args[3]); + itemId = int.Parse(args[4]); + destinationPostCodePlusDps = args[5]; - // Validate that the destination postcode plus DPS is not empty. - if (string.IsNullOrWhiteSpace(destinationPostCodePlusDps)) + // Ensure the required trailing space is present + if (!destinationPostCodePlusDps.EndsWith(" ")) + destinationPostCodePlusDps += " "; + } + } + catch (Exception ex) { - Console.WriteLine("Invalid DestinationPostCodePlusDPS. Using default value."); - destinationPostCodePlusDps = "EF61AH8T "; + Console.WriteLine($"Argument parsing error: {ex.Message}"); + Console.WriteLine("Using default Mailmark values."); } - // Create and populate the MailmarkCodetext object. + // Construct MailmarkCodetext with the collected values var mailmark = new MailmarkCodetext { Format = format, @@ -61,14 +67,19 @@ static void Main(string[] args) DestinationPostCodePlusDPS = destinationPostCodePlusDps }; - // Generate the barcode and save it as PNG. - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "mailmark.png"); - using (var generator = new ComplexBarcodeGenerator(mailmark)) + // Generate the barcode and save it as a PNG file + try { - // Save directly to file in PNG format. - generator.Save(outputPath, BarCodeImageFormat.Png); + using (var generator = new ComplexBarcodeGenerator(mailmark)) + { + string outputPath = "mailmark.png"; + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Mailmark barcode saved to '{Path.GetFullPath(outputPath)}'."); + } + } + catch (Exception ex) + { + Console.WriteLine($"Failed to generate Mailmark barcode: {ex.Message}"); } - - 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 1dfca33..89d38fb 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,56 +1,64 @@ -// 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. +// Title: Generate Mailmark 2D barcode with routing, service, and customer data +// Description: Demonstrates creating a Mailmark2DCodetext, assigning routing, service class, and custom content, then generating a Mailmark 2D barcode image. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the Mailmark2DCodetext class, which is used to build Mailmark 2‑D barcodes for postal services. Typical use cases include setting routing information, service class, and customer‑specific data before rendering the barcode as an image. Developers working with postal automation or logistics often need to generate such barcodes programmatically. // Prompt: Create a Mailmark2DCodetext instance and assign routing, service, and customer data values. -// Tags: mailmark, 2d, barcode, generation, png, aspose.barcode, complexbarcode, codetext, dataencoding +// Tags: mailmark, 2d, barcode, complexbarcode, generation, aspose.barcode using System; -using System.IO; +using Aspose.BarCode; using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; /// -/// Example program that builds a Mailmark 2D barcode by populating routing, -/// service, and customer data fields, then saves the result as a PNG image. +/// Example program that builds a Mailmark 2‑D barcode by populating routing, +/// service, and customer data fields, then saves the barcode as a PNG image. /// class Program { /// - /// Entry point of the example. Creates a Mailmark2DCodetext, sets required - /// properties, generates the barcode, and writes it to disk. + /// Entry point of the example. Creates a Mailmark2DCodetext, configures its + /// required fields, generates the barcode, and writes the output file name + /// to the console. /// static void Main() { - // Instantiate a Mailmark2DCodetext object to hold barcode data. + // Instantiate a Mailmark2DCodetext object which holds all barcode data. var mailmark2d = new Mailmark2DCodetext(); - // Set routing information: destination postcode plus DPS (trailing space required). - mailmark2d.DestinationPostCodeAndDPS = "EF61AH8T "; + // ------------------------------------------------------------ + // Required routing and service information + // ------------------------------------------------------------ + mailmark2d.VersionID = "1"; // Version identifier (single character) + mailmark2d.InformationTypeID = "0"; // Routing information (Information Type ID) + mailmark2d.Class = "1"; // Service class identifier + mailmark2d.RTSFlag = "0"; // Return‑to‑sender flag - // 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 + // ------------------------------------------------------------ + // Additional mandatory fields (sample values) + // ------------------------------------------------------------ + mailmark2d.SupplyChainID = 384224; // Supply chain identifier + mailmark2d.ItemID = 16563762; // Unique item identifier + mailmark2d.DestinationPostCodeAndDPS = "EF61AH8T "; // Destination postcode + DPS (trailing space required) + mailmark2d.ReturnToSenderPostCode = "SW1A1AA"; // Return‑to‑sender postcode (no DPS) + mailmark2d.UPUCountryID = "GB"; // UPU country identifier - // Set customer-specific data and its encoding mode. - mailmark2d.CustomerContent = "CUSTOMER123"; - mailmark2d.CustomerContentEncodeMode = DataMatrixEncodeMode.C40; + // ------------------------------------------------------------ + // Customer‑specific content + // ------------------------------------------------------------ + mailmark2d.CustomerContent = "CUSTOMER DATA"; + mailmark2d.CustomerContentEncodeMode = DataMatrixEncodeMode.C40; // Encode mode for the customer content - // Populate additional required fields with sample values. - mailmark2d.SupplyChainID = 384224; - mailmark2d.ItemID = 16563762; - mailmark2d.UPUCountryID = "GB"; + // Optional: specify DataMatrix type (default is sufficient for most scenarios) + // mailmark2d.DataMatrixType = DataMatrixType.DataMatrix; // Uncomment if needed and enum exists - // Use ComplexBarcodeGenerator to create the barcode based on the codetext. + // ------------------------------------------------------------ + // Generate the barcode and save it as a PNG file + // ------------------------------------------------------------ using (var generator = new ComplexBarcodeGenerator(mailmark2d)) { - // Define output file path and save the barcode as a PNG image. - const string outputPath = "mailmark2d.png"; - generator.Save(outputPath, BarCodeImageFormat.Png); - - // Inform the user where the file was saved. - Console.WriteLine($"Mailmark 2D barcode saved to {Path.GetFullPath(outputPath)}"); + generator.Save("Mailmark2D.png"); } + + Console.WriteLine("Mailmark 2D barcode generated: Mailmark2D.png"); } } \ 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 317e6ab..3260ea3 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,59 +1,57 @@ -// 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. +// Title: Generate Mailmark 2D Barcode from JSON +// Description: Demonstrates deserializing a Mailmark2DCodetext JSON payload and creating a Mailmark 2D barcode image using Aspose.BarCode. +// 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 symbols, a common requirement for postal and logistics applications. Developers often need to convert structured data (e.g., JSON) into barcode images for printing or electronic transmission. // Prompt: Deserialize JSON back into a Mailmark2DCodetext instance and generate the corresponding barcode. -// Tags: mailmark,2d barcode,serialization,deserialization,aspose.barcode,generation,json +// Tags: mailmark, 2d barcode, json deserialization, aspose.barcode, complexbarcode, png, generation using System; using System.IO; using System.Text.Json; -using System.Text.Json.Serialization; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; -using Aspose.Drawing; +using Aspose.BarCode.Generation; /// -/// Example program that deserializes a Mailmark2DCodetext JSON string +/// Example program that deserializes a Mailmark2DCodetext object from JSON /// and generates a Mailmark 2D barcode image using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Performs JSON deserialization, - /// creates a ComplexBarcodeGenerator, and saves the barcode image. + /// Entry point of the example. Performs JSON deserialization and barcode generation. /// static void Main() { - // Sample JSON representing a Mailmark2DCodetext. + // -------------------------------------------------------------------- + // 1. Define a JSON string that represents a Mailmark2DCodetext instance. + // Adjust the values as needed for your specific scenario. + // -------------------------------------------------------------------- string json = @"{ - ""Class"": ""1"", - ""CustomerContent"": ""SampleCustomer"", - ""CustomerContentEncodeMode"": ""C40"", - ""DestinationPostCodeAndDPS"": ""EF61AH8T "", + ""VersionID"": ""1"", ""InformationTypeID"": ""0"", - ""ItemID"": 16563762, - ""ReturnToSenderPostCode"": ""SW1A1AA"", + ""Class"": ""1"", ""RTSFlag"": ""0"", + ""ItemID"": 16563762, ""SupplyChainID"": 384224, + ""DestinationPostCodeAndDPS"": ""EF61AH8T "", ""UPUCountryID"": ""GB"", - ""VersionID"": ""1"" + ""CustomerContent"": ""SampleCustomerData"", + ""CustomerContentEncodeMode"": 0, + ""DataMatrixType"": 0 }"; - // 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. + // -------------------------------------------------------------------- + // 2. Deserialize the JSON into a Mailmark2DCodetext object. + // Handle possible errors and null results gracefully. + // -------------------------------------------------------------------- Mailmark2DCodetext mailmark; try { - mailmark = JsonSerializer.Deserialize(json, options); + mailmark = JsonSerializer.Deserialize(json); if (mailmark == null) - throw new InvalidOperationException("Deserialization returned null."); + { + Console.WriteLine("Deserialization returned null."); + return; + } } catch (Exception ex) { @@ -61,20 +59,17 @@ static void Main() return; } - // Define the output file path for the generated barcode image. - string outputPath = "mailmark2d.png"; - - // Generate the Mailmark 2D barcode using ComplexBarcodeGenerator. + // -------------------------------------------------------------------- + // 3. Generate the Mailmark 2D barcode using ComplexBarcodeGenerator. + // The barcode is saved as a PNG image to the specified path. + // -------------------------------------------------------------------- + const string outputPath = "mailmark2d.png"; try { using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // 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); + // Save the barcode image as PNG. + generator.Save(outputPath, BarCodeImageFormat.Png); } Console.WriteLine($"Barcode generated and saved to '{Path.GetFullPath(outputPath)}'."); 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 9e05cd6..662775c 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,81 +1,100 @@ -// 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. +// Title: Generate Mailmark 4‑state barcode and save as PNG +// Description: Demonstrates creating a Mailmark 4‑state barcode using Aspose.BarCode and returning it as a PNG stream. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, showcasing the MailmarkCodetext class and ComplexBarcodeGenerator. Developers use these APIs to produce postal Mailmark barcodes for logistics, tracking, and automated mail processing. Typical use cases include generating barcode images for printing on envelopes or integrating with mailing software. // 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 +// Tags: mailmark, barcode, complex barcode, png, stream, aspose.barcode, generation using System; using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; -/// -/// Provides an example of generating a Mailmark barcode and saving it as an image file. -/// -class Program +namespace MailmarkBarcodeHelper { - // 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) + /// + /// Provides a console entry point that demonstrates generating a Mailmark 4‑state barcode + /// and saving the resulting PNG image to disk. + /// + class Program { - // 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)); - - // Populate the MailmarkCodetext object with the mandatory fields. - var mailmark = new MailmarkCodetext + /// + /// Entry point of the example. Creates sample Mailmark data, generates the barcode, + /// and writes the PNG image to a file named mailmark.png. + /// + static void Main() { - 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 " - }; + // Sample Mailmark data (valid example) + int format = 4; // Mailmark 4‑state format identifier + int versionId = 1; // Version identifier + string @class = "0"; // Class must be a string (e.g., "0") + int supplychainId = 384224; // Supply‑chain identifier + int itemId = 16563762; // Item identifier (max 99 999 999) + string destinationPostCodePlusDPS = "EF61AH8T "; // Destination postcode plus DPS; trailing space is required - // Generate the barcode image into a memory stream. - var stream = new MemoryStream(); - using (var generator = new ComplexBarcodeGenerator(mailmark)) - { - generator.Save(stream, BarCodeImageFormat.Png); + // Generate the barcode image stream using the helper method + using (MemoryStream barcodeStream = GenerateMailmarkBarcode( + format, versionId, @class, supplychainId, itemId, destinationPostCodePlusDPS)) + { + // Save the stream to a PNG file for verification + using (FileStream file = new FileStream("mailmark.png", FileMode.Create, FileAccess.Write)) + { + barcodeStream.CopyTo(file); + } + + Console.WriteLine("Mailmark barcode generated and saved as 'mailmark.png'."); + } } - // Reset stream position for callers. - stream.Position = 0; - return stream; - } + /// + /// Generates a Mailmark 4‑state barcode image and returns it as a PNG . + /// + /// Mailmark format (must be 4 for 4‑state barcodes). + /// Version identifier (e.g., 1). + /// Class string (e.g., "0"). + /// Supply chain identifier. + /// Item identifier (max 99 999 999). + /// Destination postcode plus DPS (must include trailing space). + /// A containing the PNG image of the generated barcode. + /// Thrown when required parameters are missing or invalid. + public static MemoryStream GenerateMailmarkBarcode( + int format, + int versionId, + string @class, + int supplychainId, + int itemId, + string destinationPostCodePlusDPS) + { + // Basic validation of input parameters + if (format != 4) + throw new ArgumentException("Mailmark 4‑state barcode requires format = 4.", nameof(format)); - /// - /// 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 "; + if (string.IsNullOrEmpty(@class)) + throw new ArgumentException("Class cannot be null or empty.", nameof(@class)); - // 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"); + if (string.IsNullOrEmpty(destinationPostCodePlusDPS) || destinationPostCodePlusDPS.Length < 9) + throw new ArgumentException("DestinationPostCodePlusDPS must be a valid postcode string (including trailing spaces).", nameof(destinationPostCodePlusDPS)); + + // Construct the Mailmark codetext object with supplied fields + var mailmark = new MailmarkCodetext + { + Format = format, + VersionID = versionId, + Class = @class, + SupplychainID = supplychainId, + ItemID = itemId, + DestinationPostCodePlusDPS = destinationPostCodePlusDPS + }; - // Save to a file named "mailmark.png" in the current directory. - using (FileStream file = new FileStream("mailmark.png", FileMode.Create, FileAccess.Write)) + // Generate the barcode using ComplexBarcodeGenerator and write to a memory stream + var memoryStream = new MemoryStream(); + using (var generator = new ComplexBarcodeGenerator(mailmark)) { - barcodeStream.CopyTo(file); + generator.Save(memoryStream, BarCodeImageFormat.Png); } - Console.WriteLine("Barcode image saved as 'mailmark.png'."); + // Reset stream position so callers can read from the beginning + memoryStream.Position = 0; + return memoryStream; } } } \ 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 e589653..242ab7e 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,60 +1,92 @@ -// 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. +// Title: DataMatrix Barcode Encoding Comparison – Default vs UTF-8 +// Description: Demonstrates generating a DataMatrix barcode with the default automatic encoding and with an explicit UTF‑8 encoding, then compares image dimensions to assess capacity impact. +// Category-Description: This example belongs to the Aspose.BarCode encoding and capacity assessment category. It showcases the use of BarcodeGenerator, EncodeTypes, and image handling classes (Bitmap, BarCodeImageFormat) to create barcodes, control text encoding, and evaluate how encoding choices affect barcode size. Developers often need to understand encoding effects when optimizing barcode data density for packaging, inventory, or document workflows. // Prompt: Encode customer information with an alternative encoding and assess its impact on barcode capacity. -// Tags: qr, encoding, capacity, aspose.barcode, generation +// Tags: datamatrix, barcode, encoding, capacity, aspose.barcode, image, png, c# using System; +using System.IO; using System.Text; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// 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. +/// Example program that creates DataMatrix barcodes using default and explicit UTF‑8 encoding +/// and compares their image sizes to evaluate encoding impact on barcode capacity. /// class Program { /// - /// Entry point of the example. Creates two QR codes with different text encodings and prints capacity analysis. + /// Entry point. Generates two barcodes, saves them, and prints a size comparison. /// static void Main() { // Sample customer information to encode - string customerInfo = "John Doe 12345"; + string customerInfo = "John Doe, 123 Main St, City, Country"; - // File paths for the generated barcode images - string defaultPath = "qr_default.png"; - string utf8Path = "qr_utf8.png"; + // File paths for the generated PNG images + string defaultPath = "customer_default.png"; + string altPath = "customer_alt.png"; - // Generate QR code using the default encoding (Unicode/UTF-16 internal representation) - using (var generator = new BarcodeGenerator(EncodeTypes.QR)) + // ------------------------------------------------------------ + // Generate barcode using the default (auto‑detected) encoding + // ------------------------------------------------------------ + int defaultWidth, defaultHeight; + using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, customerInfo)) { - generator.CodeText = customerInfo; // Assign text with default encoding - generator.Save(defaultPath); // Save image to file + // Save the barcode image to a PNG file + generator.Save(defaultPath, BarCodeImageFormat.Png); + + // Retrieve the image dimensions for capacity comparison + using (Bitmap bmp = generator.GenerateBarCodeImage()) + { + defaultWidth = bmp.Width; + defaultHeight = bmp.Height; + } } - // Generate QR code using an alternative UTF-8 encoding via SetCodeText - using (var generatorUtf8 = new BarcodeGenerator(EncodeTypes.QR)) + // ------------------------------------------------------------ + // Generate barcode using an explicit UTF‑8 encoding via SetCodeText + // ------------------------------------------------------------ + int altWidth, altHeight; + using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix)) { - generatorUtf8.SetCodeText(customerInfo, Encoding.UTF8); // Explicit UTF-8 encoding - generatorUtf8.Save(utf8Path); // Save image to file + // Encode the same text with explicit UTF‑8 encoding + generator.SetCodeText(customerInfo, Encoding.UTF8); + + // Save the barcode image to a PNG file + generator.Save(altPath, BarCodeImageFormat.Png); + + // Retrieve the image dimensions for capacity comparison + using (Bitmap bmp = generator.GenerateBarCodeImage()) + { + altWidth = bmp.Width; + altHeight = bmp.Height; + } } - // 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 + // ------------------------------------------------------------ + // Output comparison results to the console + // ------------------------------------------------------------ + Console.WriteLine("Barcode capacity assessment (image size reflects data capacity):"); + Console.WriteLine($"Default encoding (auto): {defaultWidth}x{defaultHeight} pixels"); + Console.WriteLine($"Alternative UTF-8 encoding: {altWidth}x{altHeight} pixels"); + 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.")); + if (defaultWidth == altWidth && defaultHeight == altHeight) + { + Console.WriteLine("Both encodings produced identical image sizes; capacity impact is negligible."); + } + else + { + Console.WriteLine("Different image sizes indicate a capacity impact due to encoding differences."); + Console.WriteLine("Larger dimensions mean more modules were needed, reducing effective 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); + Console.WriteLine($"Default barcode saved to: {Path.GetFullPath(defaultPath)}"); + Console.WriteLine($"Alternative barcode saved to: {Path.GetFullPath(altPath)}"); } } \ 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 f17cfc9..2d5a469 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,59 +1,48 @@ // 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# +// Description: Demonstrates constructing a Mailmark2D codetext, decoding it with Aspose.BarCode, and extracting individual fields such as routing and service codes. +// Category-Description: This example belongs to the Aspose.BarCode ComplexBarcode category, showcasing the Mailmark2D symbology. It uses the Mailmark2DCodetext class to build a codetext string, ComplexCodetextReader to decode it, and then accesses the parsed properties. Developers working with postal automation, logistics, or any scenario that requires reading Mailmark2D barcodes will find this pattern useful for extracting routing, service, and custom data from decoded objects. +/// Prompt: Extract individual fields such as routing and service code from the decoded Mailmark2DCodetext. +/// Tags: mailmark2d, barcode, decoding, extraction, aspose.barcode, complexbarcode, csharp using System; -using System.IO; using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that creates a Mailmark2D barcode, decodes it, and extracts its individual data fields. +/// Sample program that builds a Mailmark2D codetext, decodes it, and prints each field. /// class Program { /// - /// Entry point of the example. Performs the full lifecycle: construct codetext, generate barcode, decode, and display fields. + /// Entry point of the example. Constructs a Mailmark2D codetext, decodes it, and displays the individual components. /// static void Main() { // ------------------------------------------------------------ - // 1. Create a Mailmark2D codetext object and populate its fields. + // 1. Create a Mailmark2DCodetext instance with known sample values. // ------------------------------------------------------------ - var mailmark2d = new Mailmark2DCodetext + var mailmark = new Mailmark2DCodetext { - InformationTypeID = "0", // Domestic Sorted & Unsorted (routing) VersionID = "1", - Class = "1", // Example class (service code) + InformationTypeID = "0", + Class = "1", RTSFlag = "0", - DestinationPostCodeAndDPS = "EC1A1BB", // Sample postcode + DPS SupplyChainID = 1234567, ItemID = 7654321, - UPUCountryID = "GBR" + DestinationPostCodeAndDPS = "SW1A1AA00", + ReturnToSenderPostCode = "SW1A1AA", + UPUCountryID = "GBR", + CustomerContent = "SampleContent", + CustomerContentEncodeMode = DataMatrixEncodeMode.C40 }; // ------------------------------------------------------------ - // 2. Construct the raw codetext string from the populated object. + // 2. Generate the codetext string that would be encoded in the barcode. // ------------------------------------------------------------ - string constructedCodetext = mailmark2d.GetConstructedCodetext(); + string constructedCodetext = mailmark.GetConstructedCodetext(); // ------------------------------------------------------------ - // 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. Decode the constructed codetext back into a Mailmark2DCodetext object. + // 3. Decode the generated codetext back into a Mailmark2DCodetext object. // ------------------------------------------------------------ Mailmark2DCodetext decoded = ComplexCodetextReader.TryDecodeMailmark2D(constructedCodetext); if (decoded == null) @@ -63,16 +52,18 @@ static void Main() } // ------------------------------------------------------------ - // 5. Extract and display individual fields from the decoded object. + // 4. Extract and display each individual field from the decoded object. // ------------------------------------------------------------ - Console.WriteLine("Decoded Mailmark2D fields:"); - Console.WriteLine($"Information Type ID (Routing): {decoded.InformationTypeID}"); - Console.WriteLine($"Version ID: {decoded.VersionID}"); - Console.WriteLine($"Class (Service Code): {decoded.Class}"); - 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}"); + 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}"); + Console.WriteLine($"ReturnToSenderPostCode: {decoded.ReturnToSenderPostCode}"); + Console.WriteLine($"UPUCountryID: {decoded.UPUCountryID}"); + Console.WriteLine($"CustomerContent: {decoded.CustomerContent}"); + Console.WriteLine($"CustomerContentEncodeMode: {decoded.CustomerContentEncodeMode}"); } } \ 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 e6a08e2..a38721d 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,11 +1,10 @@ -// 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. +// Title: Generate a Barcode with Transparent Background +// Description: Creates a Code128 barcode saved as a PNG image with a transparent background, suitable for overlaying on other graphics. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class to customize barcode appearance. It demonstrates setting foreground and background colors, specifically applying a transparent background, and saving the result in a format (PNG) that supports transparency. Developers working with barcode overlays, UI graphics, or printable labels often need to generate transparent barcodes for seamless integration with existing images. // Prompt: Generate a barcode with a transparent background for overlaying on other graphics. -// Tags: code128, barcode, transparent background, png, aspose.barcode, image generation +// Tags: code128, barcode generation, transparent background, png, aspose.barcode, aspose.drawing using System; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; @@ -15,30 +14,27 @@ class Program { /// - /// Entry point of the example. Creates a barcode, sets transparent background, and saves it as PNG. + /// Entry point that creates and saves the barcode image. /// static void Main() { - // Output file path + // Define the file path where the PNG image will be saved. string outputPath = "transparent_barcode.png"; - // Initialize the barcode generator for Code128 symbology - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Initialize the barcode generator for Code128 symbology with the desired text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - // Text to encode into the barcode - generator.CodeText = "Sample123"; + // Set the color of the barcode bars (foreground) to black. + generator.Parameters.Barcode.BarColor = Color.Black; - // Set background to transparent so the image can be overlaid + // Configure the background color to be transparent. generator.Parameters.BackColor = Color.Transparent; - // Optional: define the bar (foreground) color; default is black - generator.Parameters.Barcode.BarColor = Color.Black; - - // Save the barcode as PNG, which supports transparency - generator.Save(outputPath); + // Save the generated barcode as a PNG file, which preserves transparency. + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user where the file was saved + // Inform the user where the barcode image has been 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 76877aa..32ec212 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,53 +1,56 @@ // 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. +// Description: Creates a Mailmark 2D (type 7) barcode with routing and service code fields and saves it as a PNG file. +// Category-Description: Demonstrates Aspose.BarCode complex barcode generation for Mailmark symbology. Shows how to configure Mailmark2DCodetext, set optional customer content, and render the barcode using ComplexBarcodeGenerator. Useful for developers needing to produce Mailmark barcodes for postal services, logistics, or tracking applications. // Prompt: Generate a Mailmark type 7 barcode image using specified routing and service code fields. -// Tags: mailmark, barcode, generation, png, aspose.barcode, complexbarcodegenerator +// Tags: mailmark, type7, barcode generation, png, aspose.barcode, complexbarcodegenerator using System; -using Aspose.BarCode.ComplexBarcode; +using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.ComplexBarcode; using Aspose.Drawing; /// -/// Demonstrates creation of a Mailmark type 7 barcode image using Aspose.BarCode. +/// Example program that generates a Mailmark type 7 (2‑D) barcode and saves it as a PNG image. /// class Program { /// - /// Entry point. Builds a MailmarkCodetext, generates the barcode, and saves it as a PNG file. + /// Entry point. Builds the Mailmark2DCodetext, configures visual parameters, and writes the barcode to disk. /// static void Main() { - // Initialize Mailmark codetext with required fields - var mailmark = new MailmarkCodetext - { - // Mailmark 4‑state format (type 7) - Format = 4, - // Version identifier (typically 1) - VersionID = 1, - // Class identifier as a string - Class = "0", - // Routing / supply chain identifier - SupplychainID = 384224, - // Unique item identifier - ItemID = 16563762, - // Destination postcode + DPS (trailing space required by spec) - DestinationPostCodePlusDPS = "EF61AH8T " - }; - - // Generate the barcode using ComplexBarcodeGenerator - using (var generator = new ComplexBarcodeGenerator(mailmark)) + // Initialize a Mailmark 2D (type 7) codetext object + var mailmark2d = new Mailmark2DCodetext(); + + // ----- Required Mailmark fields ------------------------------------------------- + mailmark2d.VersionID = "1"; // Version identifier (mandatory) + mailmark2d.InformationTypeID = "7"; // Type 7 indicates a 2‑D Mailmark + mailmark2d.Class = "0"; // Class identifier (default) + mailmark2d.DestinationPostCodeAndDPS = "EF61AH8T "; // Destination postcode + DPS (trailing space required by spec) + mailmark2d.SupplyChainID = 384224; // Supply‑chain identifier assigned by the postal service + mailmark2d.ItemID = 16563762; // Unique item identifier within the supply chain + + // ----- Optional customer content (routing & service codes) ----------------------- + mailmark2d.CustomerContent = "R123S456"; // Example routing and service codes + mailmark2d.CustomerContentEncodeMode = DataMatrixEncodeMode.C40; // Encode using C40 to reduce size + + // Output file path for the generated PNG image + const string outputPath = "mailmark_type7.png"; + + // Use ComplexBarcodeGenerator to render the barcode based on the configured codetext + using (var generator = new ComplexBarcodeGenerator(mailmark2d)) { - // Optional visual settings: black bars on white background - generator.Parameters.Barcode.BarColor = Color.Black; - generator.Parameters.BackColor = Color.White; + // Optional visual customizations + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; // Barcode foreground color + generator.Parameters.BackColor = Aspose.Drawing.Color.White; // Background color - // Save the barcode image to a PNG file - generator.Save("mailmark.png"); + // Save the rendered barcode as a PNG file + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user that the image has been saved - Console.WriteLine("Mailmark barcode image saved as 'mailmark.png'."); + // Inform the user where the file was saved + Console.WriteLine($"Mailmark type 7 barcode saved to: {Path.GetFullPath(outputPath)}"); } } \ 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 31c8e1d..bd39dbf 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,97 +1,92 @@ -// 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. +// Title: Australia Post Barcode Generation with Customer Information Validation +// Description: Demonstrates generating an Australia Post barcode while validating customer information for unsupported characters and skipping generation when invalid. +// Category-Description: Shows how to use Aspose.BarCode to create Australia Post barcodes, covering the BarcodeGenerator class, encoding tables, and error handling. Typical use cases include postal services and logistics where customer data must conform to specific symbology rules. Developers often need to validate input, set encoding tables, and manage code‑text errors. // 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 +// Tags: barcode, australia post, validation, customer information, aspose.barcode, encoding table, ctable, ntable, other, image output using System; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// 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. +/// Example program that generates an Australia Post barcode after validating +/// customer information against the selected interpreting type. If validation fails, +/// a warning is logged and barcode generation is skipped. /// class Program { /// - /// Entry point of the example. Iterates through sample codes, validates customer information, - /// and creates barcode images when the data is supported. + /// Entry point of the example. Performs validation and generates the barcode image. /// static void Main() { - // Sample data: each tuple contains the full code text and the interpreting type to use. - var samples = new (string CodeText, CustomerInformationInterpretingType Interpreting)[] + // Example customer information that may contain unsupported characters + string customerInfo = "ABC$123"; + + // Choose the interpreting type for the customer information field + var interpretingType = CustomerInformationInterpretingType.CTable; + + // Validate the customer information against the selected interpreting type + if (!IsValidCustomerInfo(customerInfo, interpretingType)) { - ("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) - }; + // Log a warning and exit without generating the barcode + Console.WriteLine($"Warning: Customer information contains characters not allowed for {interpretingType}. Barcode generation skipped."); + return; + } - int index = 0; - foreach (var (codeText, interpreting) in samples) + // Combine the mandatory part of the Australia Post code with the customer information + string fullCodeText = "5912345678" + customerInfo; + + // Initialize the barcode generator for Australia Post symbology + using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, fullCodeText)) { - // Customer information part is everything after the first 10 characters (postal part). - string customerInfo = codeText.Length > 10 ? codeText.Substring(10) : string.Empty; + // Set the interpreting type (CTable, NTable, or Other) + generator.Parameters.Barcode.AustralianPost.EncodingTable = interpretingType; - // Validate the customer information according to the selected interpreting type. - if (!IsCustomerInfoValid(customerInfo, interpreting)) - { - // Log a warning and skip barcode generation for invalid data. - Console.WriteLine($"Warning: Customer information \"{customerInfo}\" is invalid for {interpreting}. Skipping generation."); - continue; - } + // Ensure that code‑text errors do not raise exceptions for this symbology + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; - // Generate Australia Post barcode using the valid code text. - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText)) + // Generate the barcode image (Aspose.Drawing.Bitmap) + using (Aspose.Drawing.Bitmap image = generator.GenerateBarCodeImage()) { - // Apply the appropriate encoding table for the customer information. - generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = interpreting; - - // 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)}"); + // Save the generated image to a file + string outputPath = "AustraliaPost.png"; + image.Save(outputPath); + Console.WriteLine($"Barcode saved to {outputPath}"); } - - index++; } } - // Validation according to the interpreting type. - static bool IsCustomerInfoValid(string info, CustomerInformationInterpretingType type) + // Validates customer information according to the selected interpreting type + static bool IsValidCustomerInfo(string info, CustomerInformationInterpretingType type) { switch (type) { case CustomerInformationInterpretingType.CTable: - // Allows A-Z, a-z, 1-9, space and '#'. - foreach (char ch in info) + foreach (char c in info) { - if (char.IsLetter(ch) || (ch >= '1' && ch <= '9') || ch == ' ' || ch == '#') - continue; - return false; + // CTable allows letters, digits, space and '#' + if (!(char.IsLetterOrDigit(c) || c == ' ' || c == '#')) + return false; } return true; case CustomerInformationInterpretingType.NTable: - // Allows digits only. - foreach (char ch in info) + foreach (char c in info) { - if (!char.IsDigit(ch)) + // NTable allows digits only + if (!char.IsDigit(c)) return false; } return true; case CustomerInformationInterpretingType.Other: - // Allows only symbols '0', '1', '2', '3'. - foreach (char ch in info) + // Other allows only 0‑3 symbols and a maximum length of 3 + if (info.Length > 3) return false; + foreach (char c in info) { - if (ch != '0' && ch != '1' && ch != '2' && ch != '3') + if (c < '0' || c > '3') return false; } return true; 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 7acdc65..493a505 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,95 +1,73 @@ -// 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. +// Title: Dependency Injection Example for Barcode Generation +// Description: Demonstrates how to inject a barcode generation service using a simple manual DI container and Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and related parameter classes. It illustrates typical scenarios where developers need to abstract barcode creation behind an interface for easier testing and maintainability, often employing dependency injection patterns in .NET applications. // Prompt: Implement dependency injection to provide a barcode generation service throughout the application. -// Tags: barcode symbology, generation, png, aspose.barcode, dependency injection, csharp +// Tags: barcode generation, dependency injection, code128, png, aspose.barcode, aspnet core using System; -using Microsoft.Extensions.DependencyInjection; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; -namespace BarcodeDIExample +namespace BarcodeDiExample { - /// - /// Service contract for barcode generation. - /// + // Service contract for barcode generation public interface IBarcodeService { /// - /// Generates a barcode image from the specified text and saves it to the given path. + /// Generates a barcode image from the provided text and saves it to the specified path. /// /// The text to encode in the barcode. - /// The file path where the barcode image will be saved. - void Generate(string codeText, string outputPath); + /// The file system path where the barcode image will be saved. + void GenerateBarcode(string codeText, string outputPath); } - /// - /// Concrete implementation of using Aspose.BarCode. - /// - public class BarcodeService : IBarcodeService, IDisposable + // Concrete implementation using Aspose.BarCode + public class BarcodeService : IBarcodeService { - private bool _disposed = false; - - /// - public void Generate(string codeText, string outputPath) + public void GenerateBarcode(string codeText, string outputPath) { - // Use Code128 as an example symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Ensure the output directory exists + string directory = System.IO.Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(directory) && !System.IO.Directory.Exists(directory)) { - generator.CodeText = codeText; - // Save the generated barcode as a PNG file. - generator.Save(outputPath); + System.IO.Directory.CreateDirectory(directory); } - } - /// - /// Disposes the service. Currently no unmanaged resources are held, but the pattern is kept for future extensibility. - /// - public void Dispose() - { - if (!_disposed) + // Create and configure the barcode generator + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // No unmanaged resources to release. - _disposed = true; + // Set basic colors (optional) + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Save the barcode image to the specified path + generator.Save(outputPath); } } } /// - /// Application entry point demonstrating DI-based barcode generation. + /// Provides a simple example of using dependency injection to generate barcodes. /// class Program { /// - /// Configures the DI container, resolves the barcode service, and generates a sample barcode. + /// Entry point of the application. Resolves the IBarcodeService and generates a sample barcode. /// - /// Command‑line arguments (not used). - static void Main(string[] args) + static void Main() { - // Set up a simple DI container. - var services = new ServiceCollection(); - - // Register the barcode service as a transient dependency. - services.AddTransient(); + // Simple manual DI container: resolve the service implementation + IBarcodeService barcodeService = new BarcodeService(); - // 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(); - - // Sample data and output file. - string sampleText = "123ABC456"; - string outputFile = "sample_code128.png"; + // Sample barcode data and output file + string sampleText = "ABC123"; + string outputFile = "barcode.png"; - // Generate the barcode image. - barcodeService.Generate(sampleText, outputFile); - - Console.WriteLine($"Barcode generated and saved to '{outputFile}'."); - } + // Generate the barcode using the injected service + barcodeService.GenerateBarcode(sampleText, outputFile); - // Program exits automatically. + Console.WriteLine($"Barcode generated and saved to '{outputFile}'."); } } } \ 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 f2efe06..8c3a5ef 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,107 +1,115 @@ -// 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. +// Title: Generate and Decode Code128 Barcode with Error Handling +// Description: This example creates a Code128 barcode image, saves it to disk, and then reads it back while handling possible decoding failures or incomplete data. +// Category-Description: Demonstrates Aspose.BarCode generation and recognition workflows. It uses BarcodeGenerator to produce barcodes and BarCodeReader to decode them, covering typical scenarios such as inventory labeling, shipping, and point‑of‑sale systems. Developers often need to validate barcode presence, handle missing or corrupt data, and manage exceptions from the Aspose.BarCode API. // 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 +// Tags: code128, barcode generation, barcode decoding, error handling, aspose.barcode, generation, recognition using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// 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. +/// Demonstrates creating a Code128 barcode image and decoding it with robust error handling. /// class Program { /// - /// Entry point of the example. Executes barcode creation, decoding, and cleanup with comprehensive error handling. + /// Entry point of the example. Generates a barcode, saves it, and attempts to decode it while handling errors. /// static void Main() { - // Define a temporary file path for the generated barcode image - string imagePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png"); + // Define the output file path for the generated barcode image. + string outputImagePath = "barcode.png"; - // ------------------------------------------------------------ - // Generate a sample barcode (Code128) and save it to the file - // ------------------------------------------------------------ - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // ------------------------------ + // Barcode Generation + // ------------------------------ + try + { + // Initialize the generator with Code128 symbology and the desired text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) + { + // Optional visual settings: set barcode and background colors. + generator.Parameters.Barcode.BarColor = Color.Black; + generator.Parameters.BackColor = Color.White; + + // Save the generated barcode image to the specified path. + generator.Save(outputImagePath); + Console.WriteLine($"Barcode image saved to '{outputImagePath}'."); + } + } + catch (Exception ex) { - // Optional: configure generator parameters here if needed - generator.Save(imagePath, BarCodeImageFormat.Png); + // Handle any errors that occur during barcode generation. + Console.WriteLine($"Error during barcode generation: {ex.Message}"); + return; } - // Verify that the image file was created successfully - if (!File.Exists(imagePath)) + // ------------------------------ + // Pre‑decoding Validation + // ------------------------------ + // Ensure the image file exists before attempting to read it. + if (!File.Exists(outputImagePath)) { - Console.WriteLine($"Error: Barcode image file not found at '{imagePath}'."); + Console.WriteLine($"File '{outputImagePath}' does not exist. Decoding aborted."); return; } - // ------------------------------------------------------------ - // Attempt to read the barcode with error handling - // ------------------------------------------------------------ + // ------------------------------ + // Barcode Decoding with Error Handling + // ------------------------------ try { - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Initialize the reader for Code128 barcodes using the generated image. + using (var reader = new BarCodeReader(outputImagePath, DecodeType.Code128)) { - // Use a high‑performance quality preset for faster processing - reader.QualitySettings = QualitySettings.HighPerformance; + // Configure reader settings, e.g., enforce checksum validation. + reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; - // Perform the recognition + // Perform the reading operation and retrieve all detected barcodes. var results = reader.ReadBarCodes(); - // No barcodes detected + // Verify that at least one barcode was detected. if (results == null || results.Length == 0) { Console.WriteLine("No barcode detected in the image."); return; } - // Process each detected barcode + // Process each detected barcode result. foreach (var result in results) { - // Check for missing or empty CodeText (incomplete data) - if (string.IsNullOrEmpty(result.CodeText)) + // Validate that the decoded text is present. + if (string.IsNullOrWhiteSpace(result.CodeText)) + { + Console.WriteLine("Barcode detected but CodeText is missing or empty."); + } + else { - Console.WriteLine($"Detected barcode of type '{result.CodeTypeName}' but CodeText is missing or empty."); - continue; + Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); } - // 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)); + // Optional: check the confidence level of the recognition. + if (result.Confidence == BarCodeConfidence.None) + { + Console.WriteLine("Warning: Low confidence in the recognized barcode."); + } } } } - catch (Exception ex) + catch (BarCodeException ex) { - // General exception handling for unexpected errors during decoding - Console.WriteLine($"An error occurred while decoding the barcode: {ex.Message}"); + // Handle specific Aspose.BarCode exceptions that may arise during decoding. + Console.WriteLine($"BarCodeException during decoding: {ex.Message}"); } - finally + catch (Exception ex) { - // ------------------------------------------------------------ - // Clean up the temporary image file - // ------------------------------------------------------------ - try - { - if (File.Exists(imagePath)) - { - File.Delete(imagePath); - } - } - catch - { - // Ignored – cleanup failure should not affect program flow - } + // Handle any other unexpected exceptions. + Console.WriteLine($"Unexpected error during decoding: {ex.Message}"); } } } \ No newline at end of file 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 6b5c079..5819098 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,42 +1,39 @@ -// 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. +// Title: Barcode Generation with Retry on Save Errors +// Description: Demonstrates generating a Code128 barcode image and saving it with a retry mechanism to handle transient I/O errors. +// Category-Description: Shows how to use Aspose.BarCode's BarcodeGenerator to create barcodes, configure visual parameters, and persist the image while implementing retry logic for transient failures. This example belongs to the barcode generation and image output category, illustrating typical use cases such as handling file system errors during Save operations. Developers working with Aspose.BarCode often need to ensure reliable image creation in automated pipelines. // 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 +// Tags: barcode, code128, retry, ioexception, barcodelibrary, aspose.barcode, image-saving, generation using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Example program that creates a Code128 barcode image with retry logic for transient errors. +/// Example program that generates a Code128 barcode and saves it to a PNG file, +/// retrying the save operation if transient errors occur. /// class Program { /// - /// Entry point. Generates a barcode, saves it to a PNG file, and retries on transient failures. + /// Entry point of the application. Executes the barcode generation and save logic with retry handling. /// static void Main() { - // Define the output file path for the barcode image - string outputPath = "barcode.png"; + const string outputFile = "barcode.png"; + const int maxRetries = 3; + int attempt = 0; + bool saved = false; - // Ensure the target directory exists before attempting to save - string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath)); - if (!Directory.Exists(directory)) + // Ensure the directory for the output file exists + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputFile)); + if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) { - Directory.CreateDirectory(directory); + Directory.CreateDirectory(outputDir); } - // 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 - - // Retry loop: continue until success or max attempts reached - while (attempt < maxAttempts && !success) + // Attempt to generate and save the barcode, retrying on failure up to maxRetries + while (attempt < maxRetries && !saved) { attempt++; try @@ -44,44 +41,35 @@ static void Main() // Create and configure the barcode generator using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) { - // Set visual appearance (optional) - generator.Parameters.Barcode.BarColor = Color.Black; - generator.Parameters.BackColor = Color.White; + // Set the barcode color (optional visual customization) + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - // Save the generated barcode image to the specified path - generator.Save(outputPath, BarCodeImageFormat.Png); + // Save the barcode image to the specified file + generator.Save(outputFile); } - // If no exception, mark as successful and inform the user - success = true; + // Mark as saved and report success + saved = true; Console.WriteLine($"Barcode saved successfully on attempt {attempt}."); } - catch (IOException ioEx) + catch (BarCodeException ex) { - // 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) + // Handle barcode-specific errors (e.g., invalid data or configuration) + Console.WriteLine($"BarCodeException on attempt {attempt}: {ex.Message}"); + if (attempt >= maxRetries) { Console.WriteLine("Maximum retry attempts reached. Operation failed."); } } - catch (BarCodeException bcEx) + catch (IOException ex) { - // Handle transient barcode generation errors - Console.WriteLine($"Barcode generation error on attempt {attempt}: {bcEx.Message}"); - if (attempt >= maxAttempts) + // Handle I/O errors such as file access conflicts or disk issues + Console.WriteLine($"IOException on attempt {attempt}: {ex.Message}"); + if (attempt >= maxRetries) { Console.WriteLine("Maximum retry attempts reached. Operation failed."); } } - catch (Exception ex) - { - // Handle non‑transient, unexpected errors and abort further retries - Console.WriteLine($"Unexpected error: {ex.Message}"); - break; - } } - - // 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 56245b0..8a29166 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,42 +1,50 @@ -// 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. +// Title: Generate Code128 Barcode and Output as Base64 String +// Description: Demonstrates creating a Code128 barcode using Aspose.BarCode, converting it to PNG, and encoding the image as a Base64 string, which can be returned from an ASP.NET MVC controller as a FileResult. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category. It showcases the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to produce barcode images. Typical scenarios include generating barcodes on-the-fly for web applications, embedding them in PDFs, or returning them via API endpoints. Developers often need to render barcodes in common image formats and stream them directly to HTTP responses. // 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 +// Tags: barcode generation, code128, png, base64, aspnet mvc, fileresult, aspose.barcode, c# using System; using System.IO; -using Aspose.BarCode.Generation; using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates barcode generation using Aspose.BarCode. +/// Demonstrates barcode generation logic suitable for an ASP.NET MVC controller. /// class Program { /// - /// Entry point for the console demonstration. In an MVC app this logic would reside in a controller action returning a FileResult. + /// Generates a Code128 barcode, encodes it to PNG, and writes the image as a Base64 string. /// static void Main() { - // Define the output file path for the generated barcode image. - string outputPath = "barcode.png"; + // In a real MVC controller this code would be placed inside an action method + // and the resulting byte array would be returned as a FileResult. - // Create a BarcodeGenerator for Code128 symbology with the desired data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789")) + // Initialize a BarcodeGenerator for the Code128 symbology with sample data. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) { - // Set the barcode's foreground (bar) color. + // Set visual appearance: black bars on a white background. generator.Parameters.Barcode.BarColor = Color.Black; - - // 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); + // Render the barcode to a memory stream in PNG format. + using (MemoryStream ms = new MemoryStream()) + { + generator.Save(ms, BarCodeImageFormat.Png); + byte[] imageBytes = ms.ToArray(); + + // Convert the PNG bytes to a Base64 string. + // In an MVC action you would return File(imageBytes, "image/png"). + string base64 = Convert.ToBase64String(imageBytes); + Console.WriteLine("Generated barcode image (Base64):"); + Console.WriteLine(base64); + } } - // Output the full path of the saved barcode image for verification. - Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}"); + // Program ends successfully. } } \ 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 83038ca..dc8cda6 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,88 +1,73 @@ -// 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. +// Title: Generate and Decode Code128 Barcode with Detailed Logging +// Description: Demonstrates creating a Code128 barcode, decoding it using Aspose.BarCode, and outputting all available decoding fields. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for barcode creation and BarCodeReader with DecodeType.AllSupportedTypes for decoding. Developers commonly use these APIs to embed barcodes in documents, read them from images, and troubleshoot decoding issues by examining detailed result properties. // Prompt: Log detailed decoding information, including field names and values, to assist troubleshooting. -// Tags: code128, barcode generation, barcode recognition, decoding, logging, aspose.barcode +// Tags: code128, barcode generation, barcode recognition, decoding, logging, aspose.barcode, c# using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; // Required for Bitmap if needed +using Aspose.Drawing.Imaging; // Required for image format enums /// -/// Demonstrates how to generate a Code128 barcode, save it as an image, -/// and then read it back while outputting detailed decoding information. +/// Demonstrates barcode generation and detailed decoding using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Generates a barcode, saves it, and logs - /// all available decoding details for each detected barcode. + /// Entry point. Generates a Code128 barcode, decodes it, and writes detailed result information to the console. /// static void Main() { - // Define the file name for the generated barcode image. - string imagePath = "sample_barcode.png"; - - // Generate a simple Code128 barcode and save it to a PNG file. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Generate a sample Code128 barcode and store it in a memory stream + var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"); + using (var barcodeStream = new MemoryStream()) { - // 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 as PNG into the stream + generator.Save(barcodeStream, BarCodeImageFormat.Png); + barcodeStream.Position = 0; // Reset stream position for reading - // Save the barcode image. - generator.Save(imagePath, BarCodeImageFormat.Png); - } + // Create a BarCodeReader to decode the barcode from the stream + using (var reader = new BarCodeReader(barcodeStream, DecodeType.AllSupportedTypes)) + { + // Perform recognition and retrieve all detected barcodes + BarCodeResult[] results = reader.ReadBarCodes(); - // Verify that the image file was successfully created. - if (!File.Exists(imagePath)) - { - Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); - return; - } + // Log detailed information for each detected barcode + foreach (BarCodeResult result in results) + { + Console.WriteLine($"Code Type Name : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + Console.WriteLine($"Confidence : {result.Confidence}"); + Console.WriteLine($"Reading Quality : {result.ReadingQuality}"); - // Read the barcode from the generated image and log detailed information. - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) - { - // Iterate through all detected barcodes in the image. - foreach (var result in reader.ReadBarCodes()) - { - 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}"); + // Region bounds + var rect = result.Region.Rectangle; + Console.WriteLine($"Region X : {rect.X}"); + Console.WriteLine($"Region Y : {rect.Y}"); + Console.WriteLine($"Region Width : {rect.Width}"); + Console.WriteLine($"Region Height : {rect.Height}"); - // Output the region bounds of the detected barcode. - var rect = result.Region.Rectangle; - Console.WriteLine($"Region X : {rect.X}"); - Console.WriteLine($"Region Y : {rect.Y}"); - Console.WriteLine($"Region Width : {rect.Width}"); - Console.WriteLine($"Region Height : {rect.Height}"); + // Orientation angle + Console.WriteLine($"Region Angle : {result.Region.Angle}"); - // Output extended information if it is available. - if (result.Extended != null) - { - // Example for 1D barcodes (e.g., Code128). - var oneD = result.Extended.OneD; - if (oneD != null) + // Corner points of the detected barcode region + var points = result.Region.Points; + for (int i = 0; i < points.Length; i++) { - Console.WriteLine($"Extended Value : {oneD.Value}"); - Console.WriteLine($"Extended CheckSum: {oneD.CheckSum}"); + Console.WriteLine($"Region Point {i} : X={points[i].X}, Y={points[i].Y}"); } - // 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(new string('-', 40)); } - Console.WriteLine(); + // If no barcodes were found, inform the user + if (results.Length == 0) + { + Console.WriteLine("No barcodes were detected in the image."); + } } } } 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 8facc16..75388f9 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,61 +1,71 @@ -// 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. +// Title: Parallel Barcode Generation with TPL +// Description: Demonstrates generating multiple Code128 barcodes concurrently using Aspose.BarCode and the Task Parallel Library to improve throughput for large datasets. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, showcasing how to create barcode images in bulk. It uses the BarcodeGenerator class with EncodeTypes.Code128, configures basic parameters, and saves PNG files. Developers often need to generate many barcodes quickly, and parallelizing the work with TPL is a common technique to reduce processing time. // 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 +// Tags: barcode symbology, generation, parallel, tpl, png, aspose.barcode, code128 using System; using System.Collections.Generic; +using System.IO; using System.Threading.Tasks; -using Aspose.BarCode.Generation; using Aspose.BarCode; +using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Example program that generates Code128 barcodes in parallel using the Task Parallel Library (TPL). +/// Demonstrates parallel generation of Code128 barcodes using Aspose.BarCode and TPL. /// class Program { /// - /// Entry point of the application. Generates barcodes for each item in the data set concurrently. + /// Entry point. Generates barcodes for a sample list in parallel and saves them as PNG files. /// static void Main() { - // Sample data set (replace with real data in production) - List dataSet = new List + // Prepare a small sample dataset of code texts. + var codeTexts = new List { - "Item001", - "Item002", - "Item003", - "Item004", - "Item005" + "12345", + "ABCDE", + "987654321", + "CODE128", + "Test123" }; - // Output directory (current folder) - string outputFolder = AppDomain.CurrentDomain.BaseDirectory; + // Create output folder for the generated barcode images. + var outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); - // Parallel generation of barcodes using TPL - Parallel.ForEach(dataSet, (codeText) => + // Parallelize barcode generation using the Task Parallel Library. + var tasks = new List(); + for (int i = 0; i < codeTexts.Count; i++) { - // Each task creates its own generator instance because BarcodeGenerator is not thread‑safe - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + int index = i; // Capture loop variable for the task closure. + tasks.Add(Task.Run(() => { - // 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; + // Each barcode generation uses its own BarcodeGenerator instance. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeTexts[index])) + { + // Optional: set barcode appearance parameters. + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.Barcode.XDimension.Point = 2f; + + // Define the output file path for this barcode. + var outputPath = Path.Combine(outputFolder, $"barcode_{index + 1}.png"); - // Build output file name (e.g., Item001.png) - string filePath = System.IO.Path.Combine(outputFolder, $"{codeText}.png"); + // Save the barcode image in PNG format. + generator.Save(outputPath, BarCodeImageFormat.Png); + } - // Save the barcode image to the specified path - generator.Save(filePath); + // Log progress to the console. + Console.WriteLine($"Generated barcode {index + 1} for text '{codeTexts[index]}'"); + })); + } - // Log the successful generation to the console - Console.WriteLine($"Generated barcode for '{codeText}' -> {filePath}"); - } - }); + // Wait for all barcode generation tasks to complete. + Task.WaitAll(tasks.ToArray()); - // Indicate that all barcode generation tasks have completed + // Indicate that the process has finished. Console.WriteLine("All barcodes have been generated."); } } \ No newline at end of file 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 c46c7ce..a51f5cd 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,6 +1,6 @@ // 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. +// Description: Demonstrates how to load an image file, detect a Mailmark 2D barcode (DataMatrix) with Aspose.BarCode, and extract its structured fields. +// Category-Description: This example belongs to the Aspose.BarCode barcode reading category, showcasing the use of BarCodeReader with DecodeType.DataMatrix and ComplexCodetextReader to interpret complex symbologies such as Mailmark 2D. Developers commonly need to read postal barcodes from scanned images, extract metadata, and integrate it into mailing workflows. The key API classes include BarCodeReader, DecodeType, and ComplexCodetextReader, which together provide detection, decoding, and detailed parsing capabilities. // Prompt: Read a Mailmark 2D barcode from an image file using BarCodeReader with DecodeType.DataMatrix. // Tags: mailmark, datamatrix, barcode, reading, aspose.barcode, complexcodetext @@ -10,12 +10,12 @@ using Aspose.BarCode.ComplexBarcode; /// -/// Demonstrates reading a Mailmark 2D barcode from an image file and decoding its fields. +/// Example program that reads a Mailmark 2D barcode from an image file. /// class Program { /// - /// Entry point. Loads the image, detects Mailmark 2D barcode, and prints decoded information. + /// Entry point. Loads the image, scans for DataMatrix barcodes, and parses Mailmark 2D details. /// static void Main() { @@ -29,45 +29,26 @@ static void Main() return; } - // Initialize the reader for DataMatrix symbology (Mailmark 2D is encoded in a DataMatrix) + // Create a BarCodeReader configured for DataMatrix (Mailmark 2D is based on DataMatrix) using (var reader = new BarCodeReader(imagePath, DecodeType.DataMatrix)) { - // Perform the recognition - var results = reader.ReadBarCodes(); - - // Check if any barcodes were detected - if (results.Length == 0) - { - Console.WriteLine("No barcode detected in the image."); - return; - } - - // Iterate through all detected barcodes (typically only one Mailmark 2D) - foreach (var result in results) + // Iterate through all detected barcodes in the image + foreach (var result in reader.ReadBarCodes()) { - // Output basic barcode information - Console.WriteLine($"Detected barcode type: {result.CodeTypeName}"); - Console.WriteLine($"Raw CodeText: {result.CodeText}"); + // Output the raw decoded text + Console.WriteLine($"Detected CodeText: {result.CodeText}"); - // Attempt to decode the Mailmark 2D codetext into a strongly‑typed object + // Attempt to decode the result as a Mailmark 2D codetext var mailmark = ComplexCodetextReader.TryDecodeMailmark2D(result.CodeText); if (mailmark != null) { - // Print each decoded field of the Mailmark 2D structure - Console.WriteLine("Decoded Mailmark 2D codetext:"); + // Output the parsed Mailmark 2D fields + Console.WriteLine("Mailmark 2D details:"); 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 - { - // Decoding failed – inform the user - Console.WriteLine("Failed to decode Mailmark 2D codetext."); } } } 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 d5c999c..837e727 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,50 +1,46 @@ // 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 +// Description: Demonstrates generating a Mailmark barcode using Aspose.BarCode and rotating the image 90 degrees for layout requirements. +// 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 ComplexBarcodeGenerator and MailmarkCodetext classes to create a barcode, adjust rendering parameters like rotation, and save the result as an image. Developers working with postal barcodes or custom layout constraints can refer to this pattern for similar implementations. +// Prompt: Rotate the generated Mailmark barcode by 90 degrees to satisfy specific layout requirements. +// Tags: mailmark, barcode, rotation, image, aspnet, aspose.barcode, complexbarcodegenerator, csharp using System; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; -using Aspose.Drawing; -using Aspose.Drawing.Imaging; +using Aspose.BarCode.Generation; /// -/// Demonstrates generating a Mailmark barcode, rotating it 90° clockwise, and saving the result as a PNG file. +/// Demonstrates generating and rotating a Mailmark barcode using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Prepares Mailmark codetext, creates the barcode image, rotates it, and writes the output file. + /// Entry point that creates a Mailmark barcode, rotates it 90 degrees, and saves the image. /// static void Main() { - // Prepare Mailmark codetext with required fields + // Prepare Mailmark codetext with valid sample data var mailmark = new MailmarkCodetext { - Format = 4, // 4‑state barcode + // 4-state Mailmark format + Format = 4, VersionID = 1, - Class = "0", // service type / class + Class = "0", SupplychainID = 384224, - ItemID = 16563762, // customer reference - DestinationPostCodePlusDPS = "EF61AH8T " // valid postcode + DPS + ItemID = 16563762, + // Trailing space is required for the DestinationPostCodePlusDPS field + DestinationPostCodePlusDPS = "EF61AH8T " }; - // Generate the Mailmark barcode image using ComplexBarcodeGenerator + // Generate the Mailmark barcode and apply a 90‑degree rotation using (var generator = new ComplexBarcodeGenerator(mailmark)) { - using (Image barcodeImage = generator.GenerateBarCodeImage()) - { - // Rotate the image 90 degrees clockwise (no flip) - barcodeImage.RotateFlip(RotateFlipType.Rotate90FlipNone); + // RotationAngle is a root Parameters property + generator.Parameters.RotationAngle = 90f; - // 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}"); - } + // Save the rotated barcode image to a PNG file + generator.Save("MailmarkRotated.png"); } + + Console.WriteLine("Mailmark barcode generated and rotated successfully."); } } \ 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 8ac6619..2967df6 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,8 +1,8 @@ -// 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. +// Title: Generate and Save a Mailmark Barcode as JPEG +// Description: Demonstrates creating a Mailmark barcode using Aspose.BarCode and saving it as a JPEG image in a specified folder. +// 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 MailmarkCodetext and ComplexBarcodeGenerator classes to produce high‑security postal barcodes, a common requirement for logistics and mailing applications. Developers often need to generate these barcodes programmatically and export them to image formats for integration into documents or printing workflows. // Prompt: Save the generated Mailmark barcode as a JPEG file to a specified output folder. -// Tags: mailmark, barcode, generation, jpeg, aspose.barcode, complexbarcode, codetext +// Tags: mailmark, barcode generation, jpeg, complexbarcode, aspose.barcode using System; using System.IO; @@ -11,41 +11,44 @@ using Aspose.BarCode.ComplexBarcode; /// -/// Demonstrates generating a Mailmark barcode and saving it as a JPEG file. +/// Example program that creates a Mailmark barcode and saves it as a JPEG file. /// class Program { /// - /// Entry point of the example. Generates the barcode and writes it to the output folder. + /// Entry point of the application. + /// Generates a Mailmark barcode using a MailmarkCodetext object and writes the image to disk. /// static void Main() { - // Define the output folder and ensure it exists. + // Define the output folder and ensure it exists string outputFolder = "Output"; if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } - // Populate the Mailmark codetext with required fields. + // Create a valid MailmarkCodetext instance with required properties var mailmark = new MailmarkCodetext { - Format = 4, // 4-state format + // 4-state Mailmark format + Format = 4, VersionID = 1, Class = "0", SupplychainID = 384224, ItemID = 16563762, + // Destination post code plus DPS (trailing space is required) DestinationPostCodePlusDPS = "EF61AH8T " }; - // Generate the Mailmark barcode and save it as JPEG. + // Generate the Mailmark barcode using ComplexBarcodeGenerator using (var generator = new ComplexBarcodeGenerator(mailmark)) { - string outputPath = Path.Combine(outputFolder, "mailmark.jpeg"); + // Build the full output file path + string outputPath = Path.Combine(outputFolder, "Mailmark.jpg"); + // Save the barcode as a JPEG image generator.Save(outputPath, BarCodeImageFormat.Jpeg); + 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 0faf2ca..125544d 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,8 +1,8 @@ -// 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. +// Title: Serialize Mailmark2D Code Text to JSON and Generate Barcode +// Description: This example creates a Mailmark2DCodetext object, serializes it to JSON for persistence, deserializes it back, and generates a Mailmark 2D barcode image. +// Category-Description: Demonstrates Aspose.BarCode complex barcode generation workflow, covering object serialization with System.Text.Json, deserialization, and barcode image creation using ComplexBarcodeGenerator. Developers working with Mailmark 2D symbology often need to store code text configurations and later reconstruct them for barcode rendering in applications. // Prompt: Serialize a Mailmark2DCodetext object to JSON for storage and later reconstruction in applications. -// Tags: barcode, serialization, json, mailmark2d, aspose.barcode +// Tags: mailmark2d, json, serialization, deserialization, barcode generation, complexbarcode, aspnet.barcode, system.text.json, png using System; using System.IO; @@ -11,75 +11,65 @@ using Aspose.BarCode.Generation; /// -/// Example program that serializes and deserializes a object using JSON. +/// Demonstrates serialization of Mailmark2DCodetext to JSON and barcode generation. /// class Program { /// - /// Entry point of the example. Creates a Mailmark2DCodetext, writes it to JSON, reads it back, and prints the values. + /// Entry point that creates, serializes, deserializes Mailmark2DCodetext and generates a barcode image. /// static void Main() { - // ------------------------------------------------------------ - // 1. Create and populate a Mailmark2DCodetext instance - // ------------------------------------------------------------ - var mailmark2D = new Mailmark2DCodetext + // Create a sample Mailmark2DCodetext with required fields + var mailmark2d = new Mailmark2DCodetext { - UPUCountryID = "JGB ", - InformationTypeID = "0", + // Single‑character string values as required by the API VersionID = "1", + InformationTypeID = "0", Class = "1", - SupplyChainID = 123, - ItemID = 1234, - DestinationPostCodeAndDPS = "QWE1", RTSFlag = "0", - ReturnToSenderPostCode = "QWE2", - DataMatrixType = Mailmark2DType.Type_7, - CustomerContent = "CUSTOM", - CustomerContentEncodeMode = DataMatrixEncodeMode.C40 + + // Integer identifiers + ItemID = 16563762, + SupplyChainID = 384224, + + // Destination postcode with DPS (trailing space is required) + DestinationPostCodeAndDPS = "EF61AH8T ", + + // Optional fields (left as defaults or set as needed) + // CustomerContent = "Optional customer data", + // CustomerContentEncodeMode = DataMatrixEncodeMode.C40, + // DataMatrixType = Mailmark2DType.Auto, + // ReturnToSenderPostCode = "SW1A1AA", + // UPUCountryID = "GB" }; - // ------------------------------------------------------------ - // 2. Serialize the object to a formatted JSON string - // ------------------------------------------------------------ + // Serialize the object to JSON with indentation for readability var jsonOptions = new JsonSerializerOptions { WriteIndented = true }; - string json = JsonSerializer.Serialize(mailmark2D, jsonOptions); + string json = JsonSerializer.Serialize(mailmark2d, jsonOptions); + + // Store JSON to a file + const string jsonPath = "mailmark2d.json"; + File.WriteAllText(jsonPath, json); + Console.WriteLine($"Mailmark2DCodetext serialized to {jsonPath}"); - // ------------------------------------------------------------ - // 3. Save the JSON string to a file - // ------------------------------------------------------------ - const string filePath = "mailmark2d.json"; - using (var writeStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) - using (var writer = new StreamWriter(writeStream)) + // Read JSON back from the file + string jsonFromFile = File.ReadAllText(jsonPath); + var deserializedMailmark2d = JsonSerializer.Deserialize(jsonFromFile); + if (deserializedMailmark2d == null) { - writer.Write(json); + Console.WriteLine("Deserialization failed."); + return; } + Console.WriteLine("Mailmark2DCodetext deserialized successfully."); - // ------------------------------------------------------------ - // 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)) + // Generate a barcode image from the deserialized object + const string imagePath = "mailmark2d.png"; + using (var generator = new ComplexBarcodeGenerator(deserializedMailmark2d)) { - string jsonFromFile = reader.ReadToEnd(); - deserialized = JsonSerializer.Deserialize(jsonFromFile); + // Save the barcode image to a PNG file + generator.Save(imagePath); } - - // ------------------------------------------------------------ - // 5. Output selected fields to verify successful reconstruction - // ------------------------------------------------------------ - 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}"); + Console.WriteLine($"Barcode image saved to {imagePath}"); } } \ 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 d60a1a4..8a0af76 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,8 +1,8 @@ -// 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. +// Title: Read DataMatrix Barcode from Generated Image +// Description: Generates a DataMatrix barcode, saves it as a PNG file, and then decodes it using BarCodeReader. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator to create a barcode image and BarCodeReader to recognize and decode the barcode. Developers often need to generate barcodes for labeling or tracking and later verify or extract the encoded data, requiring knowledge of setting DecodeType before reading. // Prompt: Set BarCodeReader.DecodeType to DecodeType.DataMatrix before invoking the Read method on the image. -// Tags: datamatrix, decode, png, barcodegenerator, barcodereader, aspnet, csharp +// Tags: datamatrix, barcode, generation, recognition, decode, aspose.barcode using System; using System.IO; @@ -10,43 +10,50 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates generating a DataMatrix barcode, saving it as PNG, and reading it back with decoding limited to DataMatrix. +/// Demonstrates generating a DataMatrix barcode image and decoding it using Aspose.BarCode. /// class Program { /// - /// Entry point. Generates the barcode image, verifies its existence, and reads the barcode using BarCodeReader with DecodeType.DataMatrix. + /// Entry point of the example. Generates a DataMatrix barcode, saves it, and reads it back. /// static void Main() { - // Define the file path for the sample DataMatrix barcode image. + // Path where the generated barcode image will be saved string imagePath = "datamatrix.png"; - // Generate a DataMatrix barcode and save it to a PNG file. - using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "SampleData")) + // ------------------------------------------------------------ + // Generate a DataMatrix barcode and save it as a PNG file + // ------------------------------------------------------------ + using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "Hello")) { - // Save the generated barcode image. + // Optional: configure additional DataMatrix parameters here + // generator.Parameters.Barcode.DataMatrix.Version = DataMatrixVersion.ECC200_10x10; + + // Save the barcode image to the specified path generator.Save(imagePath, BarCodeImageFormat.Png); } - // Verify that the image file was successfully created. + // Verify that the image file was created successfully if (!File.Exists(imagePath)) { - Console.WriteLine($"Error: Barcode image '{imagePath}' was not found."); + Console.WriteLine($"Failed to create barcode image at '{Path.GetFullPath(imagePath)}'."); return; } - // Create a BarCodeReader to read the barcode from the image. + // ------------------------------------------------------------ + // Read and decode the barcode from the generated image + // ------------------------------------------------------------ using (var reader = new BarCodeReader(imagePath)) { - // Set the decode type to DataMatrix before reading to limit detection to this symbology. + // Set the decode type to DataMatrix before performing the read operation reader.BarCodeReadType = DecodeType.DataMatrix; - // Perform barcode detection and iterate through any results. + // Iterate through all detected barcodes (expected one in this case) foreach (var result in reader.ReadBarCodes()) { Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Decoded Text: {result.CodeText}"); + Console.WriteLine($"Code 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 5979976..5ebe356 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,49 +1,60 @@ -// 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. +// Title: Stream Barcode Directly to HTTP Response +// Description: Demonstrates generating a Code128 barcode and streaming it as a PNG image directly to an HTTP response without creating a temporary file. +// Category-Description: This example belongs to the Aspose.BarCode image generation category. It shows how to use the BarcodeGenerator class together with BarCodeImageFormat to produce barcode images on‑the‑fly. Typical use cases include web applications that need to return barcode images to browsers or APIs, where writing to disk is undesirable. Developers often need to write the image to a response stream, set colors, and choose output formats. // 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 +// Tags: barcode, code128, generation, stream, png, aspnet, aspose.barcode, aspose.drawing using System; using System.IO; -using System.Text; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode, encodes it as Base64, -/// and writes the result to the console (simulating an HTTP response body). +/// Demonstrates streaming a generated barcode image directly to an HTTP response. /// class Program { /// - /// Entry point of the example. Generates a barcode in memory and outputs a Base64 data URI. + /// Entry point that simulates an HTTP response stream and outputs diagnostic information. /// static void Main() { - // 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")) + // Simulate an HTTP response stream. + // In a real web application, replace this MemoryStream with HttpResponse.OutputStream. + using (var responseStream = new MemoryStream()) { - // Optional: customize barcode appearance here if needed. - // e.g., generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; + // Generate the barcode and write it directly to the response stream. + GenerateBarcodeToStream(responseStream); + + // Show the size of the generated image for verification. + Console.WriteLine($"Generated barcode image size: {responseStream.Length} bytes"); - // Generate the barcode image into a memory stream. - using (var ms = new MemoryStream()) - { - generator.Save(ms, BarCodeImageFormat.Png); - byte[] imageBytes = ms.ToArray(); + // Reset the stream position to the beginning to read its contents. + responseStream.Position = 0; + + // Optional: display the image as a Base64 string (useful for testing or embedding in HTML). + string base64 = Convert.ToBase64String(responseStream.ToArray()); + Console.WriteLine("Base64 PNG:"); + Console.WriteLine(base64); + } + } - // Convert the image bytes to a Base64 string. - string base64Image = Convert.ToBase64String(imageBytes); + /// + /// Generates a Code128 barcode and saves it as a PNG image to the specified output stream. + /// + /// The stream to which the barcode image will be written. + static void GenerateBarcodeToStream(Stream outputStream) + { + // Initialize the barcode generator with the desired symbology and data. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) + { + // Configure visual appearance (optional). + generator.Parameters.Barcode.BarColor = Color.Black; // Foreground color. + generator.Parameters.BackColor = Color.White; // Background color. - // Output the Base64 string to the console. - Console.WriteLine("data:image/png;base64," + base64Image); - } + // Save the generated barcode directly to the provided stream in PNG format. + generator.Save(outputStream, BarCodeImageFormat.Png); } } } \ No newline at end of file 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 186edc2..96da1de 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,78 +1,73 @@ -// 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 +// Title: Decode Mailmark 2D codetext using ComplexCodetextReader +// Description: Demonstrates creating a Mailmark2DCodetext, encoding it to a string, and decoding it back using ComplexCodetextReader.TryDecodeMailmark2D. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode operations category. It showcases the use of Aspose.BarCode.ComplexBarcode classes such as Mailmark2DCodetext and ComplexCodetextReader for generating and parsing Mailmark 2D codetext. Developers working with postal barcode standards often need to construct codetext, encode it into barcodes, and later decode it for validation or data extraction. +// Prompt: Use ComplexCodetextReader.TryDecodeMailmark2D to obtain a Mailmark2DCodetext object from the decoded result. +// Tags: mailmark, 2d, barcode, decoding, complexcodetextreader, aspnet, csharp using System; -using System.IO; -using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; /// -/// Example program that generates a Mailmark2D barcode, reads it, and decodes its fields. +/// Example program that creates a Mailmark2DCodetext, encodes it, and then decodes it back +/// using . /// class Program { /// - /// 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. + /// Entry point of the example. Builds a Mailmark2DCodetext, constructs its codetext string, + /// attempts to decode it, and prints the resulting property values. /// static void Main() { - // Create a Mailmark2D codetext with required fields + // ------------------------------------------------------------ + // 1. Create a Mailmark2DCodetext instance with sample data. + // ------------------------------------------------------------ var mailmark2d = new Mailmark2DCodetext { - 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 + VersionID = "1", + InformationTypeID = "0", + Class = "1", + RTSFlag = "0", + SupplyChainID = 1234567, + ItemID = 7654321, + DestinationPostCodeAndDPS = "SW1A1AA00", + ReturnToSenderPostCode = "SW1A1AA", + UPUCountryID = "GB", + CustomerContent = "Sample", + CustomerContentEncodeMode = DataMatrixEncodeMode.C40 }; - // Generate the Mailmark2D barcode image into a memory stream - using (var generator = new ComplexBarcodeGenerator(mailmark2d)) - { - 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(); + // ------------------------------------------------------------ + // 2. Construct the codetext string that would be encoded in a barcode. + // ------------------------------------------------------------ + string encoded = mailmark2d.GetConstructedCodetext(); - // Process each detected barcode result - foreach (var result in results) - { - Console.WriteLine($"Detected CodeText: {result.CodeText}"); + // ------------------------------------------------------------ + // 3. Decode the constructed codetext back into a Mailmark2DCodetext object. + // ------------------------------------------------------------ + Mailmark2DCodetext decoded = ComplexCodetextReader.TryDecodeMailmark2D(encoded); - // 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."); - } - } - } - } + // ------------------------------------------------------------ + // 4. Output the decoded values or an error message. + // ------------------------------------------------------------ + if (decoded != null) + { + Console.WriteLine("Decoded Mailmark2D:"); + 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}"); + Console.WriteLine($"ReturnToSenderPostCode: {decoded.ReturnToSenderPostCode}"); + Console.WriteLine($"UPUCountryID: {decoded.UPUCountryID}"); + Console.WriteLine($"CustomerContent: {decoded.CustomerContent}"); + } + 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 eea9ab0..b37a35a 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,8 +1,8 @@ -// 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. +// Title: Generate Code128 Barcode into MemoryStream +// Description: Demonstrates generating a Code128 barcode image, storing it in a MemoryStream, and accessing the raw bytes for further processing. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to create barcode images in memory. Typical use cases include preparing barcode images for network transmission, embedding in documents, or further image manipulation without writing to disk. Developers often need in‑memory processing to improve performance and simplify deployment in cloud or CI environments. // 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 +// Tags: barcode symbology, generation, memorystream, png, aspose.barcode, csharp using System; using System.IO; @@ -10,43 +10,42 @@ using Aspose.BarCode.Generation; using Aspose.Drawing; -/// -/// Demonstrates generating a Code128 barcode, storing it in a MemoryStream, -/// and performing in‑memory processing such as size reporting and Base64 conversion. -/// -class Program +namespace BarcodeMemoryStreamDemo { /// - /// Entry point of the example. Creates a barcode, saves it to a MemoryStream, - /// and outputs image size and Base64 representation. + /// Demonstrates creating a barcode image in memory using Aspose.BarCode. /// - static void Main() + class Program { - // Initialize a barcode generator for Code128 with the sample text "Sample123" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + /// + /// Entry point that generates a Code128 barcode, writes it to a MemoryStream, + /// and outputs the size of the resulting PNG image. + /// + static void Main() { - // Configure visual appearance: white background and black bars - generator.Parameters.BackColor = Color.White; - generator.Parameters.Barcode.BarColor = Color.Black; - - // Create a MemoryStream to hold the generated PNG image in memory - using (var memoryStream = new MemoryStream()) + // Create a MemoryStream to hold the generated barcode image in memory + using (var ms = new MemoryStream()) { - // Save the barcode image into the stream in PNG format - generator.Save(memoryStream, BarCodeImageFormat.Png); + // Initialize a barcode generator for Code128 with the sample text "ABC123" + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123")) + { + // Configure visual appearance: blue foreground on white background + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Reset stream position to the beginning for reading - memoryStream.Position = 0; + // Save the generated barcode as a PNG image into the MemoryStream + generator.Save(ms, BarCodeImageFormat.Png); + } - // Extract the image bytes from the stream for further processing or transmission - byte[] imageBytes = memoryStream.ToArray(); + // Reset the stream position to the beginning for subsequent reads + ms.Position = 0; - // Display the size of the generated image in bytes - Console.WriteLine($"Generated barcode image size: {imageBytes.Length} bytes"); + // Retrieve the image bytes from the MemoryStream + byte[] imageBytes = ms.ToArray(); - // Example of converting the image bytes to a Base64 string and displaying it - string base64 = Convert.ToBase64String(imageBytes); - Console.WriteLine($"Base64: {base64}"); + // Output the size of the generated barcode image (useful for verification) + Console.WriteLine($"Generated barcode image size: {imageBytes.Length} bytes"); + // The byte array can now be transmitted over a network, embedded in documents, etc. } } } 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 5d98de8..36dd66b 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,79 +1,94 @@ -// 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. +// Title: C40 Character Set Validation for Non‑Customer Fields Before Barcode Generation +// Description: Demonstrates how to validate that all non‑customer data fields contain only characters allowed by the C40 encoding set prior to generating a barcode. +// Category-Description: This example belongs to the Aspose.BarCode data validation category, illustrating the use of Aspose.BarCode.Generation.BarcodeGenerator and related classes to ensure input data complies with specific character sets (C40) before barcode creation. Developers often need to pre‑validate fields such as product codes or descriptions to avoid encoding errors. The snippet shows typical validation logic, field filtering, and barcode generation with Code128. // Prompt: Validate that all non‑customer fields conform to the C40 character set before generation. -// Tags: datamatrix, c40, validation, png, barcodegenerator, datamatrixencodemode, aspnet.barcode +// Tags: barcode symbology, validation, c40, code128, png, aspose.barcode, generation using System; -using Aspose.BarCode; +using System.Collections.Generic; +using System.IO; using Aspose.BarCode.Generation; -using Aspose.Drawing; +using Aspose.BarCode.BarCodeRecognition; /// -/// Generates a DataMatrix barcode using C40 encoding after validating the input string. +/// Demonstrates validation of non‑customer fields against the C40 character set and generates a Code128 barcode. /// class Program { + // Allowed characters for C40 encoding: digits, uppercase letters, space and common punctuation. + private static readonly HashSet C40AllowedChars = new HashSet + { + ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', '?' + }; + /// - /// Entry point. Validates the code text against the C40 charset and creates a PNG barcode if valid. + /// Entry point that validates fields, ensures output directory, and creates a barcode image. /// static void Main() { - // Sample code text representing non‑customer fields - string codeText = "HELLO WORLD 123!"; - - // Validate that the code text conforms to the C40 character set - if (!IsC40String(codeText)) + // Sample data fields. Fields named "CustomerName" are considered customer fields and are excluded from validation. + var fields = new Dictionary { - Console.WriteLine("Warning: CodeText contains characters not allowed in the C40 charset. Generation skipped."); - return; - } + { "CustomerName", "Acme Corp" }, // Customer field – skip validation + { "ProductCode", "ABC123" }, // Non‑customer field – must be C40 compliant + { "Description", "NEW PRODUCT! RELEASE" } // Non‑customer field – must be C40 compliant + }; - // Create a DataMatrix barcode generator with C40 encoding mode - using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, codeText)) + // Validate non‑customer fields. + foreach (var kvp in fields) { - // Set the DataMatrix encode mode to C40 - generator.Parameters.Barcode.DataMatrix.EncodeMode = DataMatrixEncodeMode.C40; + if (IsCustomerField(kvp.Key)) + continue; // Skip customer fields. + + if (!IsC40Compliant(kvp.Value)) + { + Console.WriteLine($"Field \"{kvp.Key}\" contains characters not allowed in C40 encoding."); + // Abort further processing. + return; + } + } - // Optionally control image size (using unit members) - generator.Parameters.ImageWidth.Point = 200f; - generator.Parameters.ImageHeight.Point = 200f; + // All validations passed – generate a barcode. + const string barcodeText = "VALIDDATA"; + const string outputPath = "barcode.png"; - // Save the generated barcode image - string outputPath = "datamatrix_c40.png"; - generator.Save(outputPath); - Console.WriteLine($"Barcode saved to {outputPath}"); + // Ensure the output directory exists. + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); } - } - // Checks if every character in the string is allowed in the C40 charset - static bool IsC40String(string text) - { - foreach (char ch in text) + // Create and configure the barcode generator. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, barcodeText)) { - if (!IsC40Char(ch)) - return false; + // Example of setting a barcode property (XDimension) correctly. + generator.Parameters.Barcode.XDimension.Point = 2.5f; + generator.Save(outputPath, BarCodeImageFormat.Png); } - return true; + + Console.WriteLine($"Barcode generated successfully at \"{outputPath}\"."); } - // Determines whether a single character is part of the C40 charset - static bool IsC40Char(char ch) + // Determines whether a field name represents a customer field. + private static bool IsCustomerField(string fieldName) { - // Uppercase letters - if (ch >= 'A' && ch <= 'Z') - return true; - - // Digits - if (ch >= '0' && ch <= '9') - return true; + // Simple rule: field name contains the word "Customer". + return fieldName.IndexOf("Customer", StringComparison.OrdinalIgnoreCase) >= 0; + } - // Space - if (ch == ' ') - return true; + // Checks if a string contains only characters allowed in C40 encoding. + private static bool IsC40Compliant(string text) + { + foreach (char ch in text) + { + if (char.IsDigit(ch) || (ch >= 'A' && ch <= 'Z') || C40AllowedChars.Contains(ch)) + continue; - // Basic punctuation allowed in C40 - const string punctuation = "!\"#%&'()*+,-./:;<=>?"; - return punctuation.IndexOf(ch) >= 0; + // Lowercase letters are not part of C40; they must be converted or cause failure. + return false; + } + return true; } } \ 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 b60a162..4d7ab52 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,116 +1,83 @@ -// 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 +// Title: Validate Mailmark field lengths and values +// Description: Demonstrates how to validate Mailmark data fields against their defined capacity before generating a Mailmark barcode using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, illustrating validation of Mailmark codetext fields. It uses the MailmarkCodetext and ComplexBarcodeGenerator classes to ensure data conforms to the Mailmark specification (field lengths, numeric ranges) before barcode creation. Developers creating Mailmark barcodes commonly need to verify input data to avoid generation errors and to meet postal service requirements. +/// Prompt: Validate that customer data length does not exceed capacity for the selected Mailmark type. +/// Tags: mailmark, validation, barcode, aspose.barcode, complexbarcode, generation, csharp using System; -using System.Collections.Generic; -using System.IO; using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Example program that validates customer content length for Mailmark2D types -/// and generates corresponding barcode images. +/// Provides an example of validating Mailmark data fields and generating a Mailmark barcode. /// class Program { - // Mapping of Mailmark 2D type to maximum allowed customer content length. - private static readonly Dictionary MaxContentLengthByType = new() + /// + /// Validates Mailmark fields against their defined capacity and value ranges. + /// Throws when a field does not meet the specification. + /// + /// The instance to validate. + static void ValidateMailmark(MailmarkCodetext mailmark) { - { 7, 6 }, // Type 7: 6 characters - { 9, 45 }, // Type 9: 45 characters - { 29, 25 } // Type 29: 25 characters - }; + // Class must be a single character string. + if (mailmark.Class == null || mailmark.Class.Length != 1) + throw new ArgumentException("Class must be a single character."); + + // DestinationPostCodePlusDPS must be exactly 9 characters (including trailing spaces). + if (mailmark.DestinationPostCodePlusDPS == null || mailmark.DestinationPostCodePlusDPS.Length != 9) + throw new ArgumentException("DestinationPostCodePlusDPS must be exactly 9 characters (including trailing spaces)."); + + // ItemID must be between 0 and 99,999,999 (max 8 digits). + if (mailmark.ItemID < 0 || mailmark.ItemID > 99999999) + throw new ArgumentException("ItemID exceeds the maximum allowed value of 99,999,999."); + + // SupplychainID must be positive and not exceed 999 (covers both C and L types). + if (mailmark.SupplychainID < 0 || mailmark.SupplychainID > 999) + throw new ArgumentException("SupplychainID exceeds the maximum allowed value of 999."); + + // VersionID is typically a single digit; enforce 0‑9 range. + if (mailmark.VersionID < 0 || mailmark.VersionID > 9) + throw new ArgumentException("VersionID must be a single digit (0‑9)."); + } /// - /// Entry point. Iterates over sample records, validates content length, - /// builds Mailmark2DCodetext objects, and saves barcode images. + /// Entry point of the program. Constructs a Mailmark codetext, validates it, and generates a barcode image. /// static void Main() { - // Sample records: each tuple contains (Mailmark2D type, customer content) - var records = new List<(int Type, string Content)> + // Construct a Mailmark 4‑state codetext with sample data. + var mailmark = new MailmarkCodetext { - (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 + Format = 4, // 4‑state Mailmark + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762, + DestinationPostCodePlusDPS = "EF61AH8T " // 9 characters, trailing space required }; - int index = 1; - foreach (var (type, content) in records) + try { - try - { - // Validate that the content length is within the allowed limit for the type. - ValidateCustomerContent(content, type); + // Perform validation before barcode generation. + ValidateMailmark(mailmark); - // Build Mailmark2DCodetext with required fields and sample values. - var mailmark2d = new Mailmark2DCodetext - { - // Required fields: InformationTypeID, VersionID, Class, RTSFlag, SupplyChainID, ItemID, DestinationPostCodeAndDPS - InformationTypeID = "0", - VersionID = "1", - Class = "1", - RTSFlag = "0", - SupplyChainID = 1234567, - ItemID = 1000 + index, - DestinationPostCodeAndDPS = "EF61AH8T ", - // 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 barcode image and write it to a PNG file. - using (var generator = new ComplexBarcodeGenerator(mailmark2d)) - { - using (var ms = new MemoryStream()) - { - 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}"); - } - } - } - catch (ArgumentException ex) + // Generate the Mailmark barcode using ComplexBarcodeGenerator. + using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Handle validation errors (e.g., content too long or unsupported type). - Console.WriteLine($"Record {index}: Validation error – {ex.Message}"); + generator.Save("mailmark.png"); + Console.WriteLine("Mailmark barcode generated successfully: mailmark.png"); } - catch (Exception ex) - { - // Handle any unexpected errors during barcode generation. - Console.WriteLine($"Record {index}: Unexpected error – {ex.Message}"); - } - - index++; - } - } - - // Validates that the customer content length does not exceed the capacity for the given Mailmark type. - private static void ValidateCustomerContent(string content, int mailmarkType) - { - // Ensure the Mailmark type is supported. - if (!MaxContentLengthByType.TryGetValue(mailmarkType, out int maxLength)) - { - throw new ArgumentException($"Unsupported Mailmark type '{mailmarkType}'."); } - - // Ensure content is not null. - if (content == null) + catch (ArgumentException ex) { - throw new ArgumentException("Customer content cannot be null."); + // Output validation errors. + Console.WriteLine($"Validation error: {ex.Message}"); } - - // Ensure content length does not exceed the maximum allowed for the type. - if (content.Length > maxLength) + catch (Exception ex) { - throw new ArgumentException($"Customer content length ({content.Length}) exceeds maximum allowed ({maxLength}) for Mailmark type {mailmarkType}."); + // Handle unexpected errors gracefully. + Console.WriteLine($"Unexpected error: {ex.Message}"); } } } \ 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 5eee3c6..c89d7c8 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,94 +1,105 @@ -// 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. +// Title: Generate and verify UPC-A with GS1 Code128 coupon barcode +// Description: Demonstrates creating a UPC-A barcode combined with a GS1 Code128 coupon, then reading it back to confirm that the routing and service code values are encoded correctly. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showing how to use BarcodeGenerator with EncodeTypes.UpcaGs1Code128Coupon and BarCodeReader to validate encoded data. Typical use cases include testing barcode output for retail coupons where precise routing and service codes are required. Developers often need unit‑testable code that confirms the generated CodeText matches expected values. // 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 +// Tags: upc-a,gs1-code128,coupon,barcode-generation,barcode-recognition,unit-test,aspose.barcode using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// 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. +/// Demonstrates generation and verification of a UPC‑A with GS1 Code128 coupon barcode. /// class Program { /// - /// Entry point of the program. Executes the routing and service code verification test - /// and outputs the result to the console. + /// Entry point that runs a simple verification test for routing and service code values. /// static void Main() { - // Run the test and output the result. - bool testResult = TestRoutingAndServiceCode(); - Console.WriteLine(testResult ? "Test Passed" : "Test Failed"); - } + // Counters for total executed tests and failed tests + int totalTests = 0; + int failedTests = 0; - /// - /// 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"; + // ------------------------------------------------------------ + // Test 1: UPC-A with GS1 Code128 coupon (routing and service code) + // ------------------------------------------------------------ + totalTests++; + try + { + // Expected full code text (UPCA part + GS1 Code128 part) + string expectedCodeText = "514141100906(8102)03"; - // Combine them into the barcode text (format can be adjusted as needed). - string expectedCodeText = routingCode + serviceCode; + // Generate barcode image in memory using the specified symbology and data + using (var generator = new BarcodeGenerator(EncodeTypes.UpcaGs1Code128Coupon, expectedCodeText)) + { + using (var ms = new MemoryStream()) + { + // Save the generated barcode as PNG into the memory stream + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; // Reset stream position for reading - // Prepare a temporary file path for the generated barcode image. - string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "routing_service.png"); + // Read barcode back from the memory stream + using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes)) + { + var results = reader.ReadBarCodes(); - // Ensure any previous file is removed. - if (File.Exists(imagePath)) - { - File.Delete(imagePath); - } + // Verify that at least one barcode was detected + if (results.Length == 0) + { + Console.WriteLine("FAILED: No barcode detected."); + failedTests++; + } + else + { + // Check if any detected barcode matches the expected CodeText + bool matchFound = false; + foreach (var result in results) + { + if (result.CodeText == expectedCodeText) + { + matchFound = true; + break; + } + } - // Generate the barcode. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, expectedCodeText)) + if (matchFound) + { + Console.WriteLine("PASSED: Routing and service code values match."); + } + else + { + Console.WriteLine($"FAILED: Detected CodeText does not match. Expected '{expectedCodeText}'."); + foreach (var result in results) + { + Console.WriteLine($" Detected: '{result.CodeText}'"); + } + failedTests++; + } + } + } + } + } + } + catch (Exception ex) { - // Optional: set image size via AutoSizeMode.Interpolation to avoid manual dimensions. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - - // Save the barcode image. - generator.Save(imagePath); + // Report any unexpected exceptions as test failures + Console.WriteLine($"FAILED: Exception occurred - {ex.Message}"); + failedTests++; } - // Verify that the file was created. - if (!File.Exists(imagePath)) + // ------------------------------------------------------------ + // Summary of test results + // ------------------------------------------------------------ + if (failedTests == 0) { - Console.WriteLine("Failed to create barcode image."); - return false; + Console.WriteLine($"ALL TESTS PASSED: {totalTests} tests executed."); } - - // Read the barcode back and compare the decoded text. - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + else { - 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; - } - } + Console.WriteLine($"FAILED: {failedTests} out of {totalTests} tests failed."); } - - // If no barcode was read, the test fails. - Console.WriteLine("No barcode detected in the image."); - return false; } } \ No newline at end of file