diff --git a/maxicode-barcode/apply-custom-background-color-to-maxicode-barcode-and-verify-that-decoding-remains-successful.cs b/maxicode-barcode/apply-custom-background-color-to-maxicode-barcode-and-verify-that-decoding-remains-successful.cs
index 6be5c23..4b97679 100644
--- a/maxicode-barcode/apply-custom-background-color-to-maxicode-barcode-and-verify-that-decoding-remains-successful.cs
+++ b/maxicode-barcode/apply-custom-background-color-to-maxicode-barcode-and-verify-that-decoding-remains-successful.cs
@@ -1,86 +1,95 @@
+// Title: Custom Background Color for MaxiCode Barcode
+// Description: Demonstrates applying a custom background color to a MaxiCode barcode and confirming that it can still be decoded correctly.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, focusing on MaxiCode symbology. It showcases the use of ComplexBarcodeGenerator to create a MaxiCode with custom visual settings, and BarCodeReader with ComplexCodetextReader to decode the generated image. Developers working with shipping, logistics, or inventory systems often need to customize barcode appearance while ensuring reliable scanning.
+// Prompt: Apply a custom background color to a MaxiCode barcode and verify that decoding remains successful.
+// Tags: maxicode, background color, barcode generation, barcode recognition, aspose.barcode, c#
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
using Aspose.Drawing;
///
-/// Demonstrates generation and decoding of a MaxiCode barcode using Aspose.BarCode.
+/// Generates a MaxiCode barcode with a custom background color,
+/// saves it as an image, and verifies that the barcode can be decoded successfully.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a MaxiCode (Mode 2) with a custom background, saves it to a memory stream,
- /// and then reads/decodes the barcode from that stream.
+ /// Entry point of the example. Creates a MaxiCode with a light‑yellow background,
+ /// writes it to a PNG file, and then reads the file back to confirm decoding.
///
static void Main()
{
- // ------------------------------------------------------------
- // Prepare MaxiCode codetext (Mode 2 with a standard second message)
- // ------------------------------------------------------------
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // Define the output file name.
+ string outputPath = "maxicode.png";
+
+ // Prepare MaxiCode codetext (Mode 2 example) with postal code, country code, and service category.
+ var maxiCode = new MaxiCodeCodetextMode2
{
- PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // USA
- ServiceCategory = 999
+ PostalCode = "524032140", // 9‑digit US postal code
+ CountryCode = 56, // USA
+ ServiceCategory = 999 // Example service category
};
- // Create the optional second message for the MaxiCode
+ // Add a second message to the MaxiCode.
var secondMessage = new MaxiCodeStandardSecondMessage
{
Message = "Sample MaxiCode"
};
- maxiCodeCodetext.SecondMessage = secondMessage;
+ maxiCode.SecondMessage = secondMessage;
+
+ // Generate the MaxiCode barcode with a custom background color.
+ using (var complexGenerator = new ComplexBarcodeGenerator(maxiCode))
+ {
+ // Set background to light yellow (RGB 255,255,224).
+ complexGenerator.Parameters.BackColor = Aspose.Drawing.Color.FromArgb(255, 255, 224);
+
+ // Create the barcode image.
+ using (var bitmap = complexGenerator.GenerateBarCodeImage())
+ {
+ // Save the image as PNG.
+ bitmap.Save(outputPath, Aspose.Drawing.Imaging.ImageFormat.Png);
+ }
+ }
- // ------------------------------------------------------------
- // Generate the barcode with a custom background color
- // ------------------------------------------------------------
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Verify that the image file was created.
+ if (!File.Exists(outputPath))
{
- // Set a custom background (e.g., light yellow)
- generator.Parameters.BackColor = Color.FromArgb(255, 255, 224); // LightYellow
+ Console.WriteLine("Failed to create barcode image.");
+ return;
+ }
- // --------------------------------------------------------
- // Save the generated barcode to a memory stream in PNG format
- // --------------------------------------------------------
- using (var ms = new MemoryStream())
+ // Read and decode the generated MaxiCode barcode.
+ using (var reader = new BarCodeReader(outputPath, DecodeType.MaxiCode))
+ {
+ foreach (var result in reader.ReadBarCodes())
{
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading
+ // Decode the raw codetext using the appropriate MaxiCode mode.
+ var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
+ result.Extended.MaxiCode.MaxiCodeMode,
+ result.CodeText);
- // --------------------------------------------------------
- // Read and decode the barcode from the generated image stream
- // --------------------------------------------------------
- using (var reader = new BarCodeReader(ms, DecodeType.MaxiCode))
+ // Check if decoding produced the expected Mode 2 codetext.
+ if (decoded is MaxiCodeCodetextMode2 decodedMode2)
{
- var results = reader.ReadBarCodes();
+ Console.WriteLine("Decoding successful:");
+ Console.WriteLine($"Postal Code: {decodedMode2.PostalCode}");
+ Console.WriteLine($"Country Code: {decodedMode2.CountryCode}");
+ Console.WriteLine($"Service Category: {decodedMode2.ServiceCategory}");
- // Check if any barcodes were detected
- if (results.Length == 0)
+ // Output the second message if present.
+ if (decodedMode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
{
- Console.WriteLine("No barcode detected.");
- }
- else
- {
- // Iterate through all detected barcodes
- foreach (var result in results)
- {
- // Verify that decoding succeeded (non‑empty CodeText)
- if (!string.IsNullOrEmpty(result.CodeText))
- {
- Console.WriteLine("Decoding successful.");
- Console.WriteLine("Decoded CodeText: " + result.CodeText);
- }
- else
- {
- Console.WriteLine("Decoding failed: empty CodeText.");
- }
- }
+ Console.WriteLine($"Message: {stdMsg.Message}");
}
}
+ else
+ {
+ Console.WriteLine("Decoding failed or unexpected codetext type.");
+ }
}
}
}
diff --git a/maxicode-barcode/apply-custom-foreground-color-to-maxicode-mode-2-barcode-using-generator-s-forecolor-property.cs b/maxicode-barcode/apply-custom-foreground-color-to-maxicode-mode-2-barcode-using-generator-s-forecolor-property.cs
index 29a9f18..dd9ba8b 100644
--- a/maxicode-barcode/apply-custom-foreground-color-to-maxicode-mode-2-barcode-using-generator-s-forecolor-property.cs
+++ b/maxicode-barcode/apply-custom-foreground-color-to-maxicode-mode-2-barcode-using-generator-s-forecolor-property.cs
@@ -1,48 +1,57 @@
+// Title: Apply custom foreground color to a MaxiCode Mode 2 barcode
+// Description: This example creates a MaxiCode Mode 2 barcode, sets a custom bar (foreground) color, and saves it as a PNG image. It demonstrates how to customize the visual appearance of complex barcodes using Aspose.BarCode.
+// Category-Description: The sample belongs to the Aspose.BarCode complex barcode generation category, where developers work with multi‑message symbologies such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related parameter classes to configure barcode data and appearance. Typical scenarios include shipping labels, parcel tracking, and logistics applications that require colored MaxiCode symbols.
+// Prompt: Apply a custom foreground color to a MaxiCode Mode 2 barcode using the generator's ForeColor property.
+// Tags: maxicode, color, generation, png, aspose.barcode, complexbarcodegenerator, barcode
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation of a MaxiCode Mode 2 barcode using Aspose.BarCode.
+/// Demonstrates applying a custom foreground color to a MaxiCode Mode 2 barcode and saving it as PNG.
///
class Program
{
///
- /// Entry point of the application. Creates a MaxiCode codetext, configures the generator,
- /// and saves the resulting barcode image to a file.
+ /// Entry point that builds the MaxiCode data, configures the barcode color, generates the image, and writes it to disk.
///
static void Main()
{
- // Initialize MaxiCode codetext for Mode 2 with required fields.
- var maxiCode = new MaxiCodeCodetextMode2
+ // Prepare MaxiCode Mode 2 codetext with required fields
+ var maxiCodeCodetext = new MaxiCodeCodetextMode2
{
- PostalCode = "524032140", // 9‑digit postal code
- CountryCode = 56, // Numeric country identifier
- ServiceCategory = 999 // Service category value
+ PostalCode = "524032140", // 9‑digit US postal code
+ CountryCode = 56, // USA numeric country code
+ ServiceCategory = 999 // Example service category
};
- // Create the optional second message and assign it to the codetext.
+ // Create and assign the standard second message
var secondMessage = new MaxiCodeStandardSecondMessage
{
- Message = "Test message"
+ Message = "Sample MaxiCode"
};
- maxiCode.SecondMessage = secondMessage;
+ maxiCodeCodetext.SecondMessage = secondMessage;
- // Use ComplexBarcodeGenerator to render the MaxiCode barcode.
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ // Initialize the generator with the prepared codetext
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Set the color of the barcode bars (foreground). No ForeColor property exists.
- generator.Parameters.Barcode.BarColor = Color.Red;
+ // Set a custom foreground (bar) color for the barcode
+ generator.Parameters.Barcode.BarColor = Color.Blue;
+
+ // Generate the barcode image in memory
+ generator.GenerateBarCodeImage();
- // Define output file name and format, then save the image.
- string outputPath = "maxicode_mode2.png";
+ // Define output file path and save the image as PNG
+ const string outputPath = "maxicode_mode2.png";
generator.Save(outputPath, BarCodeImageFormat.Png);
- // Output the full path of the saved file for verification.
- Console.WriteLine($"Barcode saved to: {Path.GetFullPath(outputPath)}");
+ // Inform the user where the file was saved
+ Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}");
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/batch-decode-all-maxicode-png-files-in-directory-and-export-results-to-csv-report.cs b/maxicode-barcode/batch-decode-all-maxicode-png-files-in-directory-and-export-results-to-csv-report.cs
index ffda027..c68e339 100644
--- a/maxicode-barcode/batch-decode-all-maxicode-png-files-in-directory-and-export-results-to-csv-report.cs
+++ b/maxicode-barcode/batch-decode-all-maxicode-png-files-in-directory-and-export-results-to-csv-report.cs
@@ -1,179 +1,151 @@
+// Title: Batch decode MaxiCode PNG files to CSV
+// Description: Demonstrates how to read multiple MaxiCode barcodes from PNG images in a folder and export the decoded information to a CSV report.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on batch processing of MaxiCode symbology. It showcases the use of BarCodeReader, DecodeType.MaxiCode, QualitySettings, and ComplexCodetextReader to extract structured data such as postal code, country code, and service category, then writes results to a CSV file. Developers working with bulk barcode decoding, logistics, or shipping label processing can use this pattern for automated data extraction.
+// Prompt: Batch decode all MaxiCode PNG files in a directory and export the results to a CSV report.
+// Tags: maxicode, barcode, batch processing, csv, aspose.barcode, decoding, recognition, complexcodetext
+
using System;
using System.IO;
-using System.Text;
using System.Collections.Generic;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
///
-/// Entry point for the MaxiCode decoding utility.
-/// Scans a folder for PNG images, attempts to read MaxiCode barcodes,
-/// and generates a CSV report with extracted information.
+/// Provides a console application that batch decodes MaxiCode barcodes from PNG files
+/// and writes the extracted information to a CSV report.
///
class Program
{
///
- /// Main method executed by the runtime.
- /// Accepts an optional command‑line argument specifying the input folder.
+ /// Entry point of the application.
///
- /// Command‑line arguments; first argument is the input folder path.
+ ///
+ /// Optional command‑line arguments:
+ /// args[0] – input folder path (default: "Input"),
+ /// args[1] – output CSV file path (default: "MaxiCodeReport.csv").
+ ///
static void Main(string[] args)
{
- // Determine input folder: use first argument if supplied, otherwise default to "MaxiCodeImages".
- string inputFolder = args.Length > 0 ? args[0] : "MaxiCodeImages";
-
- // Path for the generated CSV report.
- string csvPath = "MaxiCodeReport.csv";
+ // Resolve input folder and output CSV path from arguments or use defaults.
+ string inputFolder = args.Length > 0 ? args[0] : "Input";
+ string outputCsv = args.Length > 1 ? args[1] : "MaxiCodeReport.csv";
- // Ensure the input folder exists; create it if missing and exit.
+ // Ensure the input folder exists; create it if missing.
if (!Directory.Exists(inputFolder))
{
- Console.WriteLine($"Input folder \"{inputFolder}\" does not exist. Creating it.");
Directory.CreateDirectory(inputFolder);
- Console.WriteLine("Place PNG files to decode in the folder and rerun the program.");
- return;
}
- // StringBuilder to accumulate CSV lines.
- var sb = new StringBuilder();
+ // Retrieve all PNG files from the input directory.
+ string[] pngFiles = Directory.GetFiles(inputFolder, "*.png");
- // Write CSV header.
- sb.AppendLine("FileName,BarcodeType,CodeText,Mode,PostalCode,CountryCode,ServiceCategory,SecondMessage");
+ // Limit processing to a maximum of 10 files as a safety guideline.
+ int maxFiles = Math.Min(pngFiles.Length, 10);
- // Retrieve all PNG files from the input folder.
- string[] pngFiles = Directory.GetFiles(inputFolder, "*.png");
- if (pngFiles.Length == 0)
+ // Open a StreamWriter for the CSV report.
+ using (var writer = new StreamWriter(outputCsv, false))
{
- Console.WriteLine($"No PNG files found in \"{inputFolder}\".");
- }
+ // Write the CSV header line.
+ writer.WriteLine("FileName,CodeText,PostalCode,CountryCode,ServiceCategory,Message");
- // Process each PNG file individually.
- foreach (string filePath in pngFiles)
- {
- try
+ // Process each PNG file up to the defined limit.
+ for (int i = 0; i < maxFiles; i++)
{
- // Open the image file as a read‑only stream.
- using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
+ string filePath = pngFiles[i];
+ string fileName = Path.GetFileName(filePath);
+
+ // Guard against missing files (should not happen after GetFiles).
+ if (!File.Exists(filePath))
{
- // Initialize the barcode reader for MaxiCode type.
- using (var reader = new BarCodeReader(fileStream, DecodeType.MaxiCode))
+ Console.WriteLine($"File not found: {filePath}");
+ continue;
+ }
+
+ // Initialize a BarCodeReader for MaxiCode decoding.
+ using (var reader = new BarCodeReader(filePath, DecodeType.MaxiCode))
+ {
+ // Apply the highest quality settings to improve detection accuracy.
+ reader.QualitySettings = QualitySettings.MaxQuality;
+
+ // Read all barcodes present in the image.
+ BarCodeResult[] results = reader.ReadBarCodes();
+
+ // If no barcodes were found, write an empty record and continue.
+ if (results.Length == 0)
{
- // Attempt to read all barcodes in the image.
- var results = reader.ReadBarCodes();
+ writer.WriteLine($"{Escape(fileName)},,,,,");
- // If no barcodes were detected, record this in the CSV.
- if (results.Length == 0)
- {
- sb.AppendLine($"{EscapeCsv(Path.GetFileName(filePath))},,,No barcode found,,,,,");
- continue;
- }
+ continue;
+ }
- // Iterate over each detected barcode result.
- foreach (var result in results)
+ // Process each detected barcode.
+ foreach (var result in results)
+ {
+ // Retrieve raw codetext; ensure it's not null.
+ string rawCodeText = result.CodeText ?? string.Empty;
+
+ // Decode the structured MaxiCode codetext.
+ MaxiCodeCodetext decoded = ComplexCodetextReader.TryDecodeMaxiCode(
+ result.Extended.MaxiCode.MaxiCodeMode,
+ rawCodeText);
+
+ // Initialize fields with default empty values.
+ string postal = string.Empty;
+ string country = string.Empty;
+ string service = string.Empty;
+ string message = string.Empty;
+
+ // Extract details for Mode 2 MaxiCode.
+ if (decoded is MaxiCodeCodetextMode2 mode2)
{
- // Basic barcode properties.
- string barcodeType = result.CodeTypeName ?? "";
- string codeText = result.CodeText ?? "";
- string modeStr = "";
- string postalCode = "";
- string countryCode = "";
- string serviceCategory = "";
- string secondMessage = "";
-
- // Attempt to extract MaxiCode‑specific extended data.
- var maxiCodeExt = result.Extended?.MaxiCode;
- if (maxiCodeExt != null)
+ postal = mode2.PostalCode ?? string.Empty;
+ country = mode2.CountryCode.ToString();
+ service = mode2.ServiceCategory.ToString();
+
+ if (mode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
{
- // Record the MaxiCode mode (e.g., 2, 3, 4, 5, 6).
- modeStr = maxiCodeExt.Mode.ToString();
-
- // Decode the structured codetext based on the mode.
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(maxiCodeExt.Mode, codeText);
-
- // Handle Mode 2 decoding.
- if (decoded is MaxiCodeCodetextMode2 mode2)
- {
- postalCode = mode2.PostalCode ?? "";
- countryCode = mode2.CountryCode.ToString();
- serviceCategory = mode2.ServiceCategory.ToString();
-
- // Extract second message, which may be standard or structured.
- if (mode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
- {
- secondMessage = stdMsg.Message ?? "";
- }
- else if (mode2.SecondMessage is MaxiCodeStructuredSecondMessage structMsg)
- {
- var parts = new List();
- foreach (var id in structMsg.Identifiers)
- parts.Add(id);
- parts.Add($"Year:{structMsg.Year}");
- secondMessage = string.Join(" | ", parts);
- }
- }
- // Handle Mode 3 decoding (similar structure to Mode 2).
- else if (decoded is MaxiCodeCodetextMode3 mode3)
- {
- postalCode = mode3.PostalCode ?? "";
- countryCode = mode3.CountryCode.ToString();
- serviceCategory = mode3.ServiceCategory.ToString();
-
- if (mode3.SecondMessage is MaxiCodeStandardSecondMessage stdMsg3)
- {
- secondMessage = stdMsg3.Message ?? "";
- }
- else if (mode3.SecondMessage is MaxiCodeStructuredSecondMessage structMsg3)
- {
- var parts = new List();
- foreach (var id in structMsg3.Identifiers)
- parts.Add(id);
- parts.Add($"Year:{structMsg3.Year}");
- secondMessage = string.Join(" | ", parts);
- }
- }
+ message = stdMsg.Message ?? string.Empty;
}
+ else if (mode2.SecondMessage is MaxiCodeStructuredSecondMessage structMsg)
+ {
+ // Concatenate identifiers from the structured message.
+ message = string.Join(" | ", structMsg.Identifiers);
+ }
+ }
+ // Extract details for Mode 3 MaxiCode.
+ else if (decoded is MaxiCodeCodetextMode3 mode3)
+ {
+ postal = mode3.PostalCode ?? string.Empty;
+ country = mode3.CountryCode.ToString();
+ service = mode3.ServiceCategory.ToString();
- // Append a CSV line with all extracted fields, escaping as needed.
- sb.AppendLine($"{EscapeCsv(Path.GetFileName(filePath))},{EscapeCsv(barcodeType)},{EscapeCsv(codeText)},{EscapeCsv(modeStr)},{EscapeCsv(postalCode)},{EscapeCsv(countryCode)},{EscapeCsv(serviceCategory)},{EscapeCsv(secondMessage)}");
+ if (mode3.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
+ {
+ message = stdMsg.Message ?? string.Empty;
+ }
+ else if (mode3.SecondMessage is MaxiCodeStructuredSecondMessage structMsg)
+ {
+ message = string.Join(" | ", structMsg.Identifiers);
+ }
}
+ // For other MaxiCode modes, fields remain empty.
+
+ // Write the CSV line, escaping commas where necessary.
+ writer.WriteLine($"{Escape(fileName)},{Escape(rawCodeText)},{Escape(postal)},{Escape(country)},{Escape(service)},{Escape(message)}");
}
}
}
- catch (Exception ex)
- {
- // Log any exception that occurs while processing a file and record it in the CSV.
- Console.WriteLine($"Error processing file \"{filePath}\": {ex.Message}");
- sb.AppendLine($"{EscapeCsv(Path.GetFileName(filePath))},Error,,{EscapeCsv(ex.Message)},,,,,");
- }
}
- // Attempt to write the accumulated CSV content to disk.
- try
- {
- File.WriteAllText(csvPath, sb.ToString(), Encoding.UTF8);
- Console.WriteLine($"CSV report generated at \"{csvPath}\".");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Failed to write CSV file: {ex.Message}");
- }
+ Console.WriteLine($"Decoding completed. Report saved to '{outputCsv}'.");
}
///
- /// Escapes a CSV field by surrounding it with quotes if it contains
- /// commas, quotes, or line‑break characters, and doubles any internal quotes.
+ /// Escapes a CSV field by surrounding it with double quotes if it contains a comma,
+ /// and doubles any existing double quotes.
///
- /// The field value to escape; may be null.
- /// A CSV‑safe representation of the field.
- static string EscapeCsv(string field)
- {
- if (field == null)
- return "";
- if (field.Contains("\""))
- field = field.Replace("\"", "\"\"");
- if (field.Contains(",") || field.Contains("\"") || field.Contains("\n") || field.Contains("\r"))
- return $"\"{field}\"";
- return field;
- }
+ /// The field value to escape.
+ /// The escaped field value.
+ private static string Escape(string s) => s.Contains(",") ? $"\"{s.Replace("\"", "\"\"")}\"" : s;
}
\ No newline at end of file
diff --git a/maxicode-barcode/configure-barcodereader-to-decode-maxicode-images-from-byte-array-and-retrieve-both-primary-and-secondary-messages.cs b/maxicode-barcode/configure-barcodereader-to-decode-maxicode-images-from-byte-array-and-retrieve-both-primary-and-secondary-messages.cs
index e78d35f..5162218 100644
--- a/maxicode-barcode/configure-barcodereader-to-decode-maxicode-images-from-byte-array-and-retrieve-both-primary-and-secondary-messages.cs
+++ b/maxicode-barcode/configure-barcodereader-to-decode-maxicode-images-from-byte-array-and-retrieve-both-primary-and-secondary-messages.cs
@@ -1,97 +1,115 @@
+// Title: Decode MaxiCode from Byte Array and Retrieve Primary & Secondary Messages
+// Description: Demonstrates how to generate a MaxiCode (Mode 2), save it to a memory stream, and use BarCodeReader to decode the image from a byte array, extracting both primary and secondary message data.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation and recognition category. It showcases the use of ComplexBarcodeGenerator for creating MaxiCode symbols and BarCodeReader for decoding them. Developers working with logistics, shipping, or retail often need to encode and decode MaxiCode data, including structured primary and secondary messages, using the MaxiCodeCodetextMode2, MaxiCodeStandardSecondMessage, and related API classes.
+// Prompt: Configure BarcodeReader to decode MaxiCode images from a byte array and retrieve both primary and secondary messages.
+// Tags: maxicode, barcode decoding, byte array, complex barcode, aspose.barcode, c#
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates creation, encoding, and decoding of a MaxiCode (Mode 2) using Aspose.BarCode.
+/// Example program that generates a MaxiCode (Mode 2), stores it in a memory stream,
+/// and decodes it using to retrieve both primary and secondary messages.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a MaxiCode barcode, saves it to a memory stream, and then reads it back.
+ /// Entry point of the example. Generates a MaxiCode, writes it to a PNG stream,
+ /// and reads the barcode back, printing decoded information to the console.
///
static void Main()
{
// ------------------------------------------------------------
- // 1. Build the MaxiCode data structure (primary and secondary messages)
+ // 1. Create a MaxiCode codetext (Mode 2) with a standard secondary message.
// ------------------------------------------------------------
- var maxiCode = new MaxiCodeCodetextMode2
+ var maxiCodeCodetext = new MaxiCodeCodetextMode2
{
- PostalCode = "524032140", // 9‑digit postal code
- CountryCode = 56, // Numeric country identifier
- ServiceCategory = 999 // Service category value
+ PostalCode = "524032140", // 9‑digit US postal code
+ CountryCode = 56, // Country code
+ ServiceCategory = 999 // Service category
};
var secondMessage = new MaxiCodeStandardSecondMessage
{
- Message = "Hello World" // Simple textual secondary message
+ Message = "Sample secondary message"
};
- maxiCode.SecondMessage = secondMessage;
+ maxiCodeCodetext.SecondMessage = secondMessage;
// ------------------------------------------------------------
- // 2. Generate the barcode image and store it in a memory stream
+ // 2. Generate the barcode image using ComplexBarcodeGenerator.
// ------------------------------------------------------------
- using (var imageStream = new MemoryStream())
+ using (var complexGenerator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Create a generator for the complex barcode (MaxiCode)
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
- {
- // Save the generated barcode as PNG (evaluation mode supports PNG)
- generator.Save(imageStream, BarCodeImageFormat.Png);
- }
-
- // Reset stream position to the beginning for reading
- imageStream.Position = 0;
-
- // ------------------------------------------------------------
- // 3. Decode the barcode from the memory stream
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(imageStream, DecodeType.MaxiCode))
+ // Generate the barcode as a bitmap.
+ using (var bitmap = complexGenerator.GenerateBarCodeImage())
{
- // Iterate through all detected barcodes (should be only one)
- foreach (var result in reader.ReadBarCodes())
+ // Save the bitmap to a memory stream in PNG format.
+ using (var imageStream = new MemoryStream())
{
- // Attempt to decode the complex MaxiCode codetext into a strongly‑typed object
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
+ bitmap.Save(imageStream, ImageFormat.Png);
+ imageStream.Position = 0; // Reset stream position for reading.
- // Verify that the decoded object is of the expected Mode 2 type
- if (decoded is MaxiCodeCodetextMode2 mode2)
+ // ------------------------------------------------------------
+ // 3. Decode the MaxiCode from the byte array (memory stream).
+ // ------------------------------------------------------------
+ using (var reader = new BarCodeReader())
{
- // Output primary message fields
- Console.WriteLine("=== Primary Message ===");
- Console.WriteLine($"Postal Code : {mode2.PostalCode}");
- Console.WriteLine($"Country Code : {mode2.CountryCode}");
- Console.WriteLine($"Service Category : {mode2.ServiceCategory}");
+ // Set the image source for the reader.
+ reader.SetBarCodeImage(imageStream);
- // Output secondary message based on its concrete type
- Console.WriteLine("=== Secondary Message ===");
- if (mode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
- {
- Console.WriteLine($"Message: {stdMsg.Message}");
- }
- else if (mode2.SecondMessage is MaxiCodeStructuredSecondMessage structMsg)
+ // Restrict decoding to MaxiCode symbols only.
+ reader.BarCodeReadType = DecodeType.MaxiCode;
+
+ // Iterate through all detected barcodes.
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine("Identifiers:");
- foreach (var id in structMsg.Identifiers)
+ Console.WriteLine($"Detected barcode type: {result.CodeTypeName}");
+ Console.WriteLine($"Raw CodeText: {result.CodeText}");
+
+ // Decode the complex codetext to obtain structured data.
+ var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
+ result.Extended.MaxiCode.MaxiCodeMode,
+ result.CodeText);
+
+ // --------------------------------------------------------
+ // 4. Process decoded data for Mode 2 (primary & secondary messages).
+ // --------------------------------------------------------
+ if (decoded is MaxiCodeCodetextMode2 mode2)
{
- Console.WriteLine($" - {id}");
+ Console.WriteLine("=== Primary Message ===");
+ Console.WriteLine($"Postal Code: {mode2.PostalCode}");
+ Console.WriteLine($"Country Code: {mode2.CountryCode}");
+ Console.WriteLine($"Service Category: {mode2.ServiceCategory}");
+
+ Console.WriteLine("=== Secondary Message ===");
+ if (mode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
+ {
+ Console.WriteLine($"Message: {stdMsg.Message}");
+ }
+ else if (mode2.SecondMessage is MaxiCodeStructuredSecondMessage structMsg)
+ {
+ Console.WriteLine("Identifiers:");
+ foreach (var id in structMsg.Identifiers)
+ {
+ Console.WriteLine($" {id}");
+ }
+ Console.WriteLine($"Year: {structMsg.Year}");
+ }
+ }
+ else if (decoded is MaxiCodeCodetextMode3 mode3)
+ {
+ // Handling for Mode 3 can be added here if required.
+ Console.WriteLine("Decoded as MaxiCode Mode 3 (not shown in this sample).");
+ }
+ else
+ {
+ Console.WriteLine("Unable to decode MaxiCode complex codetext.");
}
}
- else
- {
- Console.WriteLine("No secondary message found.");
- }
- }
- else
- {
- // Decoding failed or returned an unexpected type
- Console.WriteLine("Failed to decode MaxiCode codetext.");
}
}
}
diff --git a/maxicode-barcode/configure-barcodereader-to-ignore-checksum-errors-while-decoding-maxicode-barcodes-in-high-noise-environment.cs b/maxicode-barcode/configure-barcodereader-to-ignore-checksum-errors-while-decoding-maxicode-barcodes-in-high-noise-environment.cs
index 89efd77..9d8ccb6 100644
--- a/maxicode-barcode/configure-barcodereader-to-ignore-checksum-errors-while-decoding-maxicode-barcodes-in-high-noise-environment.cs
+++ b/maxicode-barcode/configure-barcodereader-to-ignore-checksum-errors-while-decoding-maxicode-barcodes-in-high-noise-environment.cs
@@ -1,49 +1,75 @@
+// Title: Decode MaxiCode with checksum errors ignored
+// Description: Demonstrates configuring BarCodeReader to ignore checksum validation while decoding MaxiCode barcodes in noisy images.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on error‑tolerant decoding. It shows how to use BarCodeReader, QualitySettings, and BarcodeSettings to handle damaged or high‑noise MaxiCode symbols, a common requirement for logistics and shipping applications where barcode integrity may be compromised.
+// Prompt: Configure BarcodeReader to ignore checksum errors while decoding MaxiCode barcodes in a high‑noise environment.
+// Tags: maxicode, checksum, ignore, barcodereader, qualitysettings, barcodesettings, decoding, aspose.barcode
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation and recognition of a MaxiCode barcode using Aspose.BarCode.
+/// Demonstrates configuring the BarCodeReader to ignore checksum errors when decoding MaxiCode barcodes,
+/// useful in high‑noise environments.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a MaxiCode barcode, stores it in memory, and then reads it back.
+ /// Entry point of the example. Generates a MaxiCode image, then reads it while allowing incorrect checksums.
///
static void Main()
{
- // Create an in‑memory stream to hold the generated barcode image.
- using (var imageStream = new MemoryStream())
+ // Create a simple MaxiCode codetext (Mode4 with a short message)
+ var maxiCodeCodetext = new MaxiCodeStandardCodetext
{
- // Generate a MaxiCode barcode with the specified data.
- using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, "123456789012"))
- {
- // Save the generated barcode as a PNG image into the memory stream.
- generator.Save(imageStream, BarCodeImageFormat.Png);
- }
-
- // Reset the stream position to the beginning before reading.
- imageStream.Position = 0;
+ Mode = MaxiCodeMode.Mode4,
+ Message = "Test"
+ };
- // Initialize a barcode reader configured for MaxiCode symbology.
- using (var reader = new BarCodeReader(imageStream, DecodeType.MaxiCode))
+ // Generate the MaxiCode image using ComplexBarcodeGenerator
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ {
+ // Generate bitmap representation of the barcode
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
- // Disable checksum validation to tolerate noisy or damaged barcodes.
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Off;
+ // Save bitmap to a memory stream in PNG format
+ using (var imageStream = new MemoryStream())
+ {
+ bitmap.Save(imageStream, ImageFormat.Png);
+ imageStream.Position = 0; // Reset stream position for reading
- // Use high‑quality settings to improve detection of damaged barcodes.
- reader.QualitySettings = QualitySettings.HighQuality;
+ // Initialize BarCodeReader for MaxiCode with high-quality settings
+ using (var reader = new BarCodeReader(imageStream, DecodeType.MaxiCode))
+ {
+ // Allow recognition of barcodes with incorrect checksum or damaged data
+ reader.QualitySettings.AllowIncorrectBarcodes = true;
- // Allow recognition of barcodes even if their checksums are incorrect.
- reader.QualitySettings.AllowIncorrectBarcodes = true;
+ // Disable checksum validation (reinforces ignoring checksum errors)
+ reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Off;
- // Read all barcodes from the stream and output their text.
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected MaxiCode: {result.CodeText}");
+ // Read barcodes from the image
+ BarCodeResult[] results = reader.ReadBarCodes();
+
+ if (results.Length == 0)
+ {
+ Console.WriteLine("No MaxiCode barcode detected.");
+ }
+ else
+ {
+ // Output details of each detected barcode
+ foreach (var result in results)
+ {
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
+ Console.WriteLine($"Confidence: {result.Confidence}");
+ Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
+ }
+ }
+ }
}
}
}
diff --git a/maxicode-barcode/create-aspnet-mvc-action-that-returns-generated-maxicode-barcode-image-based-on-query-string-parameters.cs b/maxicode-barcode/create-aspnet-mvc-action-that-returns-generated-maxicode-barcode-image-based-on-query-string-parameters.cs
index 81ba5b4..73d8ef8 100644
--- a/maxicode-barcode/create-aspnet-mvc-action-that-returns-generated-maxicode-barcode-image-based-on-query-string-parameters.cs
+++ b/maxicode-barcode/create-aspnet-mvc-action-that-returns-generated-maxicode-barcode-image-based-on-query-string-parameters.cs
@@ -1,3 +1,9 @@
+// Title: Generate MaxiCode Barcode in ASP.NET MVC Action
+// Description: Demonstrates creating a MaxiCode barcode image using Aspose.BarCode based on query string parameters.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator together with MaxiCode codetext classes (MaxiCodeCodetextMode2, MaxiCodeCodetextMode3, MaxiCodeStandardCodetext) to produce PNG images. Typical scenarios include shipping labels, parcel tracking, and logistics applications where MaxiCode is required. Developers often need to build MVC actions that return barcode images directly to the client, and this snippet illustrates the core API calls and parameter handling.
+// Prompt: Create an ASP.NET MVC action that returns a generated MaxiCode barcode image based on query string parameters.
+// Tags: maxicode, barcode, generation, aspnet mvc, image, png, aspose.barcode, complexbarcode
+
using System;
using System.IO;
using Aspose.BarCode;
@@ -5,70 +11,60 @@
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation of MaxiCode barcodes using Aspose.BarCode.
-/// Accepts optional command‑line arguments to customize the barcode data.
+/// Console program that mimics an ASP.NET MVC action for generating a MaxiCode barcode image.
+/// In a real MVC controller the logic would be placed inside an action method returning a FileResult.
///
class Program
{
///
- /// Entry point of the application.
- /// Parses command‑line arguments, builds the appropriate complex codetext,
- /// and outputs a Base64‑encoded PNG image of the generated MaxiCode barcode.
+ /// Entry point that parses parameters, builds the appropriate MaxiCode codetext,
+ /// generates the barcode image, and saves it as a PNG file.
///
- ///
- /// Optional arguments:
- /// 0 – mode (int, 2‑6),
- /// 1 – postal code (string),
- /// 2 – country code (int),
- /// 3 – service category (int),
- /// 4 – second message (string).
- ///
+ /// Command‑line arguments used as stand‑in for query string values.
static void Main(string[] args)
{
// --------------------------------------------------------------------
- // Default values for demonstration (used when no command‑line args)
+ // Default parameters (used when not enough command‑line arguments are supplied)
// --------------------------------------------------------------------
- int mode = 2; // MaxiCode mode (2‑6)
+ int mode = 2; // MaxiCode mode (2,3,4,5,6)
string postalCode = "524032140"; // 9‑digit for mode 2, 6‑char for mode 3
int countryCode = 56; // 3‑digit numeric country code
int serviceCategory = 999; // 3‑digit service category
- string message = "Test message"; // Second message (standard)
+ string message = "Sample message"; // Standard second message
// --------------------------------------------------------------------
- // Parse command‑line arguments if they are provided
+ // Parse command‑line arguments if provided (simulating query string)
+ // Expected order: mode postalCode countryCode serviceCategory message
// --------------------------------------------------------------------
- if (args.Length >= 1 && int.TryParse(args[0], out int parsedMode))
- mode = parsedMode;
-
- if (args.Length >= 2)
- postalCode = args[1];
-
- if (args.Length >= 3 && int.TryParse(args[2], out int parsedCountry))
- countryCode = parsedCountry;
-
- if (args.Length >= 4 && int.TryParse(args[3], out int parsedService))
- serviceCategory = parsedService;
-
- if (args.Length >= 5)
- message = args[4];
+ try
+ {
+ if (args.Length > 0) mode = int.Parse(args[0]);
+ if (args.Length > 1) postalCode = args[1];
+ if (args.Length > 2) countryCode = int.Parse(args[2]);
+ if (args.Length > 3) serviceCategory = int.Parse(args[3]);
+ if (args.Length > 4) message = args[4];
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Argument parsing error: {ex.Message}");
+ Console.WriteLine("Using default values.");
+ }
// --------------------------------------------------------------------
- // Validate the selected mode (only 2‑6 are supported)
+ // Validate the requested MaxiCode mode
// --------------------------------------------------------------------
if (mode < 2 || mode > 6)
{
- Console.WriteLine("Invalid MaxiCode mode. Supported values are 2 to 6.");
+ Console.WriteLine("Invalid MaxiCode mode. Supported values are 2,3,4,5,6.");
return;
}
// --------------------------------------------------------------------
- // Build the appropriate complex codetext object based on the mode
+ // Build the appropriate codetext object based on the selected mode
// --------------------------------------------------------------------
- IComplexCodetext complexCodetext;
-
+ IComplexCodetext codetext;
if (mode == 2)
{
- // Mode 2 includes postal code, country code, service category, and a second message
var ct = new MaxiCodeCodetextMode2
{
PostalCode = postalCode,
@@ -76,11 +72,10 @@ static void Main(string[] args)
ServiceCategory = serviceCategory,
SecondMessage = new MaxiCodeStandardSecondMessage { Message = message }
};
- complexCodetext = ct;
+ codetext = ct;
}
else if (mode == 3)
{
- // Mode 3 is similar to mode 2 but with a different data layout
var ct = new MaxiCodeCodetextMode3
{
PostalCode = postalCode,
@@ -88,37 +83,41 @@ static void Main(string[] args)
ServiceCategory = serviceCategory,
SecondMessage = new MaxiCodeStandardSecondMessage { Message = message }
};
- complexCodetext = ct;
+ codetext = ct;
}
- else
+ else // modes 4,5,6 use standard codetext
{
- // Modes 4, 5, and 6 use the standard codetext structure
var ct = new MaxiCodeStandardCodetext
{
- Mode = (MaxiCodeMode)mode,
+ Mode = mode switch
+ {
+ 4 => MaxiCodeMode.Mode4,
+ 5 => MaxiCodeMode.Mode5,
+ 6 => MaxiCodeMode.Mode6,
+ _ => throw new ArgumentOutOfRangeException()
+ },
Message = message
};
- complexCodetext = ct;
+ codetext = ct;
}
// --------------------------------------------------------------------
- // Generate the MaxiCode barcode image and output it as Base64 PNG
+ // Define the output file path (in a real MVC action this would be streamed)
// --------------------------------------------------------------------
- using (var generator = new ComplexBarcodeGenerator(complexCodetext))
- {
- // Optional: set image resolution (dots per inch)
- generator.Parameters.Resolution = 300f;
+ string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "maxicode.png");
- using (var ms = new MemoryStream())
- {
- // Save the barcode to a memory stream in PNG format
- generator.Save(ms, BarCodeImageFormat.Png);
+ // --------------------------------------------------------------------
+ // Generate the barcode image and save it as PNG
+ // --------------------------------------------------------------------
+ using (var generator = new ComplexBarcodeGenerator(codetext))
+ {
+ // Generate the bitmap (optional, GenerateBarCodeImage returns the bitmap)
+ generator.GenerateBarCodeImage();
- // Convert the image bytes to a Base64 string for easy display/transmission
- byte[] imageBytes = ms.ToArray();
- string base64 = Convert.ToBase64String(imageBytes);
- Console.WriteLine(base64);
- }
+ // Save the image to the specified path
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
+
+ Console.WriteLine($"MaxiCode barcode generated (mode {mode}) and saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/create-console-utility-that-reads-list-of-codetext-strings-and-outputs-corresponding-maxicode-png-files.cs b/maxicode-barcode/create-console-utility-that-reads-list-of-codetext-strings-and-outputs-corresponding-maxicode-png-files.cs
index 7e2471d..36dc8b2 100644
--- a/maxicode-barcode/create-console-utility-that-reads-list-of-codetext-strings-and-outputs-corresponding-maxicode-png-files.cs
+++ b/maxicode-barcode/create-console-utility-that-reads-list-of-codetext-strings-and-outputs-corresponding-maxicode-png-files.cs
@@ -1,61 +1,54 @@
+// Title: Generate MaxiCode PNG files from a list of codetext strings
+// Description: Demonstrates how to create MaxiCode barcodes and save them as PNG images using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of EncodeTypes.MaxiCode with the BarcodeGenerator class. Developers often need to produce MaxiCode symbols for shipping, logistics, and tracking applications; this snippet illustrates typical setup, resolution configuration, and image export to PNG format, serving as a reference for similar console utilities.
+// Prompt: Create a console utility that reads a list of codetext strings and outputs corresponding MaxiCode PNG files.
+// Tags: maxicode, barcode generation, png output, aspose.barcode, console utility, encode types
+
using System;
-using System.IO;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode;
///
-/// Demonstrates generating MaxiCode barcodes using Aspose.BarCode and saving them as PNG files.
+/// Console application that generates MaxiCode barcodes from predefined codetext strings
+/// and saves each barcode as a PNG image file.
///
class Program
{
///
- /// Entry point of the application. Generates a series of MaxiCode barcodes from sample text strings.
+ /// Entry point of the application. Iterates over a collection of codetext strings,
+ /// creates a MaxiCode barcode for each, and writes the resulting PNG file to disk.
///
static void Main()
{
- // Define a sample list of codetext strings to encode as MaxiCode barcodes.
- string[] codetexts = new string[]
+ // Define a sample list of MaxiCode codetext strings.
+ // In a real scenario these could be read from a file, database, or user input.
+ string[] codetexts = new[]
{
- "Sample message 1",
- "Sample message 2",
- "Sample message 3",
- "Sample message 4",
- "Sample message 5"
+ "524032140056999Test message", // Mode 2 example
+ "B1050 056999Another message", // Mode 3 example (space separates postal code)
+ "Sample MaxiCode Text 1",
+ "Sample MaxiCode Text 2",
+ "Sample MaxiCode Text 3"
};
- // Specify the output directory for generated PNG files.
- string outputDir = "MaxiCodeOutput";
-
- // Create the output directory if it does not already exist.
- if (!Directory.Exists(outputDir))
- {
- Directory.CreateDirectory(outputDir);
- }
-
- // Iterate over each codetext string and generate a corresponding MaxiCode barcode.
+ // Iterate through each codetext, generate a barcode, and save it as a PNG file.
for (int i = 0; i < codetexts.Length; i++)
{
- // Retrieve the current text to encode.
string text = codetexts[i];
+ string fileName = $"maxicode_{i + 1}.png";
- // Configure a standard MaxiCode (Mode 4) which encodes only the message.
- var maxiCode = new MaxiCodeStandardCodetext
+ // Create a BarcodeGenerator for MaxiCode using the current codetext.
+ using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, text))
{
- Mode = MaxiCodeMode.Mode4,
- Message = text
- };
-
- // Build the full file path for the output PNG file.
- string filePath = Path.Combine(outputDir, $"maxicode_{i + 1}.png");
+ // Optional: set the image resolution (dots per inch) if higher quality is required.
+ generator.Parameters.Resolution = 300;
- // Generate the barcode image and save it to the specified file.
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
- {
- generator.Save(filePath, BarCodeImageFormat.Png);
+ // Save the generated barcode image in PNG format.
+ generator.Save(fileName, BarCodeImageFormat.Png);
}
// Output a confirmation message to the console.
- Console.WriteLine($"Generated: {filePath}");
+ Console.WriteLine($"Generated {fileName} for codetext: {text}");
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/create-helper-method-that-builds-maxicode-structured-secondary-messages-from-address-components.cs b/maxicode-barcode/create-helper-method-that-builds-maxicode-structured-secondary-messages-from-address-components.cs
index 939575a..fe61662 100644
--- a/maxicode-barcode/create-helper-method-that-builds-maxicode-structured-secondary-messages-from-address-components.cs
+++ b/maxicode-barcode/create-helper-method-that-builds-maxicode-structured-secondary-messages-from-address-components.cs
@@ -1,92 +1,69 @@
+// Title: Build MaxiCode Structured Secondary Message Helper
+// Description: Demonstrates creating a MaxiCode barcode with a structured secondary message built from address components.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on MaxiCode symbology. It showcases the use of MaxiCodeCodetextMode2, MaxiCodeStructuredSecondMessage, and ComplexBarcodeGenerator classes to encode postal information and a custom secondary message. Developers often need to generate MaxiCode barcodes for shipping and logistics, requiring precise formatting of address data and service categories.
+// Prompt: Create a helper method that builds MaxiCode structured secondary messages from address components.
+// Tags: maxicode, structured secondary message, barcode generation, aspnet, aspose.barcode, complexbarcode, helper method
+
using System;
-using System.Collections.Generic;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates building a MaxiCode structured secondary message and generating a MaxiCode barcode.
+/// Demonstrates building a MaxiCode barcode with a structured secondary message.
///
class Program
{
///
/// Builds a structured secondary message for MaxiCode from address components.
///
- /// List of address lines (max 3 lines are typical for MaxiCode).
- /// City name.
+ /// First address line (e.g., street).
+ /// Second address line (e.g., city).
/// State abbreviation.
- /// Two‑digit year (0‑99).
- /// A populated with the provided data.
- static MaxiCodeStructuredSecondMessage BuildMaxiCodeStructuredMessage(
- IList addressLines,
- string city,
- string state,
- int year)
+ /// Two‑digit year value.
+ /// A populated instance.
+ static MaxiCodeStructuredSecondMessage BuildStructuredSecondMessage(string line1, string line2, string state, int year)
{
- // Validate input parameters.
- if (addressLines == null) throw new ArgumentNullException(nameof(addressLines));
- if (addressLines.Count == 0) throw new ArgumentException("At least one address line is required.", nameof(addressLines));
- if (string.IsNullOrWhiteSpace(city)) throw new ArgumentException("City is required.", nameof(city));
- if (string.IsNullOrWhiteSpace(state)) throw new ArgumentException("State is required.", nameof(state));
- if (year < 0 || year > 99) throw new ArgumentOutOfRangeException(nameof(year), "Year must be between 0 and 99.");
+ // Create a new structured message container.
+ var message = new MaxiCodeStructuredSecondMessage();
- var secondMessage = new MaxiCodeStructuredSecondMessage();
+ // Add address components to the message in the required order.
+ message.Add(line1);
+ message.Add(line2);
+ message.Add(state);
- // Add address lines.
- foreach (var line in addressLines)
- {
- secondMessage.Add(line);
- }
+ // Set the year field.
+ message.Year = year;
- // Add city, state and year as separate identifiers.
- secondMessage.Add(city);
- secondMessage.Add(state);
- secondMessage.Year = year;
-
- return secondMessage;
+ return message;
}
///
- /// Entry point of the program. Generates a MaxiCode barcode and saves it as a PNG file.
+ /// Entry point. Generates a MaxiCode barcode using address components and saves it as an image.
///
static void Main()
{
// Sample address components.
- var addressLines = new List
- {
- "634 ALPHA DRIVE",
- "PITTSBURGH"
- };
- string city = "PA";
- string state = "US";
- int year = 99; // Two‑digit year.
-
- // Build the structured second message using the helper method.
- var structuredMessage = BuildMaxiCodeStructuredMessage(addressLines, city, state, year);
+ string street = "634 ALPHA DRIVE";
+ string city = "PITTSBURGH";
+ string state = "PA";
+ int year = 99;
- // Configure MaxiCode codetext (Mode 2 example).
+ // Configure MaxiCode codetext for Mode 2 (postal code, country, service category).
var maxiCodeCodetext = new MaxiCodeCodetextMode2
{
PostalCode = "524032140", // 9‑digit US postal code.
- CountryCode = 056, // Example country code.
- ServiceCategory = 999, // Example service category.
- SecondMessage = structuredMessage
+ CountryCode = 056, // USA numeric country code.
+ ServiceCategory = 999 // Example service category.
};
- // Generate the MaxiCode barcode using ComplexBarcodeGenerator.
- using (var complexGenerator = new ComplexBarcodeGenerator(maxiCodeCodetext))
- {
- // Optional: set a human‑readable text displayed below the barcode.
- complexGenerator.Parameters.Barcode.CodeTextParameters.TwoDDisplayText = "Sample MaxiCode";
+ // Assign the structured secondary message built from the address components.
+ maxiCodeCodetext.SecondMessage = BuildStructuredSecondMessage(street, city, state, year);
- // Generate the barcode image.
- using (var image = complexGenerator.GenerateBarCodeImage())
- {
- // Save the image as PNG.
- image.Save("maxicode.png", ImageFormat.Png);
- }
+ // Generate the MaxiCode barcode and save it as a PNG image.
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ {
+ generator.Save("maxicode.png");
}
Console.WriteLine("MaxiCode barcode generated: maxicode.png");
diff --git a/maxicode-barcode/create-maxicode-mode-3-barcode-using-structured-secondary-message-and-export-image-as-jpeg.cs b/maxicode-barcode/create-maxicode-mode-3-barcode-using-structured-secondary-message-and-export-image-as-jpeg.cs
index 3a0f9a1..0759e77 100644
--- a/maxicode-barcode/create-maxicode-mode-3-barcode-using-structured-secondary-message-and-export-image-as-jpeg.cs
+++ b/maxicode-barcode/create-maxicode-mode-3-barcode-using-structured-secondary-message-and-export-image-as-jpeg.cs
@@ -1,52 +1,49 @@
+// Title: Create MaxiCode Mode 3 Barcode with Structured Secondary Message
+// Description: Demonstrates how to generate a MaxiCode Mode 3 barcode that includes a structured secondary message and export the result as a JPEG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of MaxiCodeCodetextMode3, MaxiCodeStructuredSecondMessage, and ComplexBarcodeGenerator classes to create high‑density 2‑D barcodes for shipping and logistics applications. Developers often need to embed address information and other structured data within MaxiCode symbols for automated sorting and tracking.
+// Prompt: Create a MaxiCode Mode 3 barcode using a structured secondary message and export the image as JPEG.
+// Tags: maxicode, mode3, structured-secondary-message, jpeg, barcode-generation, aspose.barcode, complexbarcode
+
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation of a MaxiCode Mode 3 barcode with a structured secondary message
-/// using Aspose.BarCode's ComplexBarcodeGenerator.
+/// Example program that creates a MaxiCode Mode 3 barcode with a structured secondary message
+/// and saves it as a JPEG file.
///
class Program
{
///
- /// Entry point of the application. Generates the barcode and saves it as a JPEG file.
+ /// Entry point of the application.
///
static void Main()
{
- // Define the output file path in the current working directory.
- string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "MaxiCodeMode3.jpg");
-
- // Create MaxiCode codetext for Mode 3, populating required fields.
- var maxiCodeCodetext = new MaxiCodeCodetextMode3
- {
- PostalCode = "B1050", // 6‑character alphanumeric postal code
- CountryCode = 56, // Example country code
- ServiceCategory = 999 // Example service category
- };
-
- // Build the structured secondary message (address lines, state, and year).
+ // Initialize a structured secondary message with address lines and year.
var structuredMessage = new MaxiCodeStructuredSecondMessage();
structuredMessage.Add("634 ALPHA DRIVE"); // Street address
structuredMessage.Add("PITTSBURGH"); // City
- structuredMessage.Add("PA"); // State abbreviation
- structuredMessage.Year = 99; // Example year (two‑digit)
-
- // Attach the structured message to the MaxiCode codetext.
- maxiCodeCodetext.SecondMessage = structuredMessage;
+ structuredMessage.Add("PA"); // State
+ structuredMessage.Year = 99; // Two‑digit year
- // Initialize the complex barcode generator with the prepared codetext.
- using (var complexGenerator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Configure the MaxiCode Mode 3 codetext, including postal code, country code,
+ // service category, and the previously created secondary message.
+ var maxiCode = new MaxiCodeCodetextMode3
{
- // Generate the barcode image in memory (required before saving).
- complexGenerator.GenerateBarCodeImage();
+ PostalCode = "B1050", // 6 alphanumeric characters
+ CountryCode = 56, // 3‑digit country code
+ ServiceCategory = 999,
+ SecondMessage = structuredMessage
+ };
- // Persist the generated image as a JPEG file.
- complexGenerator.Save(outputPath, BarCodeImageFormat.Jpeg);
+ // Generate the barcode using ComplexBarcodeGenerator and save it as a JPEG image.
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ {
+ generator.Save("maxicode_mode3.jpeg");
}
- // Inform the user where the barcode image has been saved.
- Console.WriteLine($"MaxiCode Mode 3 barcode saved to: {outputPath}");
+ // Inform the user that the barcode has been saved.
+ Console.WriteLine("MaxiCode Mode 3 barcode saved as maxicode_mode3.jpeg");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/create-maxicode-mode-6-barcode-apply-transparent-background-and-write-file-to-memory-stream.cs b/maxicode-barcode/create-maxicode-mode-6-barcode-apply-transparent-background-and-write-file-to-memory-stream.cs
index 5c9f487..f5985a2 100644
--- a/maxicode-barcode/create-maxicode-mode-6-barcode-apply-transparent-background-and-write-file-to-memory-stream.cs
+++ b/maxicode-barcode/create-maxicode-mode-6-barcode-apply-transparent-background-and-write-file-to-memory-stream.cs
@@ -1,44 +1,46 @@
+// Title: Generate MaxiCode Mode 6 Barcode with Transparent Background
+// Description: Creates a MaxiCode Mode 6 barcode, applies a transparent background, and writes the PNG image to a memory stream.
+// Category-Description: This example demonstrates the use of Aspose.BarCode's ComplexBarcodeGenerator to produce MaxiCode symbols, a 2‑D barcode used in logistics and shipping. It showcases setting barcode parameters such as mode and background color, and saving the result to a stream in PNG format. Developers working with advanced barcode symbologies, custom rendering options, or in‑memory image handling will find this pattern useful.
+// Prompt: Create a MaxiCode Mode 6 barcode, apply a transparent background, and write the file to a memory stream.
+// Tags: maxicode, mode6, transparent background, memory stream, png, aspose.barcode, barcode generation
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.ComplexBarcode;
using Aspose.Drawing;
///
-/// Demonstrates generating a MaxiCode barcode (Mode 6) with a transparent background
-/// and writing it to a memory stream.
+/// Demonstrates generating a MaxiCode Mode 6 barcode with a transparent background
+/// and saving it to a memory stream as a PNG image.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates the barcode, saves it to a memory stream, and outputs its size.
+ /// Entry point of the example. Builds the barcode, configures rendering options,
+ /// and writes the image to a .
///
static void Main()
{
- // Initialize a MaxiCode barcode generator for Mode 6
- using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode))
+ // Initialize MaxiCode codetext for Mode 6 and set the message payload.
+ var maxiCodeCodetext = new MaxiCodeStandardCodetext
{
- // Set the text to be encoded in the barcode
- generator.CodeText = "Test message";
-
- // Configure MaxiCode specific parameters: select Mode 6
- generator.Parameters.Barcode.MaxiCode.Mode = MaxiCodeMode.Mode6;
+ Mode = MaxiCodeMode.Mode6,
+ Message = "Test message"
+ };
- // Set the background color to transparent to support PNG transparency
+ // Create a ComplexBarcodeGenerator using the prepared codetext.
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ {
+ // Configure the barcode to have a transparent background.
generator.Parameters.BackColor = Color.Transparent;
- // Create a memory stream to hold the generated PNG image
+ // Save the generated barcode image to a memory stream in PNG format.
using (var memoryStream = new MemoryStream())
{
- // Save the barcode image to the memory stream in PNG format
generator.Save(memoryStream, BarCodeImageFormat.Png);
-
- // Reset the stream position to the beginning for any subsequent reads
- memoryStream.Position = 0;
-
- // Output the size of the generated image in bytes
- Console.WriteLine($"Generated barcode size: {memoryStream.Length} bytes");
+ Console.WriteLine($"Barcode generated. Stream length: {memoryStream.Length} bytes.");
}
}
}
diff --git a/maxicode-barcode/create-unit-test-that-verifies-generated-maxicode-mode-2-codetext-matches-expected-formatted-string.cs b/maxicode-barcode/create-unit-test-that-verifies-generated-maxicode-mode-2-codetext-matches-expected-formatted-string.cs
index 1f30329..56d4382 100644
--- a/maxicode-barcode/create-unit-test-that-verifies-generated-maxicode-mode-2-codetext-matches-expected-formatted-string.cs
+++ b/maxicode-barcode/create-unit-test-that-verifies-generated-maxicode-mode-2-codetext-matches-expected-formatted-string.cs
@@ -1,58 +1,83 @@
+// Title: Verify MaxiCode Mode 2 Codetext Generation
+// Description: Demonstrates a unit‑test‑style verification that the MaxiCode Mode 2 codetext produced by Aspose.BarCode matches the expected formatted string.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on MaxiCode symbology. It shows how to use MaxiCodeCodetextMode2, MaxiCodeStandardSecondMessage, and ComplexBarcodeGenerator to construct and validate codetext without rendering an image. Developers working with shipping or logistics barcode solutions often need to ensure the encoded data follows the required format before creating the barcode image.
+// Prompt: Create a unit test that verifies the generated MaxiCode Mode 2 codetext matches the expected formatted string.
+// Tags: maxicode, mode2, codetext, unit-test, aspose.barcode, complexbarcodegenerator
+
using System;
using Aspose.BarCode;
-using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.Generation;
///
-/// Demonstrates creation, encoding, and decoding of MaxiCode Mode 2 codetext using Aspose.BarCode.
+/// Example program that builds a MaxiCode Mode 2 codetext, generates a barcode generator instance,
+/// and validates that the constructed codetext matches the expected formatted string.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Prepares expected values, constructs the codetext object,
+ /// instantiates the generator, and verifies the resulting codetext.
///
static void Main()
{
- // Create a MaxiCode Mode 2 codetext object and set the required fields.
- var maxiCodeCodetext = new MaxiCodeCodetextMode2();
- maxiCodeCodetext.PostalCode = "524032140"; // 9‑digit US postal code
- maxiCodeCodetext.CountryCode = 56; // 3‑digit country code (leading zeros are optional)
- maxiCodeCodetext.ServiceCategory = 999; // 3‑digit service category
-
- // Create and assign the standard second message.
- var secondMessage = new MaxiCodeStandardSecondMessage();
- secondMessage.Message = "Test message";
- maxiCodeCodetext.SecondMessage = secondMessage;
+ // ------------------------------------------------------------
+ // Prepare expected values for the MaxiCode components
+ // ------------------------------------------------------------
+ string expectedPostalCode = "524032140";
+ int expectedCountryCode = 56; // will be formatted as three digits "056"
+ int expectedServiceCategory = 999;
+ string expectedMessage = "Test message";
- // Generate the formatted codetext string from the object.
- string generatedCodetext = maxiCodeCodetext.GetConstructedCodetext();
+ // Build the expected formatted codetext string according to MaxiCode Mode 2 rules
+ string expectedCodetext = expectedPostalCode +
+ expectedCountryCode.ToString("D3") +
+ expectedServiceCategory.ToString("D3") +
+ expectedMessage;
- // Decode the generated codetext back into a MaxiCode object.
- var decodedCodetext = ComplexCodetextReader.TryDecodeMaxiCode(MaxiCodeMode.Mode2, generatedCodetext) as MaxiCodeCodetextMode2;
+ // ------------------------------------------------------------
+ // Create and populate the MaxiCode Mode 2 codetext object
+ // ------------------------------------------------------------
+ var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ {
+ PostalCode = expectedPostalCode,
+ CountryCode = expectedCountryCode,
+ ServiceCategory = expectedServiceCategory
+ };
- // Simple assertion helper to validate conditions.
- void Assert(bool condition, string message)
+ // Attach the standard second message to the codetext
+ var secondMessage = new MaxiCodeStandardSecondMessage
{
- if (!condition)
- {
- Console.WriteLine("ASSERTION FAILED: " + message);
- Environment.Exit(1);
- }
- }
+ Message = expectedMessage
+ };
+ maxiCodeCodetext.SecondMessage = secondMessage;
- // Verify that decoding succeeded and all fields match the original values.
- Assert(decodedCodetext != null, "Decoded codetext should not be null.");
- Assert(decodedCodetext.PostalCode == maxiCodeCodetext.PostalCode, "PostalCode mismatch.");
- Assert(decodedCodetext.CountryCode == maxiCodeCodetext.CountryCode, "CountryCode mismatch.");
- Assert(decodedCodetext.ServiceCategory == maxiCodeCodetext.ServiceCategory, "ServiceCategory mismatch.");
+ // ------------------------------------------------------------
+ // Initialize the ComplexBarcodeGenerator (required lifecycle)
+ // ------------------------------------------------------------
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ {
+ // Image generation is unnecessary for this test, but the generator must be instantiated.
+ generator.GenerateBarCodeImage();
+ }
- // Verify the second message content.
- var decodedSecond = decodedCodetext.SecondMessage as MaxiCodeStandardSecondMessage;
- Assert(decodedSecond != null, "SecondMessage type mismatch.");
- Assert(decodedSecond.Message == secondMessage.Message, "SecondMessage content mismatch.");
+ // ------------------------------------------------------------
+ // Retrieve the constructed codetext from the object for verification
+ // ------------------------------------------------------------
+ string actualCodetext = maxiCodeCodetext.GetConstructedCodetext();
- // If all assertions pass, the generated codetext matches the expected format.
- Console.WriteLine("MaxiCode Mode 2 codetext generation test passed.");
+ // ------------------------------------------------------------
+ // Verify that the generated codetext matches the expected format
+ // ------------------------------------------------------------
+ if (actualCodetext == expectedCodetext)
+ {
+ Console.WriteLine("Test Passed: Generated codetext matches expected.");
+ }
+ else
+ {
+ Console.WriteLine("Test Failed:");
+ Console.WriteLine($"Expected: \"{expectedCodetext}\"");
+ Console.WriteLine($"Actual: \"{actualCodetext}\"");
+ }
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/develop-web-api-endpoint-that-accepts-json-builds-maxicode-mode-3-codetext-and-returns-png-data.cs b/maxicode-barcode/develop-web-api-endpoint-that-accepts-json-builds-maxicode-mode-3-codetext-and-returns-png-data.cs
index 76fb6a3..c21912f 100644
--- a/maxicode-barcode/develop-web-api-endpoint-that-accepts-json-builds-maxicode-mode-3-codetext-and-returns-png-data.cs
+++ b/maxicode-barcode/develop-web-api-endpoint-that-accepts-json-builds-maxicode-mode-3-codetext-and-returns-png-data.cs
@@ -1,100 +1,100 @@
+// Title: Generate MaxiCode Mode 3 barcode and output PNG as Base64
+// Description: Demonstrates building a MaxiCode Mode 3 codetext from JSON input and returning the barcode image in PNG format.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode3, and related classes to encode postal and service data. Developers creating shipping, logistics, or tracking solutions often need to generate MaxiCode barcodes for UPS and other carriers, and this snippet illustrates the typical workflow of parsing input, constructing codetext, and producing a PNG image.
+// Prompt: Develop a Web API endpoint that accepts JSON, builds a MaxiCode Mode 3 codetext, and returns PNG data.
+// Tags: maxicode, barcode, generation, png, json, aspnet, aspose.barcode, complexbarcode
+
using System;
using System.IO;
-using System.Text;
using System.Text.Json;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing.Imaging;
-namespace MaxiCodeApiDemo
+namespace MaxiCodeConsoleApp
{
///
- /// Model representing the expected JSON payload for a MaxiCode request.
+ /// Simple DTO matching the expected JSON structure for MaxiCode input data.
///
- public class MaxiCodeRequest
+ public class MaxiCodeInput
{
- public string PostalCode { get; set; } // 6 alphanumeric characters
- public int CountryCode { get; set; } // 3‑digit numeric code
- public int ServiceCategory { get; set; } // 3‑digit numeric code
- public string Message { get; set; } // Standard second message
+ public string PostalCode { get; set; }
+ public int CountryCode { get; set; }
+ public int ServiceCategory { get; set; }
+ public string Message { get; set; }
}
///
- /// Demonstrates generating a MaxiCode (Mode 3) barcode from JSON input.
+ /// Console application that demonstrates generating a MaxiCode Mode 3 barcode from JSON input and outputting the PNG image as a Base64 string.
///
class Program
{
///
- /// Entry point of the application.
- /// Accepts a JSON string as a command‑line argument or uses a default sample.
- /// Generates a MaxiCode barcode and outputs the PNG image as a Base64 string.
+ /// Entry point. Parses JSON input, creates MaxiCode codetext, generates a PNG barcode, and writes the image bytes as Base64 to the console.
///
- /// Command‑line arguments; first argument may contain JSON input.
+ /// Command‑line arguments; the first argument may contain a JSON payload.
static void Main(string[] args)
{
- // Determine JSON input: use first argument if provided, otherwise fall back to a sample payload.
- string jsonInput = args.Length > 0 ? args[0] :
- @"{
- ""PostalCode"": ""B1050"",
- ""CountryCode"": 56,
- ""ServiceCategory"": 999,
- ""Message"": ""Test message""
- }";
+ // NOTE:
+ // The original request was for a Web API endpoint.
+ // The snippet runner environment does not support hosting an HTTP server,
+ // so this console application demonstrates the core logic:
+ // - Parse JSON input (from command‑line argument or default)
+ // - Build a MaxiCode Mode 3 codetext
+ // - Generate a PNG image
+ // - Output the PNG bytes as a Base64 string to the console
+
+ // Use the first command‑line argument as JSON if provided; otherwise fall back to a default payload.
+ string json = args.Length > 0
+ ? args[0]
+ : "{\"PostalCode\":\"B1050\",\"CountryCode\":56,\"ServiceCategory\":999,\"Message\":\"Test message\"}";
- // Attempt to deserialize the JSON payload into a MaxiCodeRequest object.
- MaxiCodeRequest request;
+ MaxiCodeInput input;
try
{
- request = JsonSerializer.Deserialize(jsonInput, new JsonSerializerOptions
+ // Deserialize the JSON payload into the DTO, ignoring case differences in property names.
+ input = JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
+
+ // Validate required fields.
+ if (input == null ||
+ string.IsNullOrWhiteSpace(input.PostalCode) ||
+ string.IsNullOrWhiteSpace(input.Message))
{
- PropertyNameCaseInsensitive = true
- });
+ throw new ArgumentException("Invalid JSON payload.");
+ }
}
catch (Exception ex)
{
- // Output an error message if JSON parsing fails and terminate the program.
- Console.WriteLine($"Invalid JSON input: {ex.Message}");
- return;
- }
-
- // Perform basic validation of required fields.
- if (request == null ||
- string.IsNullOrWhiteSpace(request.PostalCode) ||
- request.PostalCode.Length != 6 ||
- string.IsNullOrWhiteSpace(request.Message))
- {
- Console.WriteLine("Invalid request data. Ensure PostalCode is 6 characters and Message is provided.");
+ Console.WriteLine($"Error parsing input JSON: {ex.Message}");
return;
}
- // Construct the MaxiCode codetext for Mode 3 using the request data.
- var maxiCodeCodetext = new MaxiCodeCodetextMode3
+ // Build the MaxiCode Mode 3 codetext using the input data.
+ var codetext = new MaxiCodeCodetextMode3
{
- PostalCode = request.PostalCode,
- CountryCode = request.CountryCode,
- ServiceCategory = request.ServiceCategory
+ PostalCode = input.PostalCode,
+ CountryCode = input.CountryCode,
+ ServiceCategory = input.ServiceCategory
};
- // Attach the standard second message to the codetext.
+ // Attach the secondary message (free‑form text) to the codetext.
var secondMessage = new MaxiCodeStandardSecondMessage
{
- Message = request.Message
+ Message = input.Message
};
- maxiCodeCodetext.SecondMessage = secondMessage;
+ codetext.SecondMessage = secondMessage;
- // Generate the barcode image and write it to a memory stream.
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Generate the barcode and write PNG data to a memory stream.
+ using (var generator = new ComplexBarcodeGenerator(codetext))
+ using (var ms = new MemoryStream())
{
- using (var ms = new MemoryStream())
- {
- // Save the generated barcode as a PNG image.
- generator.Save(ms, BarCodeImageFormat.Png);
- byte[] pngBytes = ms.ToArray();
+ generator.Save(ms, BarCodeImageFormat.Png);
+ byte[] pngBytes = ms.ToArray();
- // Convert the PNG byte array to a Base64 string (simulating an HTTP response body).
- string base64 = Convert.ToBase64String(pngBytes);
- Console.WriteLine(base64);
- }
+ // Convert the PNG bytes to a Base64 string for easy console output or API response.
+ string base64 = Convert.ToBase64String(pngBytes);
+ Console.WriteLine(base64);
}
}
}
diff --git a/maxicode-barcode/encode-numeric-postal-code-in-primary-message-of-maxicode-mode-2-and-verify-decoding-accuracy.cs b/maxicode-barcode/encode-numeric-postal-code-in-primary-message-of-maxicode-mode-2-and-verify-decoding-accuracy.cs
index 4400a64..6db9a76 100644
--- a/maxicode-barcode/encode-numeric-postal-code-in-primary-message-of-maxicode-mode-2-and-verify-decoding-accuracy.cs
+++ b/maxicode-barcode/encode-numeric-postal-code-in-primary-message-of-maxicode-mode-2-and-verify-decoding-accuracy.cs
@@ -1,3 +1,9 @@
+// Title: Encode and Verify MaxiCode Mode 2 Postal Code
+// Description: Demonstrates encoding a numeric postal code into the primary message of a MaxiCode Mode 2 barcode and validates the result by decoding the generated image.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation and recognition category. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and BarCodeReader to create and read MaxiCode symbols. Developers working with high‑density 2‑D barcodes such as MaxiCode can use these APIs to embed structured data (e.g., postal codes) and verify encoding accuracy, a common requirement in logistics and shipping applications.
+// Prompt: Encode a numeric postal code in the primary message of a MaxiCode Mode 2 and verify decoding accuracy.
+// Tags: maxicode, mode2, barcode, encoding, decoding, aspose.barcode, complexbarcode, png
+
using System;
using System.IO;
using Aspose.BarCode;
@@ -6,83 +12,69 @@
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation and decoding of a MaxiCode Mode 2 barcode using Aspose.BarCode.
+/// Example program that creates a MaxiCode Mode 2 barcode containing a numeric postal code,
+/// saves it as a PNG image, and then reads the image back to verify that the encoded data
+/// matches the original input.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a MaxiCode Mode 2 barcode, decodes it, and prints the extracted fields.
+ /// Entry point of the example. Generates the barcode, saves it, and validates decoding.
///
static void Main()
{
- // ------------------------------------------------------------
- // 1. Define sample data for MaxiCode Mode 2
- // ------------------------------------------------------------
- string postalCode = "524032140"; // 9‑digit US postal code
- int countryCode = 56; // Example 3‑digit country code
- int serviceCategory = 999; // Example service category
- string secondMessageText = "Test message";
+ // Define the output file path for the generated barcode image.
+ string outputPath = "maxicode_mode2.png";
- // ------------------------------------------------------------
- // 2. Build the codetext object that represents the MaxiCode data
- // ------------------------------------------------------------
+ // Build the MaxiCode Mode 2 codetext with required fields.
var maxiCodeCodetext = new MaxiCodeCodetextMode2
{
- PostalCode = postalCode,
- CountryCode = countryCode,
- ServiceCategory = serviceCategory,
- SecondMessage = new MaxiCodeStandardSecondMessage { Message = secondMessageText }
+ PostalCode = "123456789", // 9‑digit numeric postal code (primary message)
+ CountryCode = 840, // Numeric ISO country code for USA
+ ServiceCategory = 999 // Example service category identifier
};
- // ------------------------------------------------------------
- // 3. Generate the barcode image and store it in a memory stream
- // ------------------------------------------------------------
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
- using (var imageStream = new MemoryStream())
+ // Optional: add a standard secondary message to the MaxiCode.
+ var secondMessage = new MaxiCodeStandardSecondMessage
{
- // Save the generated barcode as PNG into the stream
- generator.Save(imageStream, BarCodeImageFormat.Png);
- // Reset stream position to the beginning for reading
- imageStream.Position = 0;
+ Message = "Sample secondary data"
+ };
+ maxiCodeCodetext.SecondMessage = secondMessage;
- // --------------------------------------------------------
- // 4. Decode the barcode from the memory stream
- // --------------------------------------------------------
- using (var reader = new BarCodeReader(imageStream, DecodeType.MaxiCode))
- {
- // Iterate over all detected barcodes (should be only one)
- foreach (var result in reader.ReadBarCodes())
- {
- // Decode the complex codetext from the raw code text
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
+ // Generate the MaxiCode image using the ComplexBarcodeGenerator.
+ using (var complexGenerator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ {
+ complexGenerator.Save(outputPath, BarCodeImageFormat.Png);
+ }
- // ----------------------------------------------------
- // 5. If decoding succeeded as Mode 2, output the fields
- // ----------------------------------------------------
- if (decoded is MaxiCodeCodetextMode2 decodedMode2)
- {
- Console.WriteLine($"Decoded PostalCode: {decodedMode2.PostalCode}");
- Console.WriteLine($"Decoded CountryCode: {decodedMode2.CountryCode}");
- Console.WriteLine($"Decoded ServiceCategory: {decodedMode2.ServiceCategory}");
+ // Verify that the image file was created successfully.
+ if (!File.Exists(outputPath))
+ {
+ Console.WriteLine("Failed to create barcode image.");
+ return;
+ }
- // Output the optional second message if present
- if (decodedMode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
- {
- Console.WriteLine($"Decoded Second Message: {stdMsg.Message}");
- }
+ // Read and decode the generated barcode image.
+ using (var reader = new BarCodeReader(outputPath, DecodeType.MaxiCode))
+ {
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Decode the raw codetext according to the detected MaxiCode mode.
+ var decodedCodetext = ComplexCodetextReader.TryDecodeMaxiCode(
+ result.Extended.MaxiCode.MaxiCodeMode,
+ result.CodeText);
- // Verify that the decoded postal code matches the original input
- bool match = decodedMode2.PostalCode == postalCode;
- Console.WriteLine($"Postal code match: {match}");
- }
- else
- {
- // Decoding did not produce a Mode 2 object
- Console.WriteLine("Failed to decode MaxiCode as Mode 2.");
- }
+ // Check if the decoded data is of type MaxiCode Mode 2.
+ if (decodedCodetext is MaxiCodeCodetextMode2 decodedMode2)
+ {
+ Console.WriteLine($"Decoded PostalCode: {decodedMode2.PostalCode}");
+ Console.WriteLine($"Original PostalCode: {maxiCodeCodetext.PostalCode}");
+ bool match = decodedMode2.PostalCode == maxiCodeCodetext.PostalCode;
+ Console.WriteLine($"Match: {match}");
+ }
+ else
+ {
+ Console.WriteLine("Decoded codetext is not MaxiCode Mode 2.");
}
}
}
diff --git a/maxicode-barcode/export-generated-maxicode-barcode-as-base64-string-for-embedding-in-json-api-responses.cs b/maxicode-barcode/export-generated-maxicode-barcode-as-base64-string-for-embedding-in-json-api-responses.cs
index c21554a..aa7aa76 100644
--- a/maxicode-barcode/export-generated-maxicode-barcode-as-base64-string-for-embedding-in-json-api-responses.cs
+++ b/maxicode-barcode/export-generated-maxicode-barcode-as-base64-string-for-embedding-in-json-api-responses.cs
@@ -1,44 +1,55 @@
+// Title: Export MaxiCode barcode as Base64 string
+// Description: Generates a MaxiCode barcode (Mode 2) and converts the PNG image to a Base64 string suitable for inclusion in JSON API responses.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, illustrating how to use ComplexBarcodeGenerator with MaxiCodeCodetextMode2, configure postal and secondary message data, and output the result in a web‑friendly format. Developers working with shipping, logistics, or inventory systems often need to embed barcode images directly in JSON payloads, and this snippet shows the typical workflow using Aspose.BarCode classes.
+// Prompt: Export a generated MaxiCode barcode as a base64 string for embedding in JSON API responses.
+// Tags: maxicode, barcode, base64, json, aspose.barcode, complexbarcode, generation
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generating a MaxiCode barcode and outputting its Base64 representation.
+/// Demonstrates generating a MaxiCode barcode and converting it to a Base64 string for JSON embedding.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a MaxiCode barcode from sample text, encodes it as PNG,
- /// converts the image to a Base64 string, and writes it to the console.
+ /// Entry point of the example. Creates a MaxiCode (Mode 2) barcode, saves it to a memory stream,
+ /// converts the image to Base64, and writes the string to the console.
///
static void Main()
{
- // Sample data to encode in the MaxiCode barcode
- const string codeText = "Test MaxiCode";
+ // Prepare MaxiCode codetext for Mode 2 (postal information + data)
+ var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ {
+ PostalCode = "524032140", // 9‑digit US postal code
+ CountryCode = 56, // Country code (e.g., USA = 56)
+ ServiceCategory = 999 // Example service category
+ };
- // Resolve the MaxiCode symbology as a BaseEncodeType
- BaseEncodeType encodeType = EncodeTypes.MaxiCode;
+ // Add a simple second message
+ var secondMessage = new MaxiCodeStandardSecondMessage
+ {
+ Message = "Sample MaxiCode"
+ };
+ maxiCodeCodetext.SecondMessage = secondMessage;
- // Create a memory stream to hold the generated barcode image
- using (var memoryStream = new MemoryStream())
+ // Generate the barcode image into a memory stream
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Initialize the barcode generator with the specified type and text
- using (var generator = new BarcodeGenerator(encodeType, codeText))
+ using (var ms = new MemoryStream())
{
- // Save the generated barcode as a PNG image into the memory stream
- generator.Save(memoryStream, BarCodeImageFormat.Png);
- }
-
- // Reset stream position to the beginning before reading its contents
- memoryStream.Position = 0;
+ // Save the barcode as PNG to the stream
+ generator.Save(ms, BarCodeImageFormat.Png);
- // Convert the image bytes from the stream to a Base64-encoded string
- string base64 = Convert.ToBase64String(memoryStream.ToArray());
+ // Convert the image bytes to a Base64 string
+ string base64 = Convert.ToBase64String(ms.ToArray());
- // Output the Base64 string (e.g., for embedding in JSON)
- Console.WriteLine(base64);
+ // Output the Base64 string (can be embedded in JSON)
+ Console.WriteLine(base64);
+ }
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/generate-maxicode-barcode-with-custom-margin-of-10-pixels-on-all-sides-for-better-visual-separation.cs b/maxicode-barcode/generate-maxicode-barcode-with-custom-margin-of-10-pixels-on-all-sides-for-better-visual-separation.cs
index b6ce2a8..f88fb45 100644
--- a/maxicode-barcode/generate-maxicode-barcode-with-custom-margin-of-10-pixels-on-all-sides-for-better-visual-separation.cs
+++ b/maxicode-barcode/generate-maxicode-barcode-with-custom-margin-of-10-pixels-on-all-sides-for-better-visual-separation.cs
@@ -1,38 +1,42 @@
+// Title: Generate MaxiCode barcode with custom margins
+// Description: Creates a MaxiCode barcode (Mode 4) and applies a 10‑pixel margin on all sides before saving as PNG.
+// Category-Description: This example demonstrates how to use Aspose.BarCode's ComplexBarcodeGenerator to produce two‑dimensional barcodes with custom layout settings. It focuses on the MaxiCode symbology, showing how to configure padding via the Parameters.Barcode.Padding properties. Developers working with shipping labels, logistics, or any application requiring MaxiCode can reuse this pattern to adjust visual spacing and output format.
+// Prompt: Generate a MaxiCode barcode with a custom margin of 10 pixels on all sides for better visual separation.
+// Tags: maxicode, barcode, margin, padding, png, aspose.barcode, complexbarcodegenerator
+
using System;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generating a MaxiCode barcode using Aspose.BarCode.
+/// Demonstrates generation of a MaxiCode barcode with a uniform 10‑pixel margin using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Creates a MaxiCode barcode and saves it as a PNG file.
+ /// Entry point of the example. Creates a MaxiCode (Mode 4) barcode, sets padding, and saves it as a PNG file.
///
static void Main()
{
- // Create a standard MaxiCode codetext (Mode 4) with a simple message.
- var maxiCode = new MaxiCodeStandardCodetext
+ // Define the MaxiCode content: Mode 4 with a simple message.
+ var maxiCodeCodetext = new MaxiCodeStandardCodetext
{
Mode = MaxiCodeMode.Mode4,
Message = "Sample MaxiCode"
};
- // Initialize ComplexBarcodeGenerator with the codetext.
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ // Initialize the ComplexBarcodeGenerator with the defined codetext.
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Set a custom margin of 10 points on all sides.
- generator.Parameters.Barcode.Padding.Left.Point = 10f;
- generator.Parameters.Barcode.Padding.Top.Point = 10f;
- generator.Parameters.Barcode.Padding.Right.Point = 10f;
+ // Apply a 10‑pixel margin on all four sides of the barcode.
+ generator.Parameters.Barcode.Padding.Left.Point = 10f;
+ generator.Parameters.Barcode.Padding.Top.Point = 10f;
+ generator.Parameters.Barcode.Padding.Right.Point = 10f;
generator.Parameters.Barcode.Padding.Bottom.Point = 10f;
- // Save the generated barcode image to a PNG file.
+ // Save the resulting barcode image to a PNG file.
generator.Save("maxicode.png");
}
-
- // Inform the user that the barcode has been generated.
- Console.WriteLine("MaxiCode barcode generated: maxicode.png");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/generate-maxicode-barcode-with-custom-quiet-zone-size-to-meet-specific-scanning-requirements.cs b/maxicode-barcode/generate-maxicode-barcode-with-custom-quiet-zone-size-to-meet-specific-scanning-requirements.cs
index 0a31adc..ae3d142 100644
--- a/maxicode-barcode/generate-maxicode-barcode-with-custom-quiet-zone-size-to-meet-specific-scanning-requirements.cs
+++ b/maxicode-barcode/generate-maxicode-barcode-with-custom-quiet-zone-size-to-meet-specific-scanning-requirements.cs
@@ -1,54 +1,82 @@
+// Title: Generate MaxiCode Barcode with Custom Quiet Zone
+// Description: Demonstrates creating a MaxiCode barcode (Mode 2) with a custom quiet zone and saving it as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related classes to produce a MaxiCode symbol. Typical use cases include shipping labels, parcel tracking, and inventory management where MaxiCode is required. Developers often need to adjust quiet zone (padding) settings to meet scanner specifications, making this example a useful reference for customizing barcode layout.
+/// Prompt: Generate a MaxiCode barcode with a custom quiet zone size to meet specific scanning requirements.
+/// Tags: maxicode, barcode, quiet zone, complexbarcode, generation, png, aspose.barcode
+
using System;
+using System.IO;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates generation of a MaxiCode barcode (Mode 2) using Aspose.BarCode.
+/// Example program that generates a MaxiCode barcode with a custom quiet zone,
+/// saves it to a file, and optionally reads it back to verify decoding.
///
class Program
{
///
- /// Entry point of the application. Generates a MaxiCode barcode and saves it as a PNG file.
+ /// Entry point of the example. Creates a MaxiCode (Mode 2) barcode,
+ /// applies a 10‑point padding on all sides, saves the image, and
+ /// demonstrates decoding the saved barcode.
///
static void Main()
{
- // Define the output file path for the generated barcode image.
- string outputPath = "maxicode.png";
-
- // Create MaxiCode codetext for Mode 2 (postal + data).
+ // Prepare MaxiCode codetext (Mode 2 with a standard second message)
var maxiCodeCodetext = new MaxiCodeCodetextMode2
{
- PostalCode = "524032140", // 9‑digit US postal code.
- CountryCode = 56, // Country code (e.g., 056 for USA).
- ServiceCategory = 999 // Example service category.
+ PostalCode = "524032140", // 9‑digit US postal code
+ CountryCode = 56, // USA
+ ServiceCategory = 999
};
-
- // Create the standard second message (simple text) and assign it to the codetext.
var secondMessage = new MaxiCodeStandardSecondMessage
{
- Message = "Sample MaxiCode data"
+ Message = "Sample MaxiCode"
};
maxiCodeCodetext.SecondMessage = secondMessage;
- // Generate the MaxiCode barcode using ComplexBarcodeGenerator.
+ // Create the complex barcode generator with the codetext
using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Set custom quiet zone (padding) around the barcode.
- generator.Parameters.Barcode.Padding.Left.Point = 20f;
- generator.Parameters.Barcode.Padding.Top.Point = 20f;
- generator.Parameters.Barcode.Padding.Right.Point = 20f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 20f;
-
- // Optional: set foreground (barcode) and background colors.
- generator.Parameters.Barcode.BarColor = Color.Black;
- generator.Parameters.BackColor = Color.White;
+ // Set a custom quiet zone (padding) – 10 points on each side
+ generator.Parameters.Barcode.Padding.Left.Point = 10f;
+ generator.Parameters.Barcode.Padding.Right.Point = 10f;
+ generator.Parameters.Barcode.Padding.Top.Point = 10f;
+ generator.Parameters.Barcode.Padding.Bottom.Point = 10f;
- // Save the barcode image as a PNG file.
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ // Save the generated MaxiCode image
+ string outputPath = "maxicode.png";
+ generator.Save(outputPath);
+ Console.WriteLine($"MaxiCode barcode saved to: {Path.GetFullPath(outputPath)}");
}
- // Inform the user where the barcode image has been saved.
- Console.WriteLine($"MaxiCode barcode saved to: {outputPath}");
+ // Optional: read back the barcode to verify it can be decoded
+ if (File.Exists("maxicode.png"))
+ {
+ using (var reader = new BarCodeReader("maxicode.png", DecodeType.MaxiCode))
+ {
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Decode the MaxiCode codetext using the complex codetext reader
+ var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
+ result.Extended.MaxiCode.MaxiCodeMode,
+ result.CodeText);
+
+ if (decoded is MaxiCodeCodetextMode2 decodedMode2)
+ {
+ Console.WriteLine("Decoded MaxiCode:");
+ Console.WriteLine($" PostalCode: {decodedMode2.PostalCode}");
+ Console.WriteLine($" CountryCode: {decodedMode2.CountryCode}");
+ Console.WriteLine($" ServiceCategory: {decodedMode2.ServiceCategory}");
+ if (decodedMode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
+ {
+ Console.WriteLine($" Message: {stdMsg.Message}");
+ }
+ }
+ }
+ }
+ }
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/generate-maxicode-barcode-with-structured-secondary-message-containing-recipient-name-street-and-city-fields.cs b/maxicode-barcode/generate-maxicode-barcode-with-structured-secondary-message-containing-recipient-name-street-and-city-fields.cs
index 5807006..21e558c 100644
--- a/maxicode-barcode/generate-maxicode-barcode-with-structured-secondary-message-containing-recipient-name-street-and-city-fields.cs
+++ b/maxicode-barcode/generate-maxicode-barcode-with-structured-secondary-message-containing-recipient-name-street-and-city-fields.cs
@@ -1,48 +1,58 @@
+// Title: Generate MaxiCode barcode with structured secondary message
+// Description: Demonstrates creating a MaxiCode (Mode 2) barcode that includes a structured secondary message containing recipient name, street, and city.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and MaxiCodeStructuredSecondMessage classes to encode both primary and secondary data. Developers often need to generate shipping labels or logistics barcodes where additional address information is embedded in the secondary message.
+// Prompt: Generate a MaxiCode barcode with a structured secondary message containing recipient name, street, and city fields.
+// Tags: maxicode, complex barcode, secondary message, shipping label, aspnet.barcode, generation, png
+
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation of a MaxiCode barcode with a structured secondary message using Aspose.BarCode.
+/// Demonstrates generating a MaxiCode barcode with a structured secondary message.
///
class Program
{
///
- /// Entry point of the application. Generates a MaxiCode barcode and saves it as a PNG file.
+ /// Entry point. Generates the barcode and saves it as a PNG file.
///
static void Main()
{
- // Define the output file path for the generated barcode image.
+ // Define the output file path for the generated barcode image
string outputPath = "maxicode.png";
- // Create a structured secondary message containing recipient details.
- var structuredMessage = new MaxiCodeStructuredSecondMessage();
- structuredMessage.Add("John Doe"); // Recipient name
- structuredMessage.Add("123 Main Street"); // Street address
- structuredMessage.Add("Anytown"); // City
- structuredMessage.Year = 23; // Optional year field (e.g., 2023)
-
- // Configure the MaxiCode codetext for Mode 3 (suitable for worldwide postal codes).
- var maxiCodeCodetext = new MaxiCodeCodetextMode3
+ // Prepare MaxiCode codetext for Mode 2, including required primary fields
+ var maxiCodeCodetext = new MaxiCodeCodetextMode2
{
- PostalCode = "B1050", // Example alphanumeric postal code
- CountryCode = 056, // Example 3‑digit country code
- ServiceCategory = 999, // Example service category
- SecondMessage = structuredMessage // Attach the structured secondary message
+ PostalCode = "123456789", // 9‑digit postal code required for Mode 2
+ CountryCode = 840, // USA numeric country code
+ ServiceCategory = 999 // Example service category
};
- // Generate the MaxiCode barcode using ComplexBarcodeGenerator.
+ // Build the structured secondary message with recipient address details
+ var secondaryMessage = new MaxiCodeStructuredSecondMessage();
+ secondaryMessage.Add("John Doe"); // Recipient name
+ secondaryMessage.Add("123 Main St"); // Street address
+ secondaryMessage.Add("Anytown"); // City
+
+ // Assign the secondary message to the MaxiCode codetext
+ maxiCodeCodetext.SecondMessage = secondaryMessage;
+
+ // Generate the MaxiCode barcode using the complex barcode generator
using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Set the image resolution (dots per inch) – optional but improves quality.
- generator.Parameters.Resolution = 300f;
-
- // Save the generated barcode image as a PNG file.
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ using (Image barcodeImage = generator.GenerateBarCodeImage())
+ {
+ // Save the generated barcode image as a PNG file
+ barcodeImage.Save(outputPath, ImageFormat.Png);
+ }
}
- // Inform the user where the barcode image has been saved.
- Console.WriteLine($"MaxiCode barcode saved to: {outputPath}");
+ // Output the full path of the saved barcode image to the console
+ Console.WriteLine($"MaxiCode barcode saved to: {Path.GetFullPath(outputPath)}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/generate-maxicode-mode-2-barcode-with-unstructured-secondary-message-and-save-it-as-png.cs b/maxicode-barcode/generate-maxicode-mode-2-barcode-with-unstructured-secondary-message-and-save-it-as-png.cs
index e0ffbec..10934cf 100644
--- a/maxicode-barcode/generate-maxicode-mode-2-barcode-with-unstructured-secondary-message-and-save-it-as-png.cs
+++ b/maxicode-barcode/generate-maxicode-mode-2-barcode-with-unstructured-secondary-message-and-save-it-as-png.cs
@@ -1,52 +1,47 @@
+// Title: Generate MaxiCode Mode 2 barcode with secondary message
+// Description: Demonstrates creating a MaxiCode Mode 2 barcode, adding an unstructured secondary message, 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 MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related secondary message classes to produce high‑density 2‑D barcodes for shipping and logistics applications. Developers often need to encode postal information and custom messages for automated sorting systems.
+// Prompt: Generate a MaxiCode Mode 2 barcode with an unstructured secondary message and save it as PNG.
+// Tags: maxicode, mode2, secondary-message, png, generation, complexbarcodegenerator, maxicodecodetextmode2, maxicodesstandardsecondmessage
+
using System;
-using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation of a MaxiCode Mode 2 barcode and saves it as a PNG file.
+/// Demonstrates generating a MaxiCode Mode 2 barcode with an unstructured secondary message and saving it as a PNG file.
///
class Program
{
///
- /// Entry point of the application. Creates a MaxiCode Mode 2 codetext,
- /// configures a secondary message, generates the barcode image, and saves it.
+ /// Entry point of the example. Creates the codetext, configures the generator, and saves the barcode image.
///
static void Main()
{
- // Define the output file path for the generated PNG image.
- string outputPath = "maxicode_mode2.png";
+ // Initialize MaxiCode Mode 2 codetext object
+ var codetext = new MaxiCodeCodetextMode2();
- // Initialize MaxiCode Mode 2 codetext with required fields.
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
- {
- // 9‑digit US postal code (example value).
- PostalCode = "524032140",
- // Country code (example value).
- CountryCode = 56,
- // Service category (example value).
- ServiceCategory = 999
- };
+ // Set required postal information
+ codetext.PostalCode = "524032140"; // 9‑digit US postal code
+ codetext.CountryCode = 56; // Example country code
+ codetext.ServiceCategory = 999; // Example service category
- // Create an unstructured (standard) secondary message.
+ // Create an unstructured (standard) secondary message
var secondMessage = new MaxiCodeStandardSecondMessage
{
- // Text of the secondary message.
Message = "Sample secondary message"
};
- // Assign the secondary message to the MaxiCode codetext.
- maxiCodeCodetext.SecondMessage = secondMessage;
+ codetext.SecondMessage = secondMessage; // Attach secondary message to codetext
- // Use ComplexBarcodeGenerator to generate the barcode image.
- using (var complexGenerator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Generate the barcode using ComplexBarcodeGenerator
+ using (var generator = new ComplexBarcodeGenerator(codetext))
{
- // Generate the barcode image in memory.
- complexGenerator.GenerateBarCodeImage();
+ // Optional: set image resolution (dots per inch)
+ generator.Parameters.Resolution = 300;
- // Save the generated image to the specified file path.
- complexGenerator.Save(outputPath);
+ // Save the generated barcode as a PNG file
+ generator.Save("maxicode_mode2.png");
}
-
- // Inform the user where the barcode image has been saved.
- Console.WriteLine($"MaxiCode Mode 2 barcode saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/generate-maxicode-mode-4-barcode-with-default-primary-data-and-store-result-in-bmp-format.cs b/maxicode-barcode/generate-maxicode-mode-4-barcode-with-default-primary-data-and-store-result-in-bmp-format.cs
index f515e43..5660b23 100644
--- a/maxicode-barcode/generate-maxicode-mode-4-barcode-with-default-primary-data-and-store-result-in-bmp-format.cs
+++ b/maxicode-barcode/generate-maxicode-mode-4-barcode-with-default-primary-data-and-store-result-in-bmp-format.cs
@@ -1,46 +1,43 @@
+// Title: Generate MaxiCode Mode 4 Barcode and Save as BMP
+// Description: Creates a MaxiCode Mode 4 barcode with default primary data and writes it to a BMP image file.
+// Category-Description: This example demonstrates how to use Aspose.BarCode's ComplexBarcodeGenerator to produce a MaxiCode barcode, specifically Mode 4, which is commonly used for shipping and logistics. It showcases the MaxiCodeStandardCodetext class for setting mode and message, configuring image resolution, and saving the result in BMP format. Developers working with advanced barcode symbologies can refer to this pattern for generating other complex barcodes.
+// Prompt: Generate a MaxiCode Mode 4 barcode with default primary data and store the result in BMP format.
+// Tags: maxicode, barcode generation, bmp, aspose.barcode, complexbarcode, csharp
+
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation of a MaxiCode barcode in Mode 4 using Aspose.BarCode.
+/// Demonstrates generation of a MaxiCode Mode 4 barcode and saving it as a BMP image using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates a MaxiCode Mode 4 barcode and saves it as a BMP file.
+ /// Entry point of the example. Creates a MaxiCode barcode, configures parameters, and saves the image.
///
static void Main()
{
- // Define the output file name (saved in the current working directory)
- string outputPath = "maxicode_mode4.bmp";
+ // Initialize standard codetext for MaxiCode Mode 4
+ var maxiCodeCodetext = new MaxiCodeStandardCodetext();
+ maxiCodeCodetext.Mode = MaxiCodeMode.Mode4; // Set barcode mode to Mode 4
+ maxiCodeCodetext.Message = "Test message"; // Set the primary data message
- // Prepare the MaxiCode codetext with Mode 4 and a sample message
- var maxiCodeCodetext = new MaxiCodeStandardCodetext
+ // Generate the barcode using ComplexBarcodeGenerator
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- Mode = MaxiCodeMode.Mode4,
- Message = "Sample message"
- };
+ // Optional: define image resolution (dots per inch)
+ generator.Parameters.Resolution = 300;
- // Attempt to generate the barcode and write it to disk
- try
- {
- // Initialize the complex barcode generator with the prepared codetext
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
- {
- // Save the generated barcode as a BMP image to the specified path
- generator.Save(outputPath, BarCodeImageFormat.Bmp);
- }
+ // Define output file name and format
+ string outputFile = "maxicode_mode4.bmp";
- // Output the full path of the saved image for user confirmation
- Console.WriteLine($"MaxiCode Mode 4 barcode saved to: {Path.GetFullPath(outputPath)}");
- }
- catch (Exception ex)
- {
- // Report any errors that occur during barcode generation or file saving
- Console.WriteLine($"Error generating barcode: {ex.Message}");
+ // Save the generated barcode as BMP
+ generator.Save(outputFile, BarCodeImageFormat.Bmp);
}
+
+ // Inform the user that the barcode has been saved
+ Console.WriteLine("MaxiCode Mode 4 barcode saved successfully.");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/implement-batch-generation-of-maxicode-mode-2-barcodes-from-csv-file-containing-primary-and-secondary-data-rows.cs b/maxicode-barcode/implement-batch-generation-of-maxicode-mode-2-barcodes-from-csv-file-containing-primary-and-secondary-data-rows.cs
index 8f8c8a8..becd01e 100644
--- a/maxicode-barcode/implement-batch-generation-of-maxicode-mode-2-barcodes-from-csv-file-containing-primary-and-secondary-data-rows.cs
+++ b/maxicode-barcode/implement-batch-generation-of-maxicode-mode-2-barcodes-from-csv-file-containing-primary-and-secondary-data-rows.cs
@@ -1,108 +1,119 @@
+// Title: Batch Generation of MaxiCode Mode 2 Barcodes from CSV
+// Description: Demonstrates reading a CSV file containing primary and secondary data rows and creating MaxiCode Mode 2 barcodes for each record.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of MaxiCodeCodetextMode2, MaxiCodeStandardSecondMessage, and MaxiCodeStructuredSecondMessage classes to build MaxiCode data structures, and the ComplexBarcodeGenerator to render PNG images. Developers working with shipping, logistics, or any application that requires bulk creation of MaxiCode symbols will find this pattern useful for automating barcode production from data sources such as CSV files.
+// Prompt: Implement batch generation of MaxiCode Mode 2 barcodes from a CSV file containing primary and secondary data rows.
+// Tags: maxicode, batch, csv, barcode generation, aspose.barcode, complexbarcode, png
+
using System;
using System.IO;
using System.Collections.Generic;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates batch generation of MaxiCode barcodes from CSV or sample data.
+/// Provides a console application that reads a CSV file and generates a batch of MaxiCode Mode 2 barcodes.
///
class Program
{
///
- /// Entry point of the application. Reads input data, generates MaxiCode barcodes, and saves them as PNG files.
+ /// Entry point of the application. Reads input data, creates MaxiCode objects, and saves barcode images.
///
static void Main()
{
- // Path to the input CSV file containing barcode data.
- string csvPath = "maxicode_input.csv";
-
- // List to hold rows of data read from the CSV or fallback sample data.
- List rows = new List();
+ // Input CSV path (relative to executable)
+ string csvPath = "input.csv";
- // Check if the CSV file exists before attempting to read it.
- if (File.Exists(csvPath))
+ // If the CSV does not exist, create a small sample file
+ if (!File.Exists(csvPath))
{
- // Read each line of the CSV file. This simple parser splits on commas and trims whitespace.
- foreach (var line in File.ReadAllLines(csvPath))
+ var sampleLines = new[]
{
- // Skip empty or whitespace-only lines.
- if (string.IsNullOrWhiteSpace(line)) continue;
-
- // Split the line into parts based on commas.
- var parts = line.Split(',');
-
- // Expect at least four columns: PostalCode, CountryCode, ServiceCategory, Message.
- if (parts.Length >= 4)
- {
- // Trim each part and add as a string array to the rows collection.
- rows.Add(new[] { parts[0].Trim(), parts[1].Trim(), parts[2].Trim(), parts[3].Trim() });
- }
- }
- }
- else
- {
- // CSV not found – use hard‑coded sample data as a fallback.
- rows.Add(new[] { "524032140", "056", "999", "Sample message 1" });
- rows.Add(new[] { "524032141", "056", "998", "Sample message 2" });
- rows.Add(new[] { "524032142", "056", "997", "Sample message 3" });
+ "PostalCode,CountryCode,ServiceCategory,SecondMessageType,SecondMessageContent",
+ "524032140,056,999,Standard,Test message 1",
+ "123456789,840,100,Standard,Hello World",
+ "987654321,124,200,Structured,634 ALPHA DRIVE|PITTSBURGH|PA",
+ "111222333,036,300,Standard,Sample Text",
+ "444555666,124,400,Structured,123 MAIN ST|ANYTOWN|CA"
+ };
+ File.WriteAllLines(csvPath, sampleLines);
}
- // Ensure the output directory exists; create it if necessary.
- string outputDir = "MaxiCodeOutputs";
+ // Ensure output directory exists
+ string outputDir = "output";
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
- // Process each row and generate a corresponding MaxiCode barcode.
- int index = 1;
- foreach (var fields in rows)
+ // Read all lines from CSV (including header)
+ var lines = File.ReadAllLines(csvPath);
+ int barcodesGenerated = 0;
+
+ // Process each data line, limiting to 5 barcodes for the demo
+ for (int i = 1; i < lines.Length && barcodesGenerated < 5; i++)
{
- try
+ string line = lines[i];
+ if (string.IsNullOrWhiteSpace(line))
+ continue; // Skip empty lines
+
+ // Split CSV fields
+ string[] parts = line.Split(',');
+ if (parts.Length < 5)
+ continue; // Skip malformed lines
+
+ // Trim whitespace from each field
+ for (int p = 0; p < parts.Length; p++)
+ parts[p] = parts[p].Trim();
+
+ // Build MaxiCode codetext for Mode 2 using primary fields
+ var maxiCode = new MaxiCodeCodetextMode2
{
- // Build the codetext for MaxiCode Mode 2 using the first three fields.
- var maxiCode = new MaxiCodeCodetextMode2
- {
- PostalCode = fields[0],
- CountryCode = int.Parse(fields[1]),
- ServiceCategory = int.Parse(fields[2])
- };
+ PostalCode = parts[0],
+ CountryCode = int.Parse(parts[1]),
+ ServiceCategory = int.Parse(parts[2])
+ };
- // Attach the standard second message (fourth field) to the MaxiCode.
- var secondMessage = new MaxiCodeStandardSecondMessage
+ // Determine and assign the appropriate second message type
+ if (parts[3].Equals("Standard", StringComparison.OrdinalIgnoreCase))
+ {
+ var stdMsg = new MaxiCodeStandardSecondMessage
{
- Message = fields[3]
+ Message = parts[4]
};
- maxiCode.SecondMessage = secondMessage;
+ maxiCode.SecondMessage = stdMsg;
+ }
+ else if (parts[3].Equals("Structured", StringComparison.OrdinalIgnoreCase))
+ {
+ var structMsg = new MaxiCodeStructuredSecondMessage();
- // Generate the barcode using the ComplexBarcodeGenerator.
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ // Structured content parts are separated by '|'
+ string[] identifiers = parts[4].Split('|');
+ foreach (var id in identifiers)
{
- // Set a high resolution for the output image (optional).
- generator.Parameters.Resolution = 300f;
-
- // Construct the output file path and save the barcode as a PNG.
- string outputPath = Path.Combine(outputDir, $"maxicode_{index}.png");
- generator.Save(outputPath, BarCodeImageFormat.Png);
-
- // Inform the user that the barcode was generated successfully.
- Console.WriteLine($"Generated barcode {index}: {outputPath}");
+ structMsg.Add(id.Trim());
}
+
+ // Year is optional; not provided in this sample
+ maxiCode.SecondMessage = structMsg;
}
- catch (Exception ex)
+ else
+ {
+ // Unknown message type – skip this record
+ continue;
+ }
+
+ // Generate and save the barcode image as PNG
+ string outputPath = Path.Combine(outputDir, $"MaxiCode_{barcodesGenerated + 1}.png");
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
{
- // Report any errors that occur while processing the current row.
- Console.WriteLine($"Error processing row {index}: {ex.Message}");
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Move to the next index for naming the subsequent output file.
- index++;
+ Console.WriteLine($"Generated barcode {barcodesGenerated + 1}: {outputPath}");
+ barcodesGenerated++;
}
- // Indicate that the batch generation process has finished.
Console.WriteLine("Batch generation completed.");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/implement-error-handling-that-catches-barcodeexception-when-decoding-unreadable-maxicode-image.cs b/maxicode-barcode/implement-error-handling-that-catches-barcodeexception-when-decoding-unreadable-maxicode-image.cs
index 19276c4..9734938 100644
--- a/maxicode-barcode/implement-error-handling-that-catches-barcodeexception-when-decoding-unreadable-maxicode-image.cs
+++ b/maxicode-barcode/implement-error-handling-that-catches-barcodeexception-when-decoding-unreadable-maxicode-image.cs
@@ -1,80 +1,57 @@
using System;
using System.IO;
-using Aspose.BarCode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.Drawing;
-///
-/// Demonstrates generation of a MaxiCode barcode, intentional corruption of the image,
-/// and handling of decoding attempts with proper exception handling.
-///
class Program
{
- ///
- /// Entry point of the application.
- /// Generates a MaxiCode, corrupts its image data, and attempts to read it back.
- ///
static void Main()
{
- // --------------------------------------------------------------------
- // 1. Create a simple MaxiCode codetext (Mode 2) with required fields.
- // --------------------------------------------------------------------
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // Path to the MaxiCode image (replace with an actual file path if needed)
+ string imagePath = "unreadable_maxicode.png";
+
+ // Validate that the image file exists
+ if (!File.Exists(imagePath))
{
- PostalCode = "524032140",
- CountryCode = 56,
- ServiceCategory = 999,
- SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Test" }
- };
+ Console.WriteLine($"File not found: {imagePath}");
+ return;
+ }
- // ---------------------------------------------------------------
- // 2. Generate a valid MaxiCode image and store it in a memory stream.
- // ---------------------------------------------------------------
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
- using (var ms = new MemoryStream())
+ try
{
- // Save the barcode as PNG into the memory stream.
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for further operations.
+ // Create a BarCodeReader for MaxiCode symbology
+ using (var reader = new BarCodeReader(imagePath, DecodeType.MaxiCode))
+ {
+ // Read all barcodes from the image
+ var results = reader.ReadBarCodes();
- // ---------------------------------------------------------------
- // 3. Corrupt the image data to simulate an unreadable barcode.
- // Overwrite the first few bytes with arbitrary values.
- // ---------------------------------------------------------------
- byte[] corruptBytes = { 0xFF, 0x00, 0xFF, 0x00 };
- ms.Write(corruptBytes, 0, corruptBytes.Length);
- ms.Position = 0; // Reset again before reading.
+ if (results.Length == 0)
+ {
+ Console.WriteLine("No barcodes detected.");
+ }
- // ---------------------------------------------------------------
- // 4. Attempt to decode the corrupted MaxiCode image.
- // Handle both barcode-specific and generic exceptions.
- // ---------------------------------------------------------------
- try
- {
- using (var reader = new BarCodeReader(ms, DecodeType.MaxiCode))
+ foreach (var result in results)
{
- // Read all barcodes found in the stream.
- var results = reader.ReadBarCodes();
+ // Attempt to decode the MaxiCode codetext using ComplexCodetextReader
+ var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
+ result.Extended.MaxiCode.MaxiCodeMode,
+ result.CodeText);
- // Output each decoded result to the console.
- foreach (var result in results)
+ if (decoded != null)
+ {
+ Console.WriteLine($"Decoded MaxiCode codetext: {decoded.GetConstructedCodetext()}");
+ }
+ else
{
- Console.WriteLine($"Decoded CodeText: {result.CodeText}");
+ Console.WriteLine("Failed to decode MaxiCode codetext.");
}
}
}
- catch (BarCodeException ex)
- {
- // Specific exception thrown by Aspose.BarCode when decoding fails.
- Console.WriteLine($"BarcodeException caught: {ex.Message}");
- }
- catch (Exception ex)
- {
- // Fallback for any other unexpected errors.
- Console.WriteLine($"Unexpected exception: {ex.Message}");
- }
+ }
+ catch (Exception ex)
+ {
+ // Handle any errors that occur during decoding (e.g., unreadable image)
+ Console.WriteLine($"Error decoding barcode: {ex.Message}");
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/implement-retry-mechanism-that-attempts-to-decode-maxicode-barcode-up-to-three-times-on-failure.cs b/maxicode-barcode/implement-retry-mechanism-that-attempts-to-decode-maxicode-barcode-up-to-three-times-on-failure.cs
index 433a144..a7dc76b 100644
--- a/maxicode-barcode/implement-retry-mechanism-that-attempts-to-decode-maxicode-barcode-up-to-three-times-on-failure.cs
+++ b/maxicode-barcode/implement-retry-mechanism-that-attempts-to-decode-maxicode-barcode-up-to-three-times-on-failure.cs
@@ -1,125 +1,119 @@
+// Title: Decode MaxiCode barcode with retry mechanism
+// Description: Demonstrates generating a MaxiCode barcode in memory and attempting to decode it up to three times, handling failures gracefully.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing the use of ComplexBarcodeGenerator, BarCodeReader, and related classes for MaxiCode symbology. Developers often need to generate complex barcodes, read them from streams, and implement retry logic for unreliable scans. The snippet illustrates typical workflow and error handling for MaxiCode decoding.
+// Prompt: Implement a retry mechanism that attempts to decode a MaxiCode barcode up to three times on failure.
+// Tags: maxicode, barcode generation, barcode recognition, retry, aspose.barcode, complexbarcode
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation and recognition of a MaxiCode (Mode 2) barcode using Aspose.BarCode.
+/// Demonstrates generating a MaxiCode barcode and decoding it with retry logic.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a MaxiCode barcode, attempts to read it up to three times,
- /// and outputs the decoded information to the console.
+ /// Entry point of the example. Generates a MaxiCode barcode in memory, then attempts to decode it up to three times.
///
static void Main()
{
- // --------------------------------------------------------------------
- // 1. Create a sample MaxiCode codetext (Mode 2) with required fields.
- // --------------------------------------------------------------------
+ // Create a sample MaxiCode barcode (Mode 2) in memory
var maxiCode = new MaxiCodeCodetextMode2
{
PostalCode = "524032140",
CountryCode = 56,
- ServiceCategory = 999,
- SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Sample message" }
+ ServiceCategory = 999
};
- // ---------------------------------------------------------------
- // 2. Generate the barcode image and store it in a memory stream.
- // ---------------------------------------------------------------
- using (var barcodeStream = new MemoryStream())
+ // Add a second message to the barcode
+ var secondMessage = new MaxiCodeStandardSecondMessage
{
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
- {
- // Save the generated barcode as PNG into the memory stream.
- generator.Save(barcodeStream, BarCodeImageFormat.Png);
- }
+ Message = "Sample message"
+ };
+ maxiCode.SecondMessage = secondMessage;
- // -----------------------------------------------------------
- // 3. Prepare for up to three read attempts of the generated image.
- // -----------------------------------------------------------
- bool decoded = false;
- const int maxAttempts = 3;
+ // Generate the barcode image and store it in a memory stream
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ using (var imageStream = new MemoryStream())
+ {
+ // Save the barcode image to the memory stream in PNG format
+ generator.Save(imageStream, BarCodeImageFormat.Png);
+ // Reset stream position to the beginning for reading
+ imageStream.Position = 0;
+
+ const int maxAttempts = 3; // Maximum number of decode attempts
+ bool decoded = false; // Flag indicating successful decode
+
+ // Retry loop: attempt to read and decode the barcode up to maxAttempts times
for (int attempt = 1; attempt <= maxAttempts && !decoded; attempt++)
{
- try
+ // Ensure the stream is positioned at the start before each read
+ imageStream.Position = 0;
+
+ // Initialize the barcode reader for MaxiCode symbology
+ using (var reader = new BarCodeReader(imageStream, DecodeType.MaxiCode))
{
- // Reset the stream position to the beginning before each read.
- barcodeStream.Position = 0;
+ // Use high-quality settings to improve detection reliability
+ reader.QualitySettings = QualitySettings.MaxQuality;
+
+ // Read all barcodes found in the stream
+ var results = reader.ReadBarCodes();
- // Initialize the barcode reader for MaxiCode type.
- using (var reader = new BarCodeReader(barcodeStream, DecodeType.MaxiCode))
+ if (results.Length == 0)
{
- // Allow recognition of imperfect barcodes.
- reader.QualitySettings.AllowIncorrectBarcodes = true;
+ Console.WriteLine($"Attempt {attempt}: No barcode detected.");
+ continue; // Proceed to next attempt
+ }
- // Perform the read operation.
- var results = reader.ReadBarCodes();
+ // Process each detected barcode
+ foreach (var result in results)
+ {
+ // Attempt to decode the MaxiCode codetext using the structured reader
+ var decodedCodetext = ComplexCodetextReader.TryDecodeMaxiCode(
+ result.Extended.MaxiCode.MaxiCodeMode,
+ result.CodeText);
- if (results.Length > 0)
+ if (decodedCodetext != null)
{
- // Process each detected barcode.
- foreach (var result in results)
+ // Decoding succeeded – output the extracted information
+ Console.WriteLine($"Attempt {attempt}: Decoding succeeded.");
+ var structured = (MaxiCodeStructuredCodetext)decodedCodetext;
+ Console.WriteLine($"Postal Code: {structured.PostalCode}");
+ Console.WriteLine($"Country Code: {structured.CountryCode}");
+ Console.WriteLine($"Service Category: {structured.ServiceCategory}");
+
+ // If the barcode is Mode 2, display the second message
+ if (decodedCodetext is MaxiCodeCodetextMode2 mode2 &&
+ mode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
{
- // Decode the complex MaxiCode codetext.
- var decodedCodetext = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
-
- // Verify that the decoded codetext matches the expected Mode 2 type.
- if (decodedCodetext is MaxiCodeCodetextMode2 mode2)
- {
- Console.WriteLine($"Attempt {attempt}: Decoded successfully.");
- Console.WriteLine($"PostalCode: {mode2.PostalCode}");
- Console.WriteLine($"CountryCode: {mode2.CountryCode}");
- Console.WriteLine($"ServiceCategory: {mode2.ServiceCategory}");
-
- // Output the optional second message if present.
- if (mode2.SecondMessage is MaxiCodeStandardSecondMessage msg)
- {
- Console.WriteLine($"Message: {msg.Message}");
- }
- }
- else
- {
- Console.WriteLine($"Attempt {attempt}: Decoded but unexpected codetext type.");
- }
+ Console.WriteLine($"Message: {stdMsg.Message}");
}
- // Mark as successfully decoded to exit the retry loop.
- decoded = true;
+ decoded = true; // Mark as successfully decoded
+ break; // Exit the foreach loop
}
else
{
- Console.WriteLine($"Attempt {attempt}: No barcode detected.");
+ Console.WriteLine($"Attempt {attempt}: Decoding failed for detected barcode.");
}
}
- }
- catch (Exception ex)
- {
- // Log any exception that occurs during the read attempt.
- Console.WriteLine($"Attempt {attempt}: Exception - {ex.Message}");
- }
- // If not decoded and more attempts remain, indicate a retry.
- if (!decoded && attempt < maxAttempts)
- {
- Console.WriteLine("Retrying...");
+ // If not decoded and more attempts remain, indicate a retry
+ if (!decoded && attempt < maxAttempts)
+ {
+ Console.WriteLine($"Retrying... (attempt {attempt + 1} of {maxAttempts})");
+ }
}
}
- // -----------------------------------------------------------
- // 4. Final outcome after all attempts.
- // -----------------------------------------------------------
+ // Final outcome after all attempts
if (!decoded)
{
- Console.WriteLine("Failed to decode after 3 attempts.");
+ Console.WriteLine("Failed to decode the MaxiCode barcode after maximum attempts.");
}
}
}
diff --git a/maxicode-barcode/include-iso-country-identifier-in-secondary-structured-message-of-maxicode-mode-3-barcode.cs b/maxicode-barcode/include-iso-country-identifier-in-secondary-structured-message-of-maxicode-mode-3-barcode.cs
index e64d5fa..4c28afe 100644
--- a/maxicode-barcode/include-iso-country-identifier-in-secondary-structured-message-of-maxicode-mode-3-barcode.cs
+++ b/maxicode-barcode/include-iso-country-identifier-in-secondary-structured-message-of-maxicode-mode-3-barcode.cs
@@ -1,44 +1,65 @@
+// Title: Generate MaxiCode Mode 3 barcode with ISO country identifier in secondary message
+// Description: Demonstrates how to create a MaxiCode Mode 3 barcode and embed an ISO country identifier in its structured secondary message.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on MaxiCode symbology. It showcases the use of MaxiCodeCodetextMode3, MaxiCodeStructuredSecondMessage, and ComplexBarcodeGenerator classes to build and render a MaxiCode with custom postal, country, and service data—common tasks for shipping and logistics applications. Developers often need to encode address information and ISO country codes for automated parcel sorting systems.
+// Prompt: Include an ISO country identifier in the secondary structured message of a MaxiCode Mode 3 barcode.
+// Tags: maxicode, mode3, secondarymessage, iso country code, barcode generation, aspnet, aspose.barcode, png output
+
using System;
+using System.IO;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates generation of a MaxiCode Mode 3 barcode using Aspose.BarCode.
+/// Entry point for the example that generates a MaxiCode Mode 3 barcode with a structured secondary message containing an ISO country identifier.
///
class Program
{
///
- /// Entry point of the application. Creates a MaxiCode Mode 3 codetext,
- /// adds a structured secondary message, generates the barcode, and saves it as a PNG file.
+ /// Generates the barcode, saves it as PNG, and writes the output path to the console.
///
static void Main()
{
- // Create a MaxiCode Mode 3 codetext object and set its primary fields.
+ // Define the output file name for the generated barcode image
+ const string outputFile = "maxicode_mode3.png";
+
+ // Create MaxiCode codetext for Mode 3 with required fields
var maxiCode = new MaxiCodeCodetextMode3
{
- PostalCode = "B1050", // 6‑character alphanumeric postal code
- CountryCode = 840, // Numeric ISO country code (e.g., 840 = USA)
- ServiceCategory = 999 // Service category identifier
+ // 6‑character alphanumeric postal code (example)
+ PostalCode = "B1050",
+ // 3‑digit numeric ISO country code (example: 056 = Belgium)
+ CountryCode = 056,
+ // Service category (example)
+ ServiceCategory = 999
};
- // Build a structured secondary message consisting of address lines and country code.
+ // Build the structured secondary message
var secondaryMessage = new MaxiCodeStructuredSecondMessage();
- secondaryMessage.Add("634 ALPHA DRIVE"); // Street address
- secondaryMessage.Add("PITTSBURGH"); // City
- secondaryMessage.Add("PA"); // State abbreviation
- secondaryMessage.Add("US"); // ISO country identifier
- secondaryMessage.Year = 99; // Two‑digit year
- // Attach the secondary message to the MaxiCode codetext.
+ // Include ISO country identifier as the first line (e.g., "US")
+ secondaryMessage.Add("US");
+ // Additional address lines
+ secondaryMessage.Add("634 ALPHA DRIVE");
+ secondaryMessage.Add("PITTSBURGH");
+ secondaryMessage.Add("PA");
+ // Set the year (last two digits)
+ secondaryMessage.Year = 99;
+
+ // Assign the structured second message to the codetext
maxiCode.SecondMessage = secondaryMessage;
- // Generate the MaxiCode barcode and save it as a PNG image.
+ // Generate the MaxiCode barcode using ComplexBarcodeGenerator
using (var generator = new ComplexBarcodeGenerator(maxiCode))
{
- generator.Save("maxicode_mode3.png"); // Save the barcode image
+ // Generate the barcode image
+ generator.GenerateBarCodeImage();
+
+ // Save the image to a PNG file
+ generator.Save(outputFile, BarCodeImageFormat.Png);
}
- // Inform the user that the barcode has been generated.
- Console.WriteLine("MaxiCode Mode 3 barcode generated: maxicode_mode3.png");
+ // Inform the user where the barcode image was saved
+ Console.WriteLine($"MaxiCode Mode 3 barcode saved to: {Path.GetFullPath(outputFile)}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/produce-maxicode-mode-5-barcode-set-custom-image-width-and-height-and-save-it-as-tiff.cs b/maxicode-barcode/produce-maxicode-mode-5-barcode-set-custom-image-width-and-height-and-save-it-as-tiff.cs
index 148ad7d..33b7f09 100644
--- a/maxicode-barcode/produce-maxicode-mode-5-barcode-set-custom-image-width-and-height-and-save-it-as-tiff.cs
+++ b/maxicode-barcode/produce-maxicode-mode-5-barcode-set-custom-image-width-and-height-and-save-it-as-tiff.cs
@@ -1,37 +1,40 @@
+// Title: Generate MaxiCode Mode 5 barcode and save as TIFF
+// Description: Demonstrates creating a MaxiCode Mode 5 barcode, customizing its image size, and exporting it to a TIFF file.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on MaxiCode symbology. It showcases the use of BarcodeGenerator, EncodeTypes, and MaxiCodeMode classes to produce high‑density 2‑D barcodes, a common requirement for shipping and logistics applications where compact data encoding and error correction are needed. Developers often need to adjust image dimensions and output formats, which this sample illustrates.
+// Prompt: Produce a MaxiCode Mode 5 barcode, set custom image width and height, and save it as TIFF.
+// Tags: maxicode, mode5, barcode generation, image size, tiff, aspose.barcode
+
using System;
-using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation of a MaxiCode barcode (Mode 5) using Aspose.BarCode.
+/// Entry point for the MaxiCode Mode 5 barcode generation example.
///
class Program
{
///
- /// Entry point of the application. Creates a MaxiCode barcode, configures its size,
- /// saves it to a TIFF file, and writes a confirmation message to the console.
+ /// Generates a MaxiCode Mode 5 barcode with custom dimensions and saves it as a TIFF image.
///
static void Main()
{
- // Initialize MaxiCode data with Mode 5 and a sample message.
- var maxiCode = new MaxiCodeStandardCodetext
+ // Initialize a barcode generator for the MaxiCode symbology
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MaxiCode))
{
- Mode = MaxiCodeMode.Mode5,
- Message = "Sample MaxiCode Mode 5"
- };
+ // Assign the data to be encoded (standard test message for Mode 5)
+ generator.CodeText = "Test message";
- // Create a barcode generator for the specified MaxiCode data.
- using (ComplexBarcodeGenerator generator = new ComplexBarcodeGenerator(maxiCode))
- {
- // Set the desired image dimensions (in points).
- generator.Parameters.ImageWidth.Point = 300f; // Width of the barcode image
- generator.Parameters.ImageHeight.Point = 200f; // Height of the barcode image
+ // Configure the generator to use MaxiCode Mode 5 (data with long ECC correction)
+ generator.Parameters.Barcode.MaxiCode.MaxiCodeMode = MaxiCodeMode.Mode5;
- // Save the generated barcode to a TIFF file.
- generator.Save("MaxiCodeMode5.tiff");
- }
+ // Set custom image dimensions (width and height in points)
+ generator.Parameters.ImageWidth.Point = 300f;
+ generator.Parameters.ImageHeight.Point = 200f;
- // Inform the user that the barcode has been saved.
- Console.WriteLine("MaxiCode Mode 5 barcode saved as MaxiCodeMode5.tiff");
+ // Save the generated barcode as a TIFF file
+ generator.Save("maxicode_mode5.tiff");
+ }
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/rotate-generated-maxicode-barcode-by-90-degrees-and-save-rotated-image-as-gif.cs b/maxicode-barcode/rotate-generated-maxicode-barcode-by-90-degrees-and-save-rotated-image-as-gif.cs
index e29de9b..fc7fc03 100644
--- a/maxicode-barcode/rotate-generated-maxicode-barcode-by-90-degrees-and-save-rotated-image-as-gif.cs
+++ b/maxicode-barcode/rotate-generated-maxicode-barcode-by-90-degrees-and-save-rotated-image-as-gif.cs
@@ -1,39 +1,57 @@
+// Title: Rotate MaxiCode Barcode and Save as GIF
+// Description: Generates a MaxiCode barcode, rotates it 90 degrees, and saves the rotated image as a GIF file.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It demonstrates how to use the ComplexBarcodeGenerator with MaxiCodeCodetextMode2 to create a MaxiCode symbol, then employs Aspose.Drawing to manipulate the resulting image (rotation) before saving. Developers working with high‑density 2‑D barcodes often need to adjust orientation for printing or display purposes, and this pattern shows the typical workflow using key API classes such as ComplexBarcodeGenerator, MaxiCodeCodetextMode2, Image, and RotateFlipType.
+/// Prompt: Rotate a generated MaxiCode barcode by 90 degrees and save the rotated image as GIF.
+/// Tags: maxicode, rotation, gif, aspose.barcode, complexbarcode, imageprocessing
+
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a MaxiCode barcode, rotating it, and saving as a GIF image.
+/// Demonstrates generating a MaxiCode barcode, rotating it 90°,
+/// and saving the rotated image as a GIF file.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Creates a MaxiCode barcode, rotates the image,
+ /// and writes the result to disk.
///
static void Main()
{
- // Create a MaxiCodeStandardCodetext object with Mode 4 and a sample message.
- var maxiCodeCodetext = new MaxiCodeStandardCodetext
+ // Prepare MaxiCode codetext (Mode 2 example) with required fields.
+ var maxiCode = new MaxiCodeCodetextMode2
{
- Mode = MaxiCodeMode.Mode4,
- Message = "Sample MaxiCode"
+ PostalCode = "524032140",
+ CountryCode = 56,
+ ServiceCategory = 999
};
- // Initialize the ComplexBarcodeGenerator with the prepared codetext.
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Add a second message to the MaxiCode payload.
+ var secondMessage = new MaxiCodeStandardSecondMessage
{
- // Configure the rotation angle (root parameter) to rotate the barcode 90 degrees.
- generator.Parameters.RotationAngle = 90f;
-
- // Define the output file path for the rotated GIF image.
- string outputPath = "maxicode_rotated.gif";
+ Message = "Sample Message"
+ };
+ maxiCode.SecondMessage = secondMessage;
- // Save the generated barcode image as a GIF file.
- generator.Save(outputPath, BarCodeImageFormat.Gif);
+ // Generate the MaxiCode image into a memory stream using ComplexBarcodeGenerator.
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ using (var memory = new MemoryStream())
+ {
+ generator.Save(memory, BarCodeImageFormat.Png);
+ memory.Position = 0; // Reset stream position for reading.
- // Inform the user about the saved file location.
- Console.WriteLine($"Rotated MaxiCode saved to: {outputPath}");
+ // Load the image with Aspose.Drawing, rotate 90 degrees, and save as GIF.
+ using (var image = Image.FromStream(memory))
+ {
+ image.RotateFlip(RotateFlipType.Rotate90FlipNone);
+ image.Save("maxicode_rotated.gif", ImageFormat.Gif);
+ }
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/set-barcode-image-dpi-to-300-when-generating-maxicode-to-improve-print-quality.cs b/maxicode-barcode/set-barcode-image-dpi-to-300-when-generating-maxicode-to-improve-print-quality.cs
index 2b20b70..ae12f44 100644
--- a/maxicode-barcode/set-barcode-image-dpi-to-300-when-generating-maxicode-to-improve-print-quality.cs
+++ b/maxicode-barcode/set-barcode-image-dpi-to-300-when-generating-maxicode-to-improve-print-quality.cs
@@ -1,49 +1,54 @@
+// Title: Generate MaxiCode barcode with 300 DPI resolution
+// Description: Demonstrates creating a MaxiCode barcode and setting its image DPI to 300 for high‑quality printing.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related classes to produce MaxiCode symbols. Developers often need to adjust image resolution, embed secondary messages, and export to common formats like PNG for printing or scanning applications.
+// Prompt: Set the barcode image DPI to 300 when generating a MaxiCode to improve print quality.
+// Tags: maxicode, barcode generation, dpi, image resolution, aspose.barcode, png
+
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates generation of a MaxiCode barcode using Aspose.BarCode library.
+/// Example program that creates a MaxiCode barcode with a 300 DPI image resolution.
///
class Program
{
///
- /// Entry point of the application. Generates a MaxiCode barcode (Mode 2) with a standard second message
- /// and saves it as a PNG image.
+ /// Entry point of the application. Generates a MaxiCode, sets its DPI, and saves it as a PNG file.
///
static void Main()
{
- // Create a MaxiCode codetext object for Mode 2 with required fields
+ // Define the output file name
+ string outputPath = "maxicode.png";
+
+ // Prepare MaxiCode codetext (Mode 2 example) with required fields
var maxiCodeCodetext = new MaxiCodeCodetextMode2
{
- PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // Example country code
- ServiceCategory = 999 // Example service category
+ PostalCode = "524032140", // 9‑digit US postal code
+ CountryCode = 056, // USA country code
+ ServiceCategory = 999 // Example service category
};
- // Create the standard second message to be embedded in the barcode
+ // Add a simple second message to the MaxiCode
var secondMessage = new MaxiCodeStandardSecondMessage
{
- Message = "Sample MaxiCode message"
+ Message = "Sample MaxiCode"
};
-
- // Assign the second message to the MaxiCode codetext
maxiCodeCodetext.SecondMessage = secondMessage;
- // Initialize the ComplexBarcodeGenerator with the prepared codetext
+ // Generate the MaxiCode using the complex barcode generator
using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Configure image resolution (dots per inch) for higher print quality
+ // Set image resolution to 300 DPI for high‑quality print output
generator.Parameters.Resolution = 300f;
- // Define output file path and save the barcode as a PNG image
- string outputPath = "maxicode.png";
+ // Save the generated barcode image as a PNG file
generator.Save(outputPath, BarCodeImageFormat.Png);
-
- // Inform the user where the barcode image was saved
- Console.WriteLine($"MaxiCode barcode saved to: {outputPath}");
}
+
+ // Inform the user where the file was saved
+ Console.WriteLine($"MaxiCode saved to '{Path.GetFullPath(outputPath)}' with 300 DPI.");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/set-generator-s-imageformat-property-to-gif-and-produce-series-of-maxicode-images.cs b/maxicode-barcode/set-generator-s-imageformat-property-to-gif-and-produce-series-of-maxicode-images.cs
index a260a81..68f81e8 100644
--- a/maxicode-barcode/set-generator-s-imageformat-property-to-gif-and-produce-series-of-maxicode-images.cs
+++ b/maxicode-barcode/set-generator-s-imageformat-property-to-gif-and-produce-series-of-maxicode-images.cs
@@ -1,62 +1,58 @@
+// Title: Generate MaxiCode Barcodes as GIF Images
+// Description: Demonstrates creating multiple MaxiCode barcodes and saving them as GIF files.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class with EncodeTypes.MaxiCode and BarCodeImageFormat to produce barcode images. Typical use cases include batch creation of shipping labels, inventory tags, or any scenario requiring MaxiCode symbols in a lightweight GIF format. Developers often need to automate image format selection and file naming for large sets of barcodes.
+/// Prompt: Set the generator's ImageFormat property to GIF and produce a series of MaxiCode images.
+/// Tags: maxicode, barcode generation, gif, aspose.barcode, imageformat, encode types
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation of MaxiCode barcodes in different modes using Aspose.BarCode.
+/// Example program that generates a series of MaxiCode barcodes and saves each as a GIF image.
///
class Program
{
///
- /// Entry point of the application. Creates an output directory,
- /// generates MaxiCode images for several modes, and reports the result.
+ /// Entry point of the application. Creates an output directory, iterates over sample messages,
+ /// generates a MaxiCode barcode for each, and saves the result as a GIF file.
///
static void Main()
{
- // Determine the output directory path relative to the current working directory.
- string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "MaxiCodeImages");
-
- // Ensure the output directory exists; create it if it does not.
+ // Define the directory where generated images will be stored
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "MaxiCodeOutputs");
if (!Directory.Exists(outputDir))
{
+ // Create the directory if it does not already exist
Directory.CreateDirectory(outputDir);
}
- // Generate MaxiCode images for Mode 4, Mode 5, and Mode 6.
- GenerateMaxiCode(outputDir, MaxiCodeMode.Mode4, "Sample message for Mode 4", "maxicode_mode4.gif");
- GenerateMaxiCode(outputDir, MaxiCodeMode.Mode5, "Sample message for Mode 5", "maxicode_mode5.gif");
- GenerateMaxiCode(outputDir, MaxiCodeMode.Mode6, "Sample message for Mode 6", "maxicode_mode6.gif");
-
- // Inform the user where the images have been saved.
- Console.WriteLine("MaxiCode images have been generated in: " + outputDir);
- }
-
- ///
- /// Generates a MaxiCode barcode image using the specified mode, message, and file name.
- ///
- /// The directory where the image will be saved.
- /// The MaxiCode mode to use (e.g., Mode4, Mode5, Mode6).
- /// The text message to encode in the barcode.
- /// The name of the output image file.
- private static void GenerateMaxiCode(string folder, MaxiCodeMode mode, string message, string fileName)
- {
- // Prepare the standard MaxiCode codetext with the specified mode and message.
- var codetext = new MaxiCodeStandardCodetext
+ // Sample messages to encode in the MaxiCode barcodes
+ string[] messages = new string[]
{
- Mode = mode,
- Message = message
+ "Sample Message 1",
+ "Sample Message 2",
+ "Sample Message 3",
+ "Sample Message 4",
+ "Sample Message 5"
};
- // Use a ComplexBarcodeGenerator to create and save the barcode image.
- using (var generator = new ComplexBarcodeGenerator(codetext))
+ // Loop through each message, generate a barcode, and save it as a GIF image
+ for (int i = 0; i < messages.Length; i++)
{
- // Combine the folder path and file name to get the full output path.
- string outputPath = Path.Combine(folder, fileName);
+ // Build the full file path for the current image
+ string filePath = Path.Combine(outputDir, $"maxicode_{i + 1}.gif");
- // Save the generated barcode as a GIF image.
- generator.Save(outputPath, BarCodeImageFormat.Gif);
+ // Initialize the barcode generator with MaxiCode symbology and the current message
+ using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, messages[i]))
+ {
+ // Save the generated barcode image in GIF format
+ generator.Save(filePath, BarCodeImageFormat.Gif);
+ }
}
+
+ // Inform the user about the successful generation
+ Console.WriteLine($"Generated {messages.Length} MaxiCode GIF images in: {outputDir}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/set-generator-s-modulesize-property-to-2-to-produce-denser-maxicode-image-for-compact-labels.cs b/maxicode-barcode/set-generator-s-modulesize-property-to-2-to-produce-denser-maxicode-image-for-compact-labels.cs
index f77674f..a08153b 100644
--- a/maxicode-barcode/set-generator-s-modulesize-property-to-2-to-produce-denser-maxicode-image-for-compact-labels.cs
+++ b/maxicode-barcode/set-generator-s-modulesize-property-to-2-to-produce-denser-maxicode-image-for-compact-labels.cs
@@ -1,34 +1,43 @@
+// Title: Generate a dense MaxiCode barcode with custom module size
+// Description: Demonstrates how to set the ModuleSize (XDimension) to 2 points for a denser MaxiCode, suitable for compact label printing.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on MaxiCode symbology. It showcases the use of BarcodeGenerator, EncodeTypes, and XDimension properties to control barcode density. Developers creating packaging, shipping labels, or inventory tags often need to adjust module size for space‑constrained layouts.
+// Prompt: Set the generator's ModuleSize property to 2 to produce a denser MaxiCode image for compact labels.
+// Tags: maxicode, module size, barcode generation, png, aspose.barcode, encoding
+
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation of a MaxiCode barcode using Aspose.BarCode.
+/// Demonstrates generating a MaxiCode barcode with a custom module size for denser output.
///
class Program
{
///
- /// Entry point of the application. Generates and saves a MaxiCode barcode.
+ /// Entry point. Generates a MaxiCode barcode, sets XDimension to 2 points, and saves as PNG.
///
static void Main()
{
- // The text to encode in the MaxiCode barcode.
+ // Sample codetext for MaxiCode
const string codeText = "Sample MaxiCode";
- // Initialize the barcode generator with MaxiCode type and the specified text.
+ // Output file path
+ string outputPath = "maxicode.png";
+
+ // Create a MaxiCode generator
using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, codeText))
{
- // Set the X-dimension (module width) of the barcode to 2 points.
+ // Set module size (XDimension) to 2 points for a denser image
generator.Parameters.Barcode.XDimension.Point = 2f;
- // Define the output file path for the generated barcode image.
- const string outputPath = "maxicode.png";
-
- // Save the generated barcode image to the specified path.
- generator.Save(outputPath);
-
- // Inform the user where the barcode image has been saved.
- Console.WriteLine($"MaxiCode barcode saved to: {outputPath}");
+ // Save the generated barcode as PNG
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
+
+ // Inform the user where the file was saved
+ Console.WriteLine($"MaxiCode barcode saved to: {Path.GetFullPath(outputPath)}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/upload-generated-maxicode-png-file-to-azure-blob-storage-using-azure-sdk-after-successful-creation.cs b/maxicode-barcode/upload-generated-maxicode-png-file-to-azure-blob-storage-using-azure-sdk-after-successful-creation.cs
index bb4f551..142a58b 100644
--- a/maxicode-barcode/upload-generated-maxicode-png-file-to-azure-blob-storage-using-azure-sdk-after-successful-creation.cs
+++ b/maxicode-barcode/upload-generated-maxicode-png-file-to-azure-blob-storage-using-azure-sdk-after-successful-creation.cs
@@ -1,84 +1,90 @@
+// Title: Generate MaxiCode PNG and upload to Azure Blob Storage
+// Description: Demonstrates creating a MaxiCode barcode (Mode 2) as a PNG image using Aspose.BarCode and outlines how to upload the generated file to Azure Blob storage.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related classes to produce high‑density 2‑D barcodes, a common requirement for logistics and shipping applications. Developers often need to generate these barcodes programmatically and store them in cloud services like Azure for further processing or distribution.
+// Prompt: Upload a generated MaxiCode PNG file to Azure Blob storage using the Azure SDK after successful creation.
+// Tags: maxicode, generation, png, complexbarcode, azureblob, aspnet, barcode
+
using System;
using System.IO;
using Aspose.BarCode;
-using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation of a MaxiCode barcode and saving it locally,
-/// with optional Azure Blob Storage upload (commented out).
+/// Example program that creates a MaxiCode barcode image and demonstrates how to upload it to Azure Blob storage.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a MaxiCode barcode, writes it to a PNG file,
- /// and contains placeholder code for uploading to Azure Blob Storage.
+ /// Entry point of the application. Generates a MaxiCode PNG and optionally uploads it to Azure Blob storage.
///
static void Main()
{
- // --------------------------------------------------------------------
- // Prepare MaxiCode codetext (Mode 4 with a simple message)
- // --------------------------------------------------------------------
- var maxiCodeCodetext = new MaxiCodeStandardCodetext
+ // Prepare MaxiCode codetext (Mode 2) with sample data
+ var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ {
+ PostalCode = "524032140", // 9‑digit US postal code
+ CountryCode = 56, // USA numeric country code
+ ServiceCategory = 999 // Sample service category
+ };
+
+ // Standard second message (optional additional data)
+ var secondMessage = new MaxiCodeStandardSecondMessage
{
- Mode = MaxiCodeMode.Mode4,
- Message = "Hello from Aspose"
+ Message = "Sample MaxiCode message"
};
+ maxiCodeCodetext.SecondMessage = secondMessage;
- // --------------------------------------------------------------------
- // Generate the barcode image into a memory stream
- // --------------------------------------------------------------------
- using (var memoryStream = new MemoryStream())
+ // Generate the MaxiCode image into a memory stream
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Create a generator for the complex barcode using the prepared codetext
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ using (var ms = new MemoryStream())
{
- // Save the generated barcode as PNG into the memory stream
- generator.Save(memoryStream, BarCodeImageFormat.Png);
- }
+ // Save the barcode as PNG to the memory stream
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for subsequent reads
- // Reset stream position to the beginning for subsequent reads
- memoryStream.Position = 0;
+ // Write the PNG to a local file (fallback for environments without Azure SDK)
+ const string localPath = "maxicode.png";
+ using (var fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write))
+ {
+ ms.CopyTo(fileStream);
+ }
- // ----------------------------------------------------------------
- // Save the barcode image locally (fallback when Azure SDK is unavailable)
- // ----------------------------------------------------------------
- const string localFilePath = "maxicode.png";
+ Console.WriteLine($"MaxiCode image saved locally to '{localPath}'.");
- // Create a file stream and copy the memory stream contents into it
- using (var fileStream = File.Create(localFilePath))
- {
- memoryStream.CopyTo(fileStream);
- }
+ // ------------------------------------------------------------
+ // Azure Blob Storage upload (requires Azure.Storage.Blobs package)
+ // The following code demonstrates the intended upload logic.
+ // Uncomment and ensure the Azure.Storage.Blobs NuGet package is referenced
+ // when running in an environment where Azure SDK is available.
+ // ------------------------------------------------------------
+ /*
+ try
+ {
+ // Replace with your actual Azure Storage connection string and container name
+ string connectionString = "";
+ string containerName = "";
+ string blobName = "maxicode.png";
- Console.WriteLine($"Barcode image saved locally to '{localFilePath}'.");
+ // Create a BlobServiceClient to interact with the storage account
+ var blobServiceClient = new Azure.Storage.Blobs.BlobServiceClient(connectionString);
+ var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
+ containerClient.CreateIfNotExists();
- // ----------------------------------------------------------------
- // Azure Blob Storage upload (requires Azure.Storage.Blobs package)
- // ----------------------------------------------------------------
- // Replace the placeholders below with your actual Azure Storage connection details.
- // string connectionString = "";
- // string containerName = "barcode-container";
- // string blobName = "maxicode.png";
+ // Get a reference to the blob and upload the image
+ var blobClient = containerClient.GetBlobClient(blobName);
+ ms.Position = 0; // Reset stream position before upload
+ blobClient.Upload(ms, overwrite: true);
- // try
- // {
- // // Uncomment the following lines after adding the Azure.Storage.Blobs NuGet package.
- // /*
- // var blobServiceClient = new Azure.Storage.Blobs.BlobServiceClient(connectionString);
- // var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
- // containerClient.CreateIfNotExists();
- // var blobClient = containerClient.GetBlobClient(blobName);
- // memoryStream.Position = 0; // Ensure stream is at the beginning
- // blobClient.Upload(memoryStream, overwrite: true);
- // Console.WriteLine($"Uploaded to Azure Blob Storage: {blobClient.Uri}");
- // */
- // }
- // catch (Exception ex)
- // {
- // Console.WriteLine($"Azure upload failed: {ex.Message}");
- // }
+ Console.WriteLine($"MaxiCode image uploaded to Azure Blob storage as '{blobName}'.");
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Azure upload failed: {ex.Message}");
+ }
+ */
+ }
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/use-async-methods-to-generate-maxicode-image-and-write-it-to-file-without-blocking-ui.cs b/maxicode-barcode/use-async-methods-to-generate-maxicode-image-and-write-it-to-file-without-blocking-ui.cs
index fcf7912..3fa3e32 100644
--- a/maxicode-barcode/use-async-methods-to-generate-maxicode-image-and-write-it-to-file-without-blocking-ui.cs
+++ b/maxicode-barcode/use-async-methods-to-generate-maxicode-image-and-write-it-to-file-without-blocking-ui.cs
@@ -1,54 +1,66 @@
+// Title: Generate MaxiCode barcode asynchronously and save as PNG
+// Description: Demonstrates using async/await to create a MaxiCode barcode image without blocking the UI thread.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on complex barcode symbologies such as MaxiCode. It showcases the ComplexBarcodeGenerator and MaxiCodeCodetextMode2 classes for creating high‑density 2‑D barcodes, a common requirement in logistics and shipping applications. Developers often need to generate these barcodes in background tasks to keep UI responsive.
+// Prompt: Use async methods to generate a MaxiCode image and write it to a file without blocking the UI.
+// Tags: maxicode, barcode, async, generation, png, aspose.barcode, complexbarcodegenerator
+
using System;
using System.IO;
using System.Threading.Tasks;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation of a MaxiCode barcode using Aspose.BarCode.
+/// Demonstrates asynchronous generation of a MaxiCode barcode image and saving it to a file.
///
class Program
{
///
- /// Entry point that creates a MaxiCode barcode (Mode 2) with a standard second message
- /// and saves it as a PNG file.
+ /// Entry point of the console application. Calls the asynchronous barcode generation method.
///
/// Command‑line arguments (not used).
static async Task Main(string[] args)
{
- // Define the output file name for the generated barcode image.
+ // Define the output file path for the generated PNG image
string outputPath = "maxicode.png";
- // Configure the MaxiCode codetext for Mode 2.
- // This includes a 9‑digit postal code, a country code, and a service category.
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
- {
- PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // Example country code
- ServiceCategory = 999 // Example service category
- };
+ // Generate the MaxiCode barcode asynchronously
+ await GenerateMaxiCodeAsync(outputPath);
- // Create the standard second message that accompanies the MaxiCode.
- var secondMessage = new MaxiCodeStandardSecondMessage
- {
- Message = "Sample MaxiCode message"
- };
- // Attach the second message to the codetext.
- maxiCodeCodetext.SecondMessage = secondMessage;
+ // Inform the user that the image has been saved
+ Console.WriteLine($"MaxiCode image saved to: {outputPath}");
+ }
- // Generate and save the barcode on a background thread to avoid blocking.
+ ///
+ /// Generates a MaxiCode barcode using the ComplexBarcodeGenerator and saves it to the specified path.
+ /// The operation runs on a background thread to avoid blocking the UI.
+ ///
+ /// File system path where the PNG image will be saved.
+ static async Task GenerateMaxiCodeAsync(string path)
+ {
+ // Execute the barcode generation on a thread‑pool thread
await Task.Run(() =>
{
- // ComplexBarcodeGenerator is required for MaxiCode generation.
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Prepare MaxiCode codetext (Mode 2 with a standard second message)
+ var maxiCode = new MaxiCodeCodetextMode2
+ {
+ PostalCode = "524032140",
+ CountryCode = 56,
+ ServiceCategory = 999
+ };
+
+ // Create the optional second message for the MaxiCode
+ var secondMessage = new MaxiCodeStandardSecondMessage
{
- // Save the generated barcode as a PNG file.
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ Message = "Sample message"
+ };
+ maxiCode.SecondMessage = secondMessage;
+
+ // Generate and save the barcode image using the ComplexBarcodeGenerator
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ {
+ generator.Save(path, BarCodeImageFormat.Png);
}
});
-
- // Output the full path of the saved image for user confirmation.
- Console.WriteLine($"MaxiCode image saved to: {Path.GetFullPath(outputPath)}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/use-barcodereader-to-decode-maxicode-image-streamed-from-network-socket-without-saving-to-disk.cs b/maxicode-barcode/use-barcodereader-to-decode-maxicode-image-streamed-from-network-socket-without-saving-to-disk.cs
index 5d068cb..1877dce 100644
--- a/maxicode-barcode/use-barcodereader-to-decode-maxicode-image-streamed-from-network-socket-without-saving-to-disk.cs
+++ b/maxicode-barcode/use-barcodereader-to-decode-maxicode-image-streamed-from-network-socket-without-saving-to-disk.cs
@@ -1,115 +1,111 @@
+// Title: Decode MaxiCode from Network Stream using BarcodeReader
+// Description: Demonstrates decoding a MaxiCode barcode received over a TCP socket without writing the image to disk.
+// Category-Description: This example belongs to the Aspose.BarCode reading and complex barcode handling category. It showcases the use of BarCodeReader, ComplexCodetextReader, and related classes to decode MaxiCode symbols directly from a streamed image. Developers working with real‑time barcode scanning, networked devices, or in‑memory image processing will find such patterns useful for building low‑latency barcode solutions.
+// Prompt: Use the BarcodeReader to decode a MaxiCode image streamed from a network socket without saving to disk.
+// Tags: maxicode, barcode decoding, network stream, barcodereader, aspose.barcode, complexbarcode, tcp
+
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
-using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generating a MaxiCode barcode, transmitting it over a TCP connection,
-/// and decoding it using Aspose.BarCode libraries.
+/// Example program that generates a MaxiCode barcode, streams it over a TCP socket,
+/// and decodes it directly from the received network stream using Aspose.BarCode APIs.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a MaxiCode image, sends it via a TCP listener, receives it on a client,
- /// and decodes the barcode data.
+ /// Entry point of the example. Generates a MaxiCode image in memory, sends it via a TCP server,
+ /// receives it as a client, and decodes the barcode without persisting the image to disk.
///
static void Main()
{
- // Generate a sample MaxiCode image in memory and obtain its PNG byte array.
- byte[] maxiCodeBytes = GenerateMaxiCodeImage();
+ // ------------------------------------------------------------
+ // Generate a sample MaxiCode image in memory
+ // ------------------------------------------------------------
+ var maxiCode = new MaxiCodeCodetextMode2();
+ maxiCode.PostalCode = "524032140";
+ maxiCode.CountryCode = 56;
+ maxiCode.ServiceCategory = 999;
+ var secondMessage = new MaxiCodeStandardSecondMessage();
+ secondMessage.Message = "Sample message";
+ maxiCode.SecondMessage = secondMessage;
- // Set up a TCP listener on a free (ephemeral) port bound to the loopback address.
- using (var listener = new TcpListener(IPAddress.Loopback, 0))
+ byte[] imageBytes;
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
{
- listener.Start();
- int port = ((IPEndPoint)listener.LocalEndpoint).Port;
+ using (var ms = new MemoryStream())
+ {
+ // Save the generated barcode as PNG into the memory stream
+ generator.Save(ms, BarCodeImageFormat.Png);
+ imageBytes = ms.ToArray(); // Capture the image bytes for transmission
+ }
+ }
- // Server task: accept a client connection and send the image bytes.
- Task serverTask = Task.Run(() =>
+ // ------------------------------------------------------------
+ // Start a simple TCP server that sends the image bytes
+ // ------------------------------------------------------------
+ var listener = new TcpListener(IPAddress.Loopback, 5000);
+ listener.Start();
+ var serverTask = Task.Run(() =>
+ {
+ using (var client = listener.AcceptTcpClient())
+ using (var networkStream = client.GetStream())
{
- using (TcpClient serverClient = listener.AcceptTcpClient())
- using (NetworkStream serverStream = serverClient.GetStream())
- {
- // Write the entire image byte array to the network stream.
- serverStream.Write(maxiCodeBytes, 0, maxiCodeBytes.Length);
- serverStream.Flush();
- }
- });
+ // Write the entire image byte array to the connected client
+ networkStream.Write(imageBytes, 0, imageBytes.Length);
+ }
+ });
- // Client: connect to the server and read the transmitted image stream.
- using (var client = new TcpClient())
+ // ------------------------------------------------------------
+ // Connect as a client and read the image stream
+ // ------------------------------------------------------------
+ using (var client = new TcpClient())
+ {
+ client.Connect(IPAddress.Loopback, 5000);
+ using (var netStream = client.GetStream())
+ using (var receivedMs = new MemoryStream())
{
- client.Connect(IPAddress.Loopback, port);
- using (NetworkStream clientStream = client.GetStream())
- using (var memory = new MemoryStream())
- {
- // Copy the incoming data into a memory stream for later processing.
- clientStream.CopyTo(memory);
- memory.Position = 0; // Reset position to the beginning for reading.
+ // Copy the incoming data into a memory stream for decoding
+ netStream.CopyTo(receivedMs);
+ receivedMs.Position = 0; // Reset position to the beginning
- // Decode the MaxiCode from the received memory stream.
- using (var reader = new BarCodeReader(memory, DecodeType.MaxiCode))
+ // --------------------------------------------------------
+ // Decode the MaxiCode from the received stream
+ // --------------------------------------------------------
+ using (var reader = new BarCodeReader(receivedMs, DecodeType.MaxiCode))
+ {
+ foreach (var result in reader.ReadBarCodes())
{
- foreach (var result in reader.ReadBarCodes())
- {
- // Attempt to decode complex MaxiCode codetext based on its mode.
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
-
- // Output basic barcode information.
- Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Raw CodeText: {result.CodeText}");
+ // Attempt to parse the complex MaxiCode codetext into a strongly‑typed object
+ var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
+ result.Extended.MaxiCode.MaxiCodeMode,
+ result.CodeText);
- // If the decoded data matches Mode 2, display its specific fields.
- if (decoded is MaxiCodeCodetextMode2 mode2)
+ if (decoded is MaxiCodeCodetextMode2 decodedMode2)
+ {
+ Console.WriteLine("Postal Code: " + decodedMode2.PostalCode);
+ Console.WriteLine("Country Code: " + decodedMode2.CountryCode);
+ Console.WriteLine("Service Category: " + decodedMode2.ServiceCategory);
+ if (decodedMode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
{
- Console.WriteLine($"Postal Code: {mode2.PostalCode}");
- Console.WriteLine($"Country Code: {mode2.CountryCode}");
- Console.WriteLine($"Service Category: {mode2.ServiceCategory}");
-
- // If a standard second message is present, display it.
- if (mode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
- {
- Console.WriteLine($"Message: {stdMsg.Message}");
- }
+ Console.WriteLine("Message: " + stdMsg.Message);
}
}
}
}
}
-
- // Ensure the server task has completed before exiting.
- serverTask.Wait();
}
- }
- ///
- /// Generates a simple MaxiCode (Mode 2) image and returns its PNG byte array.
- ///
- /// Byte array containing the PNG representation of the generated MaxiCode.
- private static byte[] GenerateMaxiCodeImage()
- {
- // Define the codetext for a Mode 2 MaxiCode with sample data.
- var codetext = new MaxiCodeCodetextMode2
- {
- PostalCode = "524032140",
- CountryCode = 56,
- ServiceCategory = 999,
- SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Test message" }
- };
-
- // Use the ComplexBarcodeGenerator to create the barcode and save it to a memory stream.
- using (var generator = new ComplexBarcodeGenerator(codetext))
- using (var ms = new MemoryStream())
- {
- generator.Save(ms, BarCodeImageFormat.Png);
- return ms.ToArray(); // Return the PNG bytes.
- }
+ // ------------------------------------------------------------
+ // Ensure the server task completes and clean up resources
+ // ------------------------------------------------------------
+ serverTask.Wait();
+ listener.Stop();
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/use-maxicodecodetext-helper-to-concatenate-multiple-secondary-messages-into-single-unstructured-field.cs b/maxicode-barcode/use-maxicodecodetext-helper-to-concatenate-multiple-secondary-messages-into-single-unstructured-field.cs
index ec04a42..96cd045 100644
--- a/maxicode-barcode/use-maxicodecodetext-helper-to-concatenate-multiple-secondary-messages-into-single-unstructured-field.cs
+++ b/maxicode-barcode/use-maxicodecodetext-helper-to-concatenate-multiple-secondary-messages-into-single-unstructured-field.cs
@@ -1,58 +1,55 @@
+// Title: Generate MaxiCode barcode with concatenated secondary messages
+// Description: Demonstrates how to use MaxiCodeCodetext helper to combine multiple secondary messages into a single unstructured field and generate a MaxiCode barcode.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on MaxiCode symbology. It showcases the use of MaxiCodeCodetextMode2, MaxiCodeStandardSecondMessage, and ComplexBarcodeGenerator classes to create postal‑oriented MaxiCode barcodes. Developers often need to embed additional data such as secondary messages, postal codes, and service categories when generating MaxiCode for shipping and logistics applications.
+// Prompt: Use the MaxiCodeCodetext helper to concatenate multiple secondary messages into a single unstructured field.
+// Tags: maxicode, secondary messages, concatenation, complex barcode, generation, aspnet, csharp
+
using System;
-using Aspose.BarCode.Generation;
+using System.IO;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.Drawing.Imaging;
+using Aspose.BarCode.Generation;
///
-/// Demonstrates generation of a MaxiCode barcode (Mode 2) with concatenated secondary messages.
+/// Demonstrates generating a MaxiCode barcode (Mode 2) with concatenated secondary messages using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Builds a MaxiCode codetext, generates the barcode, and saves it as a PNG file.
+ /// Entry point. Concatenates secondary messages, builds MaxiCode codetext, and saves the barcode as PNG.
///
static void Main()
{
- // ------------------------------------------------------------
- // Prepare secondary messages that will be combined into one string.
- // ------------------------------------------------------------
- string[] secondaryMessages = new[] { "First message", "Second message", "Third message" };
- string concatenatedMessage = string.Join(" ", secondaryMessages); // "First message Second message Third message"
+ // Sample secondary messages to be concatenated
+ string[] secondaryMessages = { "Item A", "Item B", "Item C" };
- // ------------------------------------------------------------
- // Create a MaxiCode codetext object (Mode 2) and populate required primary fields.
- // ------------------------------------------------------------
- var maxiCode = new MaxiCodeCodetextMode2
+ // Concatenate messages into a single unstructured string (space‑separated)
+ string combinedMessage = string.Join(" ", secondaryMessages);
+
+ // Create MaxiCode codetext for Mode 2 (postal info + data)
+ var maxiCodeCodetext = new MaxiCodeCodetextMode2
{
PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // Example country code
+ CountryCode = 056, // USA numeric country code
ServiceCategory = 999 // Example service category
};
- // ------------------------------------------------------------
- // Assign the concatenated secondary message to the unstructured field.
- // ------------------------------------------------------------
- var secondMessage = new MaxiCodeStandardSecondMessage
+ // Assign the concatenated message as a standard (unstructured) second message
+ var standardSecondMessage = new MaxiCodeStandardSecondMessage
{
- Message = concatenatedMessage
+ Message = combinedMessage
};
- maxiCode.SecondMessage = secondMessage;
-
- // ------------------------------------------------------------
- // Build the full codetext string that will be encoded in the barcode.
- // ------------------------------------------------------------
- string fullCodeText = maxiCode.GetConstructedCodetext();
+ maxiCodeCodetext.SecondMessage = standardSecondMessage;
- // ------------------------------------------------------------
- // Generate the MaxiCode barcode image and save it as a PNG file.
- // ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, fullCodeText))
+ // Generate the MaxiCode barcode and save it to a PNG file
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Save the generated barcode to disk.
- generator.Save("maxicode.png");
+ using (var memoryStream = new MemoryStream())
+ {
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
+ File.WriteAllBytes("maxicode.png", memoryStream.ToArray());
+ }
}
- // Inform the user that the barcode has been created.
Console.WriteLine("MaxiCode barcode generated and saved as 'maxicode.png'.");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/use-maxicodecodetextmode2-helper-to-build-complex-primary-data-and-generate-barcode-image.cs b/maxicode-barcode/use-maxicodecodetextmode2-helper-to-build-complex-primary-data-and-generate-barcode-image.cs
index f2498d2..3134150 100644
--- a/maxicode-barcode/use-maxicodecodetextmode2-helper-to-build-complex-primary-data-and-generate-barcode-image.cs
+++ b/maxicode-barcode/use-maxicodecodetextmode2-helper-to-build-complex-primary-data-and-generate-barcode-image.cs
@@ -1,79 +1,78 @@
+// Title: Generate MaxiCode (Mode 2) with Complex Primary Data
+// Description: Demonstrates building a MaxiCode Mode 2 codetext using the MaxiCodeCodetextMode2 helper, then generating and decoding the barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation and recognition category. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and BarCodeReader to create and read MaxiCode symbols, a common requirement for shipping and logistics applications where detailed routing information is encoded. Developers often need to construct complex codetext structures, render them to images, and verify correctness via decoding.
+// Prompt: Use the MaxiCodeCodetextMode2 helper to build complex primary data and generate the barcode image.
+// Tags: maxicode, mode2, complex barcode, generation, decoding, aspose.barcode, c#
+
using System;
using System.IO;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demo program that generates a MaxiCode barcode, saves it, and optionally reads it back.
+/// Demonstrates creating a MaxiCode (Mode 2) barcode with complex primary data,
+/// saving it as an image, and decoding it back using Aspose.BarCode.
///
class Program
{
///
- /// Entry point. Generates a MaxiCode barcode, saves to file, and reads it back.
+ /// Entry point of the example. Builds the codetext, generates the barcode,
+ /// saves it to a PNG file, and then reads the file to verify the encoded data.
///
static void Main()
{
- // Prepare the full path for the output PNG file.
- string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "maxicode.png");
-
- // Build MaxiCode primary data using MaxiCodeCodetextMode2.
- var maxiCodeData = new MaxiCodeCodetextMode2
- {
- PostalCode = "524032140", // 9‑digit US postal code for Mode 2.
- CountryCode = 56, // Example country code.
- ServiceCategory = 999 // Example service category.
- };
+ // Build MaxiCode codetext for Mode 2 with a standard second message
+ var maxiCodeCodetext = new MaxiCodeCodetextMode2();
+ maxiCodeCodetext.PostalCode = "524032140"; // 9‑digit US postal code
+ maxiCodeCodetext.CountryCode = 56; // Numeric country code
+ maxiCodeCodetext.ServiceCategory = 999; // Example service category
- // Create a standard second message and assign it to the primary data.
- var secondMessage = new MaxiCodeStandardSecondMessage
- {
- Message = "Sample MaxiCode message"
- };
- maxiCodeData.SecondMessage = secondMessage;
+ // Create and assign the optional standard second message
+ var secondMessage = new MaxiCodeStandardSecondMessage();
+ secondMessage.Message = "Test message";
+ maxiCodeCodetext.SecondMessage = secondMessage;
- // Generate the barcode image using ComplexBarcodeGenerator.
- using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
+ // Generate and save the MaxiCode image to a PNG file
+ string outputPath = "maxicode.png";
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Optional: set image resolution (dots per inch).
- generator.Parameters.Resolution = 300f;
-
- // Save the generated barcode as a PNG file.
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ generator.Save(outputPath);
}
- // Inform the user where the barcode image was saved.
- Console.WriteLine($"MaxiCode barcode saved to: {outputPath}");
-
- // Demonstrate reading the generated barcode (optional).
+ // Verify that the image was created and read it back for validation
if (File.Exists(outputPath))
{
- // Initialize a barcode reader for MaxiCode format.
+ // Initialize a reader for MaxiCode symbols
using (var reader = new BarCodeReader(outputPath, DecodeType.MaxiCode))
{
- // Iterate through all detected barcodes in the image.
+ // Iterate through all detected barcodes (should be one)
foreach (var result in reader.ReadBarCodes())
{
- // Decode the complex codetext back to MaxiCodeCodetextMode2.
+ // Decode the complex codetext from the raw CodeText
var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
result.Extended.MaxiCode.MaxiCodeMode,
result.CodeText);
- // If decoding succeeded and the result is of the expected type, display its fields.
- if (decoded is MaxiCodeCodetextMode2 decodedData)
+ // Cast to the specific Mode 2 type to access its properties
+ if (decoded is MaxiCodeCodetextMode2 decodedMode2)
{
- Console.WriteLine("Decoded PostalCode: " + decodedData.PostalCode);
- Console.WriteLine("Decoded CountryCode: " + decodedData.CountryCode);
- Console.WriteLine("Decoded ServiceCategory: " + decodedData.ServiceCategory);
+ Console.WriteLine($"PostalCode: {decodedMode2.PostalCode}");
+ Console.WriteLine($"CountryCode: {decodedMode2.CountryCode}");
+ Console.WriteLine($"ServiceCategory: {decodedMode2.ServiceCategory}");
- // If a standard second message is present, display its content.
- if (decodedData.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
+ // Output the optional second message if present
+ if (decodedMode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
{
- Console.WriteLine("Decoded Message: " + stdMsg.Message);
+ Console.WriteLine($"Second Message: {stdMsg.Message}");
}
}
}
}
}
+ else
+ {
+ Console.WriteLine("Failed to generate the MaxiCode image.");
+ }
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/validate-input-fields-for-maxicode-mode-3-using-provided-structured-codetext-classes-before-generation.cs b/maxicode-barcode/validate-input-fields-for-maxicode-mode-3-using-provided-structured-codetext-classes-before-generation.cs
index 202109f..b2357b5 100644
--- a/maxicode-barcode/validate-input-fields-for-maxicode-mode-3-using-provided-structured-codetext-classes-before-generation.cs
+++ b/maxicode-barcode/validate-input-fields-for-maxicode-mode-3-using-provided-structured-codetext-classes-before-generation.cs
@@ -1,99 +1,118 @@
+// Title: Validate MaxiCode Mode 3 Input Fields Using Structured Codetext Classes
+// Description: Demonstrates how to validate the required fields of a MaxiCode Mode 3 codetext object before generating the barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode3, and related second‑message classes to prepare and validate data before rendering. Developers working with shipping or logistics barcodes often need to ensure data conforms to MaxiCode specifications, making validation a common prerequisite.
+// Prompt: Validate input fields for MaxiCode Mode 3 using the provided structured codetext classes before generation.
+// Tags: maxicode, validation, image, complexbarcodegenerator, codetext, aspnet, csharp
+
using System;
-using System.IO;
using System.Text.RegularExpressions;
-using Aspose.BarCode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.Drawing.Imaging;
+using Aspose.BarCode.Generation;
+using Aspose.BarCode;
///
-/// Demonstrates generation of a MaxiCode Mode 3 barcode using Aspose.BarCode.
+/// Example program that validates MaxiCode Mode 3 data and generates a barcode image.
///
class Program
{
///
- /// Entry point of the application. Generates a MaxiCode Mode 3 barcode and saves it as a PNG file.
+ /// Entry point of the application. Builds a MaxiCode Mode 3 codetext, validates it,
+ /// and generates a PNG image using Aspose.BarCode.
///
static void Main()
{
- // Sample input values for MaxiCode Mode 3
- string postalCode = "B1050A"; // 6 alphanumeric characters
- int countryCode = 56; // 3‑digit numeric code
- int serviceCategory = 999; // 3‑digit numeric code
- string secondMessageText = "Test message";
-
- try
+ // ------------------------------------------------------------
+ // Prepare sample data for MaxiCode Mode 3
+ // ------------------------------------------------------------
+ var codetext = new MaxiCodeCodetextMode3
{
- // Validate the input fields before barcode generation
- ValidateMaxiCodeMode3(postalCode, countryCode, serviceCategory, secondMessageText);
-
- // Build the structured codetext object required by ComplexBarcodeGenerator
- var codetext = new MaxiCodeCodetextMode3
- {
- PostalCode = postalCode,
- CountryCode = countryCode,
- ServiceCategory = serviceCategory,
- SecondMessage = new MaxiCodeStandardSecondMessage { Message = secondMessageText }
- };
+ PostalCode = "B1050A", // 6 alphanumeric characters
+ CountryCode = 56, // 3‑digit numeric country code
+ ServiceCategory = 999 // 3‑digit service category
+ };
- // Determine a temporary file path for the output PNG image
- string outputPath = Path.Combine(Path.GetTempPath(), "maxicode_mode3.png");
-
- // Generate the barcode and save it directly to the file system
- using (var generator = new ComplexBarcodeGenerator(codetext))
- {
- // ComplexBarcodeGenerator supports the same Save method as BarcodeGenerator
- generator.Save(outputPath, BarCodeImageFormat.Png);
- }
+ // Optional standard second message (e.g., additional textual information)
+ var secondMessage = new MaxiCodeStandardSecondMessage
+ {
+ Message = "Sample message"
+ };
+ codetext.SecondMessage = secondMessage;
- Console.WriteLine($"MaxiCode Mode 3 barcode generated successfully: {outputPath}");
+ // ------------------------------------------------------------
+ // Validate the codetext before attempting barcode generation
+ // ------------------------------------------------------------
+ try
+ {
+ ValidateMaxiCodeMode3(codetext);
}
catch (ArgumentException ex)
{
- // Handle validation errors
- Console.WriteLine($"Input validation error: {ex.Message}");
+ Console.WriteLine($"Validation error: {ex.Message}");
+ return; // Abort if validation fails
}
- catch (Exception ex)
+
+ // ------------------------------------------------------------
+ // Generate the barcode image and save it to disk
+ // ------------------------------------------------------------
+ using (var generator = new ComplexBarcodeGenerator(codetext))
{
- // Handle any unexpected errors
- Console.WriteLine($"Unexpected error: {ex.Message}");
+ generator.GenerateBarCodeImage(); // Render the barcode
+ generator.Save("maxicode_mode3.png"); // Save as PNG
}
+
+ Console.WriteLine("MaxiCode Mode 3 barcode generated successfully.");
}
///
- /// Validates the input parameters for a MaxiCode Mode 3 barcode.
- /// Throws if any parameter is invalid.
+ /// Validates the fields of a MaxiCodeCodetextMode3 instance according to
+ /// MaxiCode Mode 3 specifications, including optional second‑message validation.
///
- /// Six‑character alphanumeric postal code.
- /// Three‑digit numeric country code (0‑999).
- /// Three‑digit numeric service category (0‑999).
- /// Secondary message text; must not be empty.
- static void ValidateMaxiCodeMode3(string postalCode, int countryCode, int serviceCategory, string secondMessage)
+ /// The codetext object to validate.
+ static void ValidateMaxiCodeMode3(MaxiCodeCodetextMode3 codetext)
{
- // PostalCode must be exactly 6 alphanumeric characters
- if (string.IsNullOrWhiteSpace(postalCode) ||
- postalCode.Length != 6 ||
- !Regex.IsMatch(postalCode, @"^[A-Za-z0-9]{6}$"))
+ if (codetext == null)
+ throw new ArgumentException("Codetext object cannot be null.");
+
+ // PostalCode: exactly 6 alphanumeric characters
+ if (string.IsNullOrEmpty(codetext.PostalCode) ||
+ codetext.PostalCode.Length != 6 ||
+ !Regex.IsMatch(codetext.PostalCode, @"^[A-Za-z0-9]{6}$"))
{
- throw new ArgumentException("PostalCode must be exactly 6 alphanumeric characters.");
+ throw new ArgumentException("PostalCode must be exactly 6 alphanumeric characters for MaxiCode Mode 3.");
}
- // CountryCode must be between 0 and 999 (inclusive)
- if (countryCode < 0 || countryCode > 999)
+ // CountryCode: numeric value between 0 and 999 (inclusive)
+ if (codetext.CountryCode < 0 || codetext.CountryCode > 999)
{
- throw new ArgumentException("CountryCode must be a 3‑digit number between 0 and 999.");
+ throw new ArgumentException("CountryCode must be a 3‑digit integer between 0 and 999.");
}
- // ServiceCategory must be between 0 and 999 (inclusive)
- if (serviceCategory < 0 || serviceCategory > 999)
+ // ServiceCategory: numeric value between 0 and 999 (inclusive)
+ if (codetext.ServiceCategory < 0 || codetext.ServiceCategory > 999)
{
- throw new ArgumentException("ServiceCategory must be a 3‑digit number between 0 and 999.");
+ throw new ArgumentException("ServiceCategory must be a 3‑digit integer between 0 and 999.");
}
- // SecondMessage must be provided and not consist solely of whitespace
- if (string.IsNullOrWhiteSpace(secondMessage))
+ // Validate second message if it is provided
+ if (codetext.SecondMessage != null)
{
- throw new ArgumentException("SecondMessage cannot be empty.");
+ if (codetext.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
+ {
+ // Standard second message must contain non‑empty text
+ if (string.IsNullOrWhiteSpace(stdMsg.Message))
+ throw new ArgumentException("Standard second message must contain non‑empty text.");
+ }
+ else if (codetext.SecondMessage is MaxiCodeStructuredSecondMessage structMsg)
+ {
+ // Structured second message must have at least one identifier
+ if (structMsg.Identifiers == null || structMsg.Identifiers.Count == 0)
+ throw new ArgumentException("Structured second message must contain at least one identifier.");
+ }
+ else
+ {
+ // Any other type is not supported in this example
+ throw new ArgumentException("Unsupported second message type.");
+ }
}
}
}
\ No newline at end of file