diff --git a/special-barcode-recognition-settings/adjust-net-threadpool-minimum-threads-to-2-and-maximum-threads-to-8-before-creating-barcodereader-instances.cs b/special-barcode-recognition-settings/adjust-net-threadpool-minimum-threads-to-2-and-maximum-threads-to-8-before-creating-barcodereader-instances.cs
index 91908ba..0cbc740 100644
--- a/special-barcode-recognition-settings/adjust-net-threadpool-minimum-threads-to-2-and-maximum-threads-to-8-before-creating-barcodereader-instances.cs
+++ b/special-barcode-recognition-settings/adjust-net-threadpool-minimum-threads-to-2-and-maximum-threads-to-8-before-creating-barcodereader-instances.cs
@@ -1,8 +1,8 @@
-// Title: Adjust .NET ThreadPool settings for barcode reading
-// Description: Demonstrates how to set ThreadPool minimum and maximum threads before generating and reading a barcode image using Aspose.BarCode.
-// Category-Description: This example belongs to the Aspose.BarCode .NET barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating a Code128 barcode and BarCodeReader for decoding it, while configuring ThreadPool limits to optimize multithreaded performance. Developers often need to adjust thread pool settings when processing many images concurrently in high‑throughput applications.
+// Title: Adjust .NET ThreadPool settings and read a generated Code128 barcode
+// Description: This example generates a Code128 barcode image, configures the .NET ThreadPool limits, then reads the barcode using Aspose.BarCode.
+// Category-Description: Demonstrates basic Aspose.BarCode operations including barcode generation (BarcodeGenerator) and recognition (BarCodeReader) with thread pool tuning. Useful for developers needing to control concurrency while processing barcodes in high‑throughput scenarios. Covers common use cases such as creating PNG images and decoding all supported symbologies.
// Prompt: Adjust .NET ThreadPool minimum threads to 2 and maximum threads to 8 before creating BarCodeReader instances.
-// Tags: barcode symbology, generation, recognition, code128, threadpool, aspnet, aspose.barcode
+// Tags: code128, barcode-generation, barcode-recognition, png, threadpool, aspose.barcode
using System;
using System.IO;
@@ -12,63 +12,53 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates adjusting .NET ThreadPool settings and using Aspose.BarCode to generate and read a Code128 barcode.
+/// Demonstrates generating a barcode, configuring ThreadPool limits, and reading the barcode using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Configures ThreadPool limits, creates a barcode image, reads it, and cleans up.
+ /// Entry point of the example. Generates a Code128 barcode, sets ThreadPool thread counts, reads the barcode, and cleans up.
///
static void Main()
{
- // --------------------------------------------------------------------
- // Adjust ThreadPool settings before any barcode operations are performed
- // --------------------------------------------------------------------
- ThreadPool.GetMinThreads(out int minWorker, out int minIOC);
- ThreadPool.SetMinThreads(2, minIOC); // Set minimum worker threads to 2
- ThreadPool.GetMaxThreads(out int maxWorker, out int maxIOC);
- ThreadPool.SetMaxThreads(8, maxIOC); // Set maximum worker threads to 8
+ // Define the temporary file path for the generated barcode image
+ string barcodePath = "sample_barcode.png";
- // -------------------------------------------------
- // Generate a sample barcode image using Code128 symbology
- // -------------------------------------------------
- string imagePath = "sample_barcode.png";
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Generate a simple Code128 barcode and save it as a PNG file
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789"))
{
- generator.Save(imagePath, BarCodeImageFormat.Png);
+ generator.Save(barcodePath, BarCodeImageFormat.Png);
}
- // -------------------------------------------------
- // Verify that the barcode image was successfully created
- // -------------------------------------------------
- if (!File.Exists(imagePath))
- {
- Console.WriteLine("Failed to create barcode image.");
- return;
- }
+ // Adjust ThreadPool settings: set minimum to 2 worker threads and maximum to 8 worker threads
+ int workerThreads, completionPortThreads;
+ ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
+ ThreadPool.SetMinThreads(2, completionPortThreads);
+ ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
+ ThreadPool.SetMaxThreads(8, completionPortThreads);
- // -------------------------------------------------
- // Read the barcode from the generated image using BarCodeReader
- // -------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
+ // Read the barcode using BarCodeReader with all supported decode types
+ using (BarCodeReader reader = new BarCodeReader(barcodePath, DecodeType.AllSupportedTypes))
{
- foreach (var result in reader.ReadBarCodes())
+ BarCodeResult[] results = reader.ReadBarCodes();
+ foreach (BarCodeResult result in results)
{
Console.WriteLine($"Detected Type: {result.CodeTypeName}");
Console.WriteLine($"Detected Text: {result.CodeText}");
}
}
- // -------------------------------------------------
- // Clean up the sample image file (optional)
- // -------------------------------------------------
- try
- {
- File.Delete(imagePath);
- }
- catch
+ // Clean up the temporary barcode image file
+ if (File.Exists(barcodePath))
{
- // Ignore any cleanup errors
+ try
+ {
+ File.Delete(barcodePath);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to delete temporary file: {ex.Message}");
+ }
}
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/configure-processorsettingsuseallcores-true-to-allocate-all-cpu-cores-automatically-for-barcode-recognition.cs b/special-barcode-recognition-settings/configure-processorsettingsuseallcores-true-to-allocate-all-cpu-cores-automatically-for-barcode-recognition.cs
index 488ebbe..964b147 100644
--- a/special-barcode-recognition-settings/configure-processorsettingsuseallcores-true-to-allocate-all-cpu-cores-automatically-for-barcode-recognition.cs
+++ b/special-barcode-recognition-settings/configure-processorsettingsuseallcores-true-to-allocate-all-cpu-cores-automatically-for-barcode-recognition.cs
@@ -1,52 +1,59 @@
-// Title: Barcode Recognition Using All CPU Cores
-// Description: Demonstrates how to enable multi‑core processing for barcode recognition with Aspose.BarCode and reads a generated Code128 barcode.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader and its ProcessorSettings to leverage all available CPU cores for faster decoding. Typical use cases include high‑throughput scanning applications where performance is critical. Developers often need to configure ProcessorSettings, select DecodeType, and retrieve barcode metadata such as type, text, and region.
+// Title: Using Aspose.BarCode to generate and recognize a Code128 barcode with multi‑core processing
+// Description: Demonstrates creating a Code128 barcode image, saving it, and then recognizing it while configuring the processor to utilize all CPU cores.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It shows how to use BarcodeGenerator to create barcodes and BarCodeReader with ProcessorSettings to perform high‑performance recognition. Developers often need to generate barcodes for labeling and then read them in batch scenarios, where enabling multi‑core processing improves throughput.
// Prompt: Configure ProcessorSettings.UseAllCores true to allocate all CPU cores automatically for barcode recognition.
-// Tags: barcode, recognition, multithreading, useallcores, code128, aspnet, aspnetcore, aspose.barcode, image processing
+// Tags: code128, barcode-generation, barcode-recognition, multithreading, useallcores, aspose-barcodes, png
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Demonstrates configuring Aspose.BarCode to use all CPU cores for barcode recognition and reading a Code128 barcode.
+/// Example program that generates a Code128 barcode, saves it as PNG,
+/// configures the recognition processor to use all CPU cores, reads the barcode,
+/// and cleans up the temporary image file.
///
class Program
{
///
- /// Entry point that generates a sample barcode if missing, enables multi‑core processing, and reads the barcode information.
+ /// Entry point of the example. Executes barcode generation, multi‑core recognition,
+ /// and cleanup operations.
///
static void Main()
{
- // Enable utilization of all CPU cores for barcode recognition
- BarCodeReader.ProcessorSettings.UseAllCores = true;
-
- // Path to the barcode image file
- string imagePath = "barcode.png";
+ // Define the temporary file path for the generated barcode image.
+ string imagePath = "sample.png";
- // Generate a sample Code128 barcode image if it does not already exist
- if (!File.Exists(imagePath))
+ // Generate a simple Code128 barcode and save it as a PNG file.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345"))
{
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789"))
- {
- generator.Save(imagePath, BarCodeImageFormat.Png);
- }
+ // Set barcode foreground and background colors (optional).
+ generator.Parameters.Barcode.BarColor = Color.Black;
+ generator.Parameters.BackColor = Color.White;
+
+ // Save the barcode image to the specified path.
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // Initialize the reader to decode all supported barcode types from the image
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // Enable multi‑core processing for barcode recognition to improve performance.
+ BarCodeReader.ProcessorSettings.UseAllCores = true;
+
+ // Read and display barcode information from the saved image.
+ using (var reader = new BarCodeReader(imagePath))
{
- // Iterate through all detected barcodes and output their details
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Barcode Text: {result.CodeText}");
-
- var bounds = result.Region.Rectangle;
- Console.WriteLine($"Region - X:{bounds.X}, Y:{bounds.Y}, Width:{bounds.Width}, Height:{bounds.Height}");
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Detected Text: {result.CodeText}");
}
}
+
+ // Delete the temporary image file to clean up resources.
+ if (File.Exists(imagePath))
+ {
+ File.Delete(imagePath);
+ }
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/create-background-worker-that-reads-barcodes-from-video-stream-using-processorsettings-for-optimal-core-usage.cs b/special-barcode-recognition-settings/create-background-worker-that-reads-barcodes-from-video-stream-using-processorsettings-for-optimal-core-usage.cs
index 7501249..4e5e9a8 100644
--- a/special-barcode-recognition-settings/create-background-worker-that-reads-barcodes-from-video-stream-using-processorsettings-for-optimal-core-usage.cs
+++ b/special-barcode-recognition-settings/create-background-worker-that-reads-barcodes-from-video-stream-using-processorsettings-for-optimal-core-usage.cs
@@ -1,88 +1,113 @@
-// Title: Background Worker Barcode Reader from Video Stream
-// Description: Demonstrates reading barcodes from simulated video frames using a BackgroundWorker and ProcessorSettings to control core usage.
-// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to generate barcodes, process them in a background thread, and fine‑tune multi‑core utilization via ProcessorSettings. Developers often need to handle high‑throughput image streams (e.g., video) and require optimal CPU usage while recognizing multiple symbologies using BarCodeReader, BarcodeGenerator, and QualitySettings.
+// Title: Background worker barcode reading with processor settings
+// Description: Demonstrates generating sample barcode images, configuring Aspose.BarCode processor settings for multi‑core usage, and reading the barcodes asynchronously using a BackgroundWorker.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases key API classes such as BarcodeGenerator, BarCodeReader, and ProcessorSettings, illustrating typical scenarios where developers need to generate barcodes, optimize recognition performance across CPU cores, and process images in a background thread for responsive applications.
// Prompt: Create a background worker that reads barcodes from a video stream using ProcessorSettings for optimal core usage.
-// Tags: code128, read, console, barcodegenerator, barcodereader, processorsettings, qualitysettings
+// Tags: code128, qr, generation, reading, png, barcodegenerator, barcodereader, backgroundworker
using System;
-using System.Collections.Generic;
-using System.ComponentModel;
using System.IO;
+using System.ComponentModel;
using System.Threading;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Example program that generates barcode images, simulates video frames,
-/// and reads them in a background worker using Aspose.BarCode APIs.
+/// Demonstrates generating sample barcodes, configuring multi‑core processor settings,
+/// and reading the barcodes asynchronously using a BackgroundWorker.
///
class Program
{
///
- /// Entry point. Generates sample frames, configures processor settings,
- /// and processes frames asynchronously.
+ /// Entry point. Sets processor settings, creates sample barcodes, runs a background
+ /// worker to read them, and cleans up temporary files.
///
- static void Main()
+ static void Main(string[] args)
{
- // Generate a few barcode images to simulate video frames
- var frames = new List();
- for (int i = 0; i < 3; i++)
+ // Enable use of all CPU cores for barcode processing
+ BarCodeReader.ProcessorSettings.UseAllCores = true;
+ // Allow additional threads proportional to processor count for better throughput
+ BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = Environment.ProcessorCount * 2;
+
+ // Create a temporary folder to store generated barcode images
+ string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeSample");
+ Directory.CreateDirectory(tempFolder);
+ GenerateSampleBarcodes(tempFolder);
+
+ // Set up a BackgroundWorker to process the images without blocking the main thread
+ using (var worker = new BackgroundWorker())
{
- // Create a barcode generator for Code128 with unique text
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i + 1}"))
+ var completedEvent = new ManualResetEventSlim(false);
+
+ // Define the work to be performed in the background thread
+ worker.DoWork += (sender, e) => ProcessImages(tempFolder);
+ // Signal completion when the background work finishes
+ worker.RunWorkerCompleted += (sender, e) => completedEvent.Set();
+
+ // Start the background operation
+ worker.RunWorkerAsync();
+
+ // Wait for the background worker to finish, but limit wait time to avoid hanging
+ if (!completedEvent.Wait(TimeSpan.FromSeconds(30)))
{
- // Set a simple visual dimension
- generator.Parameters.Barcode.XDimension.Point = 2f;
- // Render the barcode to a bitmap
- using (var bitmap = generator.GenerateBarCodeImage())
- {
- // Save bitmap to memory stream as PNG
- using (var ms = new MemoryStream())
- {
- bitmap.Save(ms, ImageFormat.Png);
- frames.Add(ms.ToArray());
- }
- }
+ Console.WriteLine("Processing timed out.");
}
}
- // Synchronization primitive to wait for background work completion
- var doneEvent = new ManualResetEventSlim(false);
+ // Attempt to delete the temporary folder and its contents; ignore any errors in CI environments
+ try
+ {
+ Directory.Delete(tempFolder, true);
+ }
+ catch
+ {
+ // Suppress cleanup exceptions
+ }
+ }
- // BackgroundWorker that processes the simulated video frames
- var worker = new BackgroundWorker();
- worker.DoWork += (sender, args) =>
+ // Generates a few barcode images for demonstration purposes
+ private static void GenerateSampleBarcodes(string folder)
+ {
+ const int sampleCount = 5;
+ for (int i = 0; i < sampleCount; i++)
{
- // Configure processor settings for optimal core usage
- BarCodeReader.ProcessorSettings.UseAllCores = false;
- BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Math.Max(1, Environment.ProcessorCount / 2);
+ string text = $"Sample{i}";
+ string filePath = Path.Combine(folder, $"barcode{i}.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text))
+ {
+ // Simple generation; default settings are sufficient
+ generator.Save(filePath);
+ }
+ }
+ }
- // Iterate over each simulated frame
- foreach (var frameData in frames)
+ // Reads barcodes from all PNG files in the specified folder
+ private static void ProcessImages(string folder)
+ {
+ string[] files = Directory.GetFiles(folder, "*.png");
+ // Iterate over each image file
+ for (int i = 0; i < files.Length; i++)
+ {
+ string file = files[i];
+ try
{
- // Create a memory stream from the frame bytes
- using (var stream = new MemoryStream(frameData))
- // Initialize the barcode reader for all supported symbologies
- using (var reader = new BarCodeReader(stream, DecodeType.AllSupportedTypes))
+ // Initialize the reader for Code128 and QR symbologies
+ using (var reader = new BarCodeReader(file, DecodeType.Code128, DecodeType.QR))
{
// Apply a high‑performance quality preset
reader.QualitySettings = QualitySettings.HighPerformance;
-
- // Read and output all detected barcodes
+ // Read and output each detected barcode
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected: {result.CodeTypeName} - {result.CodeText}");
+ Console.WriteLine($"File: {Path.GetFileName(file)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
}
}
}
- };
- // Signal completion when background work finishes
- worker.RunWorkerCompleted += (s, e) => doneEvent.Set();
-
- // Start processing and wait until it finishes
- worker.RunWorkerAsync();
- doneEvent.Wait();
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Error processing '{Path.GetFileName(file)}': {ex.Message}");
+ }
+ }
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/create-batch-process-that-reads-multiple-images-with-stripfnc-false-to-keep-fnc-symbols.cs b/special-barcode-recognition-settings/create-batch-process-that-reads-multiple-images-with-stripfnc-false-to-keep-fnc-symbols.cs
index a8f07bd..3e87afe 100644
--- a/special-barcode-recognition-settings/create-batch-process-that-reads-multiple-images-with-stripfnc-false-to-keep-fnc-symbols.cs
+++ b/special-barcode-recognition-settings/create-batch-process-that-reads-multiple-images-with-stripfnc-false-to-keep-fnc-symbols.cs
@@ -1,92 +1,94 @@
-// Title: Batch barcode reading with StripFNC disabled
-// Description: Demonstrates reading multiple barcode images while preserving FNC symbols by setting StripFNC to false.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to configure BarCodeReader settings for batch processing of images. It highlights the use of BarCodeReader, BarcodeSettings, and DecodeType to read various symbologies, a common task for developers needing to extract raw barcode data without stripping control characters.
+// Title: Batch barcode generation and recognition with StripFNC disabled
+// Description: This example creates multiple GS1‑Code128 barcode images that contain FNC symbols, then reads them back while preserving those symbols.
+// Category-Description: Demonstrates Aspose.BarCode generation and recognition in a batch workflow. It uses BarcodeGenerator to encode GS1 data, BarCodeReader with DecodeType.Code128 to decode, and BarcodeSettings.StripFNC to control FNC handling. Typical scenarios include processing large sets of GS1 barcodes where FNC characters must remain intact, such as inventory or logistics applications. Developers often need to generate barcodes, store them as images, and later read them without losing embedded control characters.
// Prompt: Create a batch process that reads multiple images with StripFNC false to keep FNC symbols.
-// Tags: barcode, batch processing, stripfnc, gs1code128, decode, aspnet, aspnetcore, aspose.barcode
+// Tags: barcode, gs1code128, stripfnc, batch-processing, generation, recognition, csharp, aspose.barcode
using System;
using System.IO;
-using System.Collections.Generic;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Demonstrates batch processing of barcode images while keeping FNC symbols (StripFNC = false).
+/// Demonstrates batch generation of GS1‑Code128 barcodes containing FNC characters
+/// and subsequent recognition while preserving those characters (StripFNC = false).
///
class Program
{
///
- /// Entry point. Generates sample images if needed and reads all PNG files in the InputImages folder,
- /// printing detected barcode information without stripping FNC characters.
+ /// Entry point. Generates sample barcode images, then reads each image back
+ /// with FNC symbols retained.
///
static void Main()
{
- // Define the folder that will contain input images.
- string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "InputImages");
-
- // Ensure the input folder exists.
- if (!Directory.Exists(inputFolder))
+ // --------------------------------------------------------------------
+ // Prepare output folder for generated barcode images
+ // --------------------------------------------------------------------
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(folderPath))
{
- Directory.CreateDirectory(inputFolder);
+ Directory.CreateDirectory(folderPath);
}
- // If the folder is empty, generate a few sample GS1‑Code128 barcodes containing FNC characters.
- string[] existingFiles = Directory.GetFiles(inputFolder, "*.png");
- if (existingFiles.Length == 0)
+ // --------------------------------------------------------------------
+ // Sample GS1 data strings that include FNC (Function) characters
+ // --------------------------------------------------------------------
+ string[] sampleTexts = new[]
{
- List sampleTexts = new List
- {
- "(01)12345678901231", // GTIN
- "(01)98765432109876(10)ABCD", // GTIN with lot number
- "(01)55555555555555(21)XYZ" // GTIN with serial number
- };
+ "(02)04006664241007(37)1(400)7019590754",
+ "(01)12345678901231(10)ABC123",
+ "(01)98765432109876(21)XYZ789"
+ };
- int index = 1;
- foreach (string text in sampleTexts)
+ // --------------------------------------------------------------------
+ // Generate a PNG barcode image for each sample text using GS1Code128
+ // --------------------------------------------------------------------
+ for (int i = 0; i < sampleTexts.Length; i++)
+ {
+ string filePath = Path.Combine(folderPath, $"barcode_{i + 1}.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, sampleTexts[i]))
{
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.GS1Code128, text))
- {
- string filePath = Path.Combine(inputFolder, $"Sample{index}.png");
- generator.Save(filePath, BarCodeImageFormat.Png);
- }
- index++;
+ generator.Save(filePath);
}
}
- // Retrieve all PNG images from the input folder.
- string[] imageFiles = Directory.GetFiles(inputFolder, "*.png");
+ // --------------------------------------------------------------------
+ // Locate all generated PNG files for batch processing
+ // --------------------------------------------------------------------
+ string[] imageFiles = Directory.GetFiles(folderPath, "*.png");
+ if (imageFiles.Length == 0)
+ {
+ Console.WriteLine("No barcode images found to process.");
+ return;
+ }
- // Process each image file.
- foreach (string imagePath in imageFiles)
+ // --------------------------------------------------------------------
+ // Read each image, ensuring FNC characters are NOT stripped (StripFNC = false)
+ // --------------------------------------------------------------------
+ foreach (string imageFile in imageFiles)
{
- if (!File.Exists(imagePath))
+ if (!File.Exists(imageFile))
{
- Console.WriteLine($"File not found: {imagePath}");
+ Console.WriteLine($"File not found: {imageFile}");
continue;
}
- // Initialize the barcode reader for all supported symbologies.
- using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ using (var reader = new BarCodeReader(imageFile, DecodeType.Code128))
{
- // Disable stripping of FNC characters to keep them in the result.
+ // Disable automatic removal of FNC symbols
reader.BarcodeSettings.StripFNC = false;
- // Read all barcodes present in the image.
BarCodeResult[] results = reader.ReadBarCodes();
-
if (results.Length == 0)
{
- Console.WriteLine($"No barcode detected in {Path.GetFileName(imagePath)}");
+ Console.WriteLine($"No barcodes detected in {Path.GetFileName(imageFile)}.");
+ continue;
}
- else
+
+ Console.WriteLine($"Barcodes in {Path.GetFileName(imageFile)}:");
+ foreach (BarCodeResult result in results)
{
- // Output details for each detected barcode.
- foreach (BarCodeResult result in results)
- {
- Console.WriteLine($"File: {Path.GetFileName(imagePath)} | Type: {result.CodeTypeName} | CodeText: {result.CodeText}");
- }
+ Console.WriteLine($" Type: {result.CodeTypeName}, CodeText: {result.CodeText}");
}
}
}
diff --git a/special-barcode-recognition-settings/create-batch-process-that-reads-multiple-images-with-stripfnc-true-to-strip-fnc-symbols.cs b/special-barcode-recognition-settings/create-batch-process-that-reads-multiple-images-with-stripfnc-true-to-strip-fnc-symbols.cs
index ae49ab7..fa2b76a 100644
--- a/special-barcode-recognition-settings/create-batch-process-that-reads-multiple-images-with-stripfnc-true-to-strip-fnc-symbols.cs
+++ b/special-barcode-recognition-settings/create-batch-process-that-reads-multiple-images-with-stripfnc-true-to-strip-fnc-symbols.cs
@@ -1,90 +1,80 @@
-// Title: Batch barcode image processing with StripFNC enabled
-// Description: Demonstrates how to read multiple barcode images in a folder while stripping FNC symbols from the decoded text.
-// Category-Description: This example belongs to the Aspose.BarCode recognition category, showcasing the use of BarCodeReader to decode various symbologies. It highlights the StripFNC setting, which removes Function Code (FNC) characters from the result—useful when clean data is required. Developers working with bulk barcode scanning, image preprocessing, or data sanitization will find this pattern common.
+// Title: Batch barcode recognition with FNC stripping
+// Description: Demonstrates how to generate multiple GS1-128 barcode images and then recognize them in a batch while stripping FNC symbols.
+// Category-Description: This example belongs to the Aspose.BarCode batch processing and barcode recognition category. It showcases the use of BarcodeGenerator for image creation, BarCodeReader for decoding, and the StripFNC setting to remove function characters from GS1 barcodes. Developers often need to process large sets of barcode images and require clean data without control characters.
// Prompt: Create a batch process that reads multiple images with StripFNC true to strip FNC symbols.
-// Tags: barcode symbology, strip fnc, text output, barcodereader, barcoderesult
+// Tags: gs1code128, stripfnc, batch-processing, barcode-recognition, aspose.barcode
using System;
using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Provides a simple batch processor that scans a folder of images,
-/// decodes any barcodes found, and strips Function Code (FNC) symbols
-/// from the resulting text using Aspose.BarCode.
+/// Demonstrates batch generation and recognition of GS1-128 barcodes with FNC characters stripped.
///
class Program
{
///
- /// Entry point of the application. Iterates over image files in the
- /// specified folder, decodes barcodes with StripFNC enabled, and
- /// writes the results to the console.
+ /// Entry point. Generates sample barcode images, then reads each image with StripFNC enabled.
///
static void Main()
{
- // Folder containing barcode images
- string imagesFolder = "Images";
-
- // Verify that the folder exists before proceeding
- if (!Directory.Exists(imagesFolder))
+ // Define folder for sample barcode images
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(folderPath))
{
- Console.WriteLine($"Folder not found: {imagesFolder}");
- return;
+ Directory.CreateDirectory(folderPath);
}
- // Retrieve all files in the folder (any extension) – filtering will be applied later
- string[] imageFiles = Directory.GetFiles(imagesFolder, "*.*", SearchOption.TopDirectoryOnly);
- int processed = 0;
- const int maxFiles = 10; // Limit processing to a safe sample size
+ // Sample code text containing FNC characters (GS1 format)
+ string sampleCodeText = "(02)04006664241007(37)1(400)7019590754";
- // Process each file until the maximum count is reached
- foreach (string filePath in imageFiles)
+ // Generate a few barcode images
+ for (int i = 1; i <= 3; i++)
{
- if (processed >= maxFiles) break;
-
- // Ensure the file still exists (it could have been removed externally)
- if (!File.Exists(filePath))
+ string imagePath = Path.Combine(folderPath, $"barcode{i}.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, sampleCodeText))
{
- Console.WriteLine($"File not found: {filePath}");
- continue;
+ generator.Save(imagePath);
}
+ }
+
+ // Retrieve all generated PNG files
+ string[] imageFiles = Directory.GetFiles(folderPath, "*.png");
+ if (imageFiles.Length == 0)
+ {
+ Console.WriteLine("No barcode images found to process.");
+ return;
+ }
- // Accept only common image formats
- string extension = Path.GetExtension(filePath).ToLowerInvariant();
- if (extension != ".png" && extension != ".jpg" && extension != ".jpeg" && extension != ".bmp")
+ // Process each image, stripping FNC characters during recognition
+ foreach (string file in imageFiles)
+ {
+ if (!File.Exists(file))
{
- Console.WriteLine($"Unsupported file type: {filePath}");
+ Console.WriteLine($"File not found: {file}");
continue;
}
- // Initialize the barcode reader for the current image
- using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
+ using (var reader = new BarCodeReader(file, DecodeType.Code128))
{
- // Enable stripping of FNC symbols from decoded text
+ // Enable stripping of FNC characters
reader.BarcodeSettings.StripFNC = true;
- // Perform the recognition
BarCodeResult[] results = reader.ReadBarCodes();
-
- // Output the results
if (results.Length == 0)
{
- Console.WriteLine($"No barcodes detected in: {Path.GetFileName(filePath)}");
+ Console.WriteLine($"No barcodes detected in {Path.GetFileName(file)}.");
+ continue;
}
- else
+
+ // Output each recognized barcode with FNC stripped
+ foreach (BarCodeResult result in results)
{
- Console.WriteLine($"Barcodes in {Path.GetFileName(filePath)} (FNC stripped):");
- foreach (BarCodeResult result in results)
- {
- Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}");
- }
+ Console.WriteLine($"File: {Path.GetFileName(file)} | Type: {result.CodeTypeName} | CodeText (FNC stripped): {result.CodeText}");
}
}
-
- processed++;
}
-
- Console.WriteLine("Batch processing completed.");
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/create-multithreaded-barcode-scanner-that-processes-image-files-in-parallel-using-default-processorsettings.cs b/special-barcode-recognition-settings/create-multithreaded-barcode-scanner-that-processes-image-files-in-parallel-using-default-processorsettings.cs
index c7234f6..545d984 100644
--- a/special-barcode-recognition-settings/create-multithreaded-barcode-scanner-that-processes-image-files-in-parallel-using-default-processorsettings.cs
+++ b/special-barcode-recognition-settings/create-multithreaded-barcode-scanner-that-processes-image-files-in-parallel-using-default-processorsettings.cs
@@ -1,64 +1,81 @@
-// Title: Multithreaded Barcode Scanning with Aspose.BarCode
-// Description: Demonstrates generating sample Code128 barcodes and scanning them concurrently using Aspose.BarCode's default ProcessorSettings.
-// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the BarcodeGenerator for creating barcodes and BarCodeReader for decoding them, combined with .NET's Parallel.ForEach to process multiple images in parallel. Developers often need fast, scalable barcode processing pipelines for bulk image analysis, inventory automation, or document digitization.
+// Title: Multithreaded barcode scanning using Aspose.BarCode default settings
+// Description: Demonstrates generating sample Code128 barcodes, saving them as PNG files, and scanning them concurrently with Parallel.ForEach using the default ProcessorSettings.
+// Category-Description: This example belongs to the Aspose.BarCode image processing and recognition category. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader with default ProcessorSettings for decoding. Typical use cases include batch processing of scanned documents, automated inventory systems, and high‑throughput barcode validation where developers need to read multiple images in parallel.
// Prompt: Create a multithreaded barcode scanner that processes image files in parallel using default ProcessorSettings.
-// Tags: code128, scanning, console, barcodegenerator, barcodereader, parallel, aspose.barcode
+// Tags: barcode, multithreading, parallel, code128, png, generation, recognition, aspnet, aspose.barcode, processorsettings
using System;
using System.IO;
-using System.Collections.Generic;
using System.Threading.Tasks;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates parallel barcode generation and recognition using Aspose.BarCode.
+/// Demonstrates generating barcode images and scanning them in parallel using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Generates sample barcode images and scans them concurrently.
+ /// Entry point of the example. Generates sample barcodes, saves them as PNG files,
+ /// and processes the images concurrently to read barcode data.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Define the directory that will hold the sample barcode images.
- string imagesDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
- Directory.CreateDirectory(imagesDir);
+ // --------------------------------------------------------------------
+ // Prepare a folder for sample barcode images
+ // --------------------------------------------------------------------
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ Directory.CreateDirectory(folderPath);
- // Build a list of file paths for the sample images.
- List imageFiles = new List();
- for (int i = 1; i <= 5; i++)
- {
- string filePath = Path.Combine(imagesDir, $"barcode{i}.png");
- imageFiles.Add(filePath);
+ // --------------------------------------------------------------------
+ // Define sample texts to encode as Code128 barcodes
+ // --------------------------------------------------------------------
+ string[] sampleTexts = { "ABC123", "XYZ789", "123456", "HELLO", "WORLD" };
- // Create a barcode image if it does not already exist.
- if (!File.Exists(filePath))
+ // --------------------------------------------------------------------
+ // Generate barcode images (PNG) using default generator settings
+ // --------------------------------------------------------------------
+ for (int i = 0; i < sampleTexts.Length; i++)
+ {
+ string filePath = Path.Combine(folderPath, $"barcode_{i}.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, sampleTexts[i]))
{
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}"))
- {
- generator.Save(filePath, BarCodeImageFormat.Png);
- }
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
}
- // Scan all images in parallel using the default ProcessorSettings.
+ // --------------------------------------------------------------------
+ // Retrieve all PNG files in the folder for processing
+ // --------------------------------------------------------------------
+ string[] imageFiles = Directory.GetFiles(folderPath, "*.png");
+
+ // --------------------------------------------------------------------
+ // Process images in parallel using default ProcessorSettings
+ // --------------------------------------------------------------------
Parallel.ForEach(imageFiles, file =>
{
- // Verify that the file exists before attempting to read it.
+ // Verify the file still exists (it may have been removed concurrently)
if (!File.Exists(file))
{
Console.WriteLine($"File not found: {file}");
return;
}
- // Initialize the reader for all supported barcode types.
- using (var reader = new BarCodeReader(file, DecodeType.AllSupportedTypes))
+ // Create a reader instance for each file
+ using (var reader = new BarCodeReader())
{
- // Iterate through all detected barcodes in the image.
+ // Use all supported decode types (default ProcessorSettings are applied automatically)
+ reader.BarCodeReadType = DecodeType.AllSupportedTypes;
+
+ // Load the image for recognition
+ reader.SetBarCodeImage(file);
+
+ // Read and output all detected barcodes
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"{Path.GetFileName(file)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
+ Console.WriteLine($"File: {Path.GetFileName(file)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
}
}
});
diff --git a/special-barcode-recognition-settings/create-sample-that-reads-batch-of-png-files-applying-australiapostsettingscustomerinformationinterpretingtypectable.cs b/special-barcode-recognition-settings/create-sample-that-reads-batch-of-png-files-applying-australiapostsettingscustomerinformationinterpretingtypectable.cs
index 570f147..5606f87 100644
--- a/special-barcode-recognition-settings/create-sample-that-reads-batch-of-png-files-applying-australiapostsettingscustomerinformationinterpretingtypectable.cs
+++ b/special-barcode-recognition-settings/create-sample-that-reads-batch-of-png-files-applying-australiapostsettingscustomerinformationinterpretingtypectable.cs
@@ -1,8 +1,8 @@
-// Title: Read batch of PNG barcodes with AustraliaPost CTable interpretation
-// Description: Demonstrates generating and reading multiple PNG images using AustraliaPostSettings.CustomerInformationInterpretingType.CTable.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on Australia Post symbology. It shows how to configure the AustralianPostEncodingTable for generation and the CustomerInformationInterpretingType for recognition using BarcodeGenerator, BarCodeReader, and related settings. Developers often need to process batches of barcodes with specific encoding tables, making this pattern useful for bulk operations.
+// Title: Read batch of PNG barcodes with Australia Post CTable interpretation
+// Description: Demonstrates generating Australia Post barcodes, saving them as PNG files, and reading them back using CustomerInformationInterpretingType.CTable.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the BarcodeGenerator for creating barcodes and BarCodeReader for decoding them, focusing on the AustraliaPost symbology. Developers often need to batch‑process image files, apply specific encoding tables (CTable), and extract barcode data for logistics or mailing applications. The code illustrates typical use cases such as bulk image creation, file system handling, and customized decoding settings.
// Prompt: Create a sample that reads a batch of PNG files applying AustraliaPostSettings.CustomerInformationInterpretingType.CTable.
-// Tags: barcode symbology, australia post, ctable, batch processing, png, generation, recognition, aspose.barcode
+// Tags: barcode, australia post, ctable, generation, recognition, png, batch, aspose.barcode
using System;
using System.IO;
@@ -11,74 +11,73 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Sample program that generates and reads a batch of PNG barcodes using Australia Post CTable interpretation.
+/// Sample program that generates Australia Post barcodes, saves them as PNG files,
+/// and reads them back using CTable customer information interpreting type.
///
class Program
{
///
- /// Entry point. Generates sample Australia Post barcodes, saves them as PNG, then reads them applying CTable interpretation.
+ /// Entry point. Generates sample barcodes, saves them, and decodes them.
///
static void Main()
{
- // Prepare a temporary folder for sample barcode images
- string folder = Path.Combine(Path.GetTempPath(), "AustraliaPostBarcodes");
- Directory.CreateDirectory(folder);
+ // Define folder for sample barcode images
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(folderPath))
+ {
+ Directory.CreateDirectory(folderPath);
+ }
- // Sample Australia Post code texts (must satisfy CTable rules)
- string[] sampleCodes = new string[]
+ // Sample Australia Post codetexts (FCC=59, DPID=8 digits, optional CTable info)
+ string[] sampleCodes = new[]
{
- "5912345678AB",
- "5912345678CD",
- "5912345678EF"
+ "5912345678AB", // 2 CTable chars
+ "6212345678ABCDE",// 5 CTable chars (max)
+ "5912345678" // No customer info
};
- // Generate PNG files for the sample codes
- foreach (string code in sampleCodes)
+ // -------------------------------------------------
+ // Generate barcode images and apply CTable interpreting type
+ // -------------------------------------------------
+ for (int i = 0; i < sampleCodes.Length; i++)
{
- string filePath = Path.Combine(folder, $"{code}.png");
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, code))
+ string codeText = sampleCodes[i];
+ string filePath = Path.Combine(folderPath, $"barcode{i + 1}.png");
+
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
{
- // Apply CTable interpreting type for generation
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable;
- generator.Save(filePath, BarCodeImageFormat.Png);
+ // Apply CTable interpreting type for encoding
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
+ generator.Save(filePath); // format inferred from extension
}
}
- // Read all PNG files in the folder (limit to 5 files for safety)
- string[] pngFiles = Directory.GetFiles(folder, "*.png");
- int maxFiles = Math.Min(pngFiles.Length, 5);
- Console.WriteLine($"Reading up to {maxFiles} barcode images from '{folder}':");
-
- for (int i = 0; i < maxFiles; i++)
+ // -------------------------------------------------
+ // Read and decode the generated PNG files using CTable interpreting type
+ // -------------------------------------------------
+ string[] pngFiles = Directory.GetFiles(folderPath, "barcode*.png");
+ foreach (string pngFile in pngFiles)
{
- string file = pngFiles[i];
- if (!File.Exists(file))
- {
- Console.WriteLine($"File not found: {file}");
- continue;
- }
-
- using (var reader = new BarCodeReader(file, DecodeType.AustraliaPost))
+ try
{
- // Apply CTable interpreting type for recognition
- reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
-
- // Optional: set a quality preset
- reader.QualitySettings = QualitySettings.NormalQuality;
-
- // Iterate through all detected barcodes in the image
- foreach (var result in reader.ReadBarCodes())
+ using (BarCodeReader reader = new BarCodeReader(pngFile, DecodeType.AustraliaPost))
{
- Console.WriteLine($"File: {Path.GetFileName(file)}");
- Console.WriteLine($" Detected Type: {result.CodeTypeName}");
- Console.WriteLine($" Code Text: {result.CodeText}");
- var bounds = result.Region.Rectangle;
- Console.WriteLine($" Region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}");
+ // Set decoding to use CTable interpreting type
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
+
+ foreach (BarCodeResult result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"File: {Path.GetFileName(pngFile)}");
+ Console.WriteLine($" BarCode Type: {result.CodeType}");
+ Console.WriteLine($" BarCode CodeText: {result.CodeText}");
+ }
}
}
+ catch (ArgumentException)
+ {
+ // Skip files that cannot be loaded as images
+ continue;
+ }
}
-
- // Cleanup: optionally delete the temporary files
- // foreach (var file in pngFiles) File.Delete(file);
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/create-sample-that-reads-batch-of-tiff-images-applying-australiapostsettingscustomerinformationinterpretingtypentable.cs b/special-barcode-recognition-settings/create-sample-that-reads-batch-of-tiff-images-applying-australiapostsettingscustomerinformationinterpretingtypentable.cs
index 66fa8f5..c391279 100644
--- a/special-barcode-recognition-settings/create-sample-that-reads-batch-of-tiff-images-applying-australiapostsettingscustomerinformationinterpretingtypentable.cs
+++ b/special-barcode-recognition-settings/create-sample-that-reads-batch-of-tiff-images-applying-australiapostsettingscustomerinformationinterpretingtypentable.cs
@@ -1,75 +1,103 @@
// Title: Read batch of TIFF images with Australia Post NTable interpretation
-// Description: Demonstrates how to load multiple TIFF files and decode Australia Post barcodes using the NTable customer information interpreting type.
-// Category-Description: This example belongs to the Aspose.BarCode barcode reading category, focusing on image batch processing and specific symbology settings. It showcases the BarCodeReader, DecodeType, and AustraliaPostSettings classes, which developers commonly use to extract barcode data from various image formats, apply custom decoding options, and handle batch operations efficiently.
+// Description: Demonstrates how to generate Australia Post barcodes saved as TIFF files and then read them using the NTable customer information interpreting type.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeReader for decoding them, and the AustraliaPostSettings.CustomerInformationInterpretingType property to control how customer information is interpreted. Typical use cases include batch processing of shipping labels or postal barcodes where specific interpreting tables (e.g., NTable) are required. Developers often need to generate barcode images in various formats and then read them back for validation or data extraction.
// Prompt: Create a sample that reads a batch of TIFF images applying AustraliaPostSettings.CustomerInformationInterpretingType.NTable.
-// Tags: barcode symbology, australia post, batch processing, tiff, barcodereader, decode type, customerinformationinterpretingtype
+// Tags: barcode, australia post, ntable, tiff, generation, recognition, aspose.barcode
using System;
using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Sample program that reads up to five TIFF images from a folder and decodes
-/// Australia Post barcodes using the NTable customer information interpreting type.
+/// Sample program that generates Australia Post barcodes as TIFF files,
+/// then reads them back applying the NTable customer information interpreting type.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the sample. Generates sample TIFF images if they do not exist,
+ /// then iterates through each file, reading barcodes with NTable interpretation.
///
static void Main()
{
- // Define the folder that contains the TIFF images.
- string folderPath = "tiff_images";
-
- // Verify that the folder exists before proceeding.
- if (!Directory.Exists(folderPath))
+ // Define the folder that will contain the sample TIFF images
+ string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "InputImages");
+ if (!Directory.Exists(inputFolder))
{
- Console.WriteLine($"Folder not found: {folderPath}");
- return;
+ // Create the folder when it does not exist
+ Directory.CreateDirectory(inputFolder);
}
- // Retrieve all TIFF files in the folder (case‑insensitive pattern).
- string[] tiffFiles = Directory.GetFiles(folderPath, "*.tif");
- // Limit processing to a maximum of five files.
- int filesToProcess = Math.Min(tiffFiles.Length, 5);
+ // Sample data to encode into Australia Post barcodes
+ string[] sampleTexts = new[] { "1100000000", "4501234567", "5901234567" };
- // Iterate over each selected TIFF file.
- for (int i = 0; i < filesToProcess; i++)
+ // Generate TIFF images for each sample text if they are missing
+ for (int i = 0; i < sampleTexts.Length; i++)
{
- string file = tiffFiles[i];
-
- // Ensure the file still exists (it could have been removed externally).
- if (!File.Exists(file))
+ string filePath = Path.Combine(inputFolder, $"sample{i + 1}.tif");
+ if (!File.Exists(filePath))
{
- Console.WriteLine($"File not found: {file}");
- continue;
+ GenerateAustraliaPostTiff(sampleTexts[i], filePath);
}
+ }
+
+ // Retrieve all TIFF files from the input folder
+ string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif");
+ if (tiffFiles.Length == 0)
+ {
+ Console.WriteLine("No TIFF files found in the input folder.");
+ return;
+ }
- // Load the TIFF image into a bitmap object.
- using (Bitmap bitmap = new Bitmap(file))
+ // Process each TIFF file individually
+ foreach (string file in tiffFiles)
+ {
+ Console.WriteLine($"Processing file: {Path.GetFileName(file)}");
+ using (var reader = new BarCodeReader(file, DecodeType.AustraliaPost))
{
- // Create a barcode reader configured for Australia Post symbology.
- using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost))
- {
- // Set the customer information interpreting type to NTable.
- reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.NTable;
+ // Set the interpreting type to NTable for customer information
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.NTable;
- // Read all barcodes found in the image.
- foreach (var result in reader.ReadBarCodes())
+ // Read all barcodes present in the image
+ BarCodeResult[] results = reader.ReadBarCodes();
+ if (results.Length == 0)
+ {
+ Console.WriteLine(" No barcodes detected.");
+ }
+ else
+ {
+ // Output details of each detected barcode
+ foreach (var result in results)
{
- // Output details of each detected barcode.
- Console.WriteLine($"File: {Path.GetFileName(file)}");
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"CodeText: {result.CodeText}");
- var rect = result.Region.Rectangle;
- Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
- Console.WriteLine();
+ Console.WriteLine($" Type: {result.CodeType}");
+ Console.WriteLine($" CodeText: {result.CodeText}");
}
}
}
}
}
+
+ // Generates an Australia Post barcode image saved as a TIFF file
+ static void GenerateAustraliaPostTiff(string codeText, string filePath)
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ {
+ // Configure the generator to use the NTable interpreting type
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.NTable;
+
+ // Create the barcode image in memory
+ using (var bitmap = generator.GenerateBarCodeImage())
+ {
+ // Save the image to the specified file path in TIFF format
+ using (var stream = new FileStream(filePath, FileMode.Create))
+ {
+ bitmap.Save(stream, ImageFormat.Tiff);
+ }
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/design-ui-component-allowing-users-to-toggle-stripfnc-and-view-real-time-decoding-results.cs b/special-barcode-recognition-settings/design-ui-component-allowing-users-to-toggle-stripfnc-and-view-real-time-decoding-results.cs
index 3b15475..a3eb476 100644
--- a/special-barcode-recognition-settings/design-ui-component-allowing-users-to-toggle-stripfnc-and-view-real-time-decoding-results.cs
+++ b/special-barcode-recognition-settings/design-ui-component-allowing-users-to-toggle-stripfnc-and-view-real-time-decoding-results.cs
@@ -1,8 +1,8 @@
-// Title: Toggle StripFNC on GS1-128 barcode decoding
-// Description: Demonstrates generating a GS1‑128 barcode, then decoding it with and without stripping FNC characters to show the effect on the extracted text.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the BarcodeGenerator and BarCodeReader classes, focusing on the StripFNC setting used when decoding GS1‑128 (Code128) barcodes. Developers often need to control whether Function characters are retained or removed during decoding to meet GS1 data formatting requirements.
+// Title: Toggle StripFNC while decoding a GS1‑128 barcode
+// Description: Generates a GS1‑128 barcode containing FNC1 characters, then decodes it twice—once preserving and once stripping the FNC characters—to illustrate the effect of the StripFNC setting.
+// Category-Description: This example belongs to the Aspose.BarCode decoding settings category. It demonstrates how to use BarcodeGenerator, BarCodeReader, and BarcodeSettings to control the StripFNC option, a common requirement when processing GS1 symbologies such as Code128. Developers often need to toggle this setting to obtain raw data or human‑readable output, making it essential for inventory, shipping, and retail applications.
// Prompt: Design a UI component allowing users to toggle StripFNC and view real‑time decoding results.
-// Tags: gs1-128, stripfnc, barcode generation, barcode recognition, code128, png, aspose.barcode
+// Tags: gs1-128, stripfnc, barcode decoding, aspose.barcode, code128, barcode generation, c#
using System;
using System.IO;
@@ -11,63 +11,76 @@
using Aspose.Drawing;
///
-/// Generates a GS1‑128 barcode, then reads it twice: once preserving FNC characters
-/// and once stripping them, illustrating the impact of the StripFNC setting.
+/// Demonstrates generating a GS1‑128 barcode with FNC1 characters and decoding it
+/// with the StripFNC option toggled on and off.
///
class Program
{
///
- /// Entry point of the example. Creates a barcode image in memory, then decodes it
- /// with different StripFNC configurations.
+ /// Entry point of the example. Generates a barcode, then decodes it twice
+ /// to show the impact of the StripFNC setting.
///
static void Main()
{
- // Sample GS1‑128 barcode text containing FNC characters
- const string barcodeText = "(02)04006664241007(37)1(400)7019590754";
+ // Sample GS1‑128 data containing FNC1 characters (application identifiers)
+ const string barcodeData = "(02)04006664241007(37)1(400)7019590754";
- // Generate the barcode image into a memory stream (PNG format)
+ // Create an in‑memory stream to hold the generated barcode image
using (var imageStream = new MemoryStream())
{
- using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, barcodeText))
+ // Generate the barcode image and write it to the stream
+ using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, barcodeData))
{
- // Save the generated barcode as PNG to the stream
+ // Save the barcode as PNG into the memory stream
generator.Save(imageStream, BarCodeImageFormat.Png);
+ // Reset the stream position so it can be read from the beginning
+ imageStream.Position = 0;
}
- // Reset stream position so it can be read from the beginning
+ // Decode the barcode without stripping FNC characters
+ DecodeAndPrint(imageStream, stripFnc: false);
+
+ // Reset the stream position for the second decoding pass
imageStream.Position = 0;
- // Local function that reads the barcode with a specified StripFNC value
- void ReadAndDisplay(bool stripFnc)
- {
- // Ensure the stream is positioned at the start before creating a bitmap
- imageStream.Position = 0;
+ // Decode the barcode with FNC characters stripped
+ DecodeAndPrint(imageStream, stripFnc: true);
+ }
+ }
- // Load the image from the stream into a bitmap object
- using (var bitmap = new Bitmap(imageStream))
- {
- // Initialize a reader for Code128 (covers GS1‑128)
- using (var reader = new BarCodeReader(bitmap, DecodeType.Code128))
- {
- // Apply the StripFNC setting (true = remove FNC characters)
- reader.BarcodeSettings.StripFNC = stripFnc;
+ ///
+ /// Decodes the barcode from the provided stream and prints the result to the console.
+ ///
+ /// Stream containing the barcode image.
+ /// If true, FNC characters are stripped from the decoded text.
+ private static void DecodeAndPrint(Stream stream, bool stripFnc)
+ {
+ // Initialize a reader for Code128 barcodes using the supplied image stream
+ using (var reader = new BarCodeReader(stream, DecodeType.Code128))
+ {
+ // Apply the StripFNC setting based on the caller's request
+ reader.BarcodeSettings.StripFNC = stripFnc;
- // Perform barcode recognition and output results
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"StripFNC = {stripFnc}");
- Console.WriteLine($" Type : {result.CodeTypeName}");
- Console.WriteLine($" Text : {result.CodeText}");
- }
- }
- }
- }
+ // Perform the decoding operation
+ BarCodeResult[] results = reader.ReadBarCodes();
- // Decode and display results without stripping FNC characters
- ReadAndDisplay(false);
+ Console.WriteLine($"--- Decoding with StripFNC = {stripFnc} ---");
+ if (results.Length == 0)
+ {
+ Console.WriteLine("No barcode detected.");
+ return;
+ }
- // Decode and display results with FNC characters stripped
- ReadAndDisplay(true);
+ // Iterate through all detected barcodes and output their details
+ foreach (BarCodeResult result in results)
+ {
+ Console.WriteLine($"Type : {result.CodeTypeName}");
+ Console.WriteLine($"Text : {result.CodeText}");
+ Console.WriteLine($"Angle : {result.Region.Angle}");
+ Console.WriteLine($"Region : X={result.Region.Rectangle.X}, Y={result.Region.Rectangle.Y}, " +
+ $"Width={result.Region.Rectangle.Width}, Height={result.Region.Rectangle.Height}");
+ Console.WriteLine();
+ }
}
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/develop-batch-job-that-extracts-images-from-pdf-files-and-decodes-barcodes-with-multithreading-enabled.cs b/special-barcode-recognition-settings/develop-batch-job-that-extracts-images-from-pdf-files-and-decodes-barcodes-with-multithreading-enabled.cs
index 1f38c3c..171837b 100644
--- a/special-barcode-recognition-settings/develop-batch-job-that-extracts-images-from-pdf-files-and-decodes-barcodes-with-multithreading-enabled.cs
+++ b/special-barcode-recognition-settings/develop-batch-job-that-extracts-images-from-pdf-files-and-decodes-barcodes-with-multithreading-enabled.cs
@@ -1,100 +1,145 @@
-// Title: Batch PDF Image Extraction and Barcode Decoding with Multithreading
-// Description: Demonstrates how to extract page images from PDF files and decode any barcodes found using Aspose.Pdf and Aspose.BarCode in a parallel batch job.
-// Category-Description: This example belongs to the Aspose.BarCode and Aspose.Pdf integration category, showing how to combine PDF rendering with barcode recognition. It covers key API classes such as Document, PdfConverter, and BarCodeReader, typical for scenarios like invoice processing, shipping label verification, or bulk document scanning where developers need to efficiently extract images and read barcodes from multiple PDFs concurrently.
+// Title: Multithreaded PDF Image Extraction and Barcode Decoding Example
+// Description: Demonstrates a batch job that extracts images from PDF files and decodes any embedded barcodes using Aspose.BarCode and Aspose.Pdf.
+// Category-Description: This example belongs to the Aspose.BarCode PDF processing category, showcasing how to combine Aspose.Pdf for image extraction with Aspose.BarCode for barcode recognition. It covers key API classes such as Document, PdfConverter, BarCodeReader, and BarcodeGenerator, typical for developers who need to automate barcode scanning from PDF documents in high‑throughput scenarios.
// Prompt: Develop a batch job that extracts images from PDF files and decodes barcodes with multithreading enabled.
-// Tags: barcode symbology, decoding, image extraction, multithreading, aspose.pdf, aspose.barcode
+// Tags: barcode, pdf, multithreading, aspose.barcode, aspose.pdf, code128, image-extraction, barcode-recognition
using System;
using System.IO;
using System.Threading.Tasks;
+using System.Collections.Generic;
+using Aspose.BarCode.BarCodeRecognition;
using Aspose.Pdf;
using Aspose.Pdf.Facades;
-using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing.Imaging;
///
-/// Example program that processes PDF files in a folder, extracts each page as an image,
-/// and decodes any barcodes found using Aspose.Pdf and Aspose.BarCode.
+/// Demonstrates extracting images from PDF files and decoding barcodes using Aspose libraries with parallel processing.
///
class Program
{
///
- /// Entry point of the application. Accepts an optional folder path argument,
- /// processes up to three PDF files in parallel, and writes barcode results to the console.
+ /// Entry point of the application. Sets up input/output folders, creates a sample PDF if needed,
+ /// and processes PDF files in parallel to extract images and read barcodes.
///
- /// Command‑line arguments; first argument can specify the input folder.
+ /// Command‑line arguments (not used).
static void Main(string[] args)
{
- // Determine input folder: use first argument or default to "./pdfs" relative to the current directory.
- string inputFolder = args.Length > 0
- ? args[0]
- : Path.Combine(Directory.GetCurrentDirectory(), "pdfs");
+ // Define input and output directories relative to the current working directory.
+ string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "InputPdfs");
+ string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "OutputResults");
- // Verify that the input folder exists.
+ // Ensure the required folders exist.
if (!Directory.Exists(inputFolder))
- {
- Console.WriteLine($"Input folder does not exist: {inputFolder}");
- return;
- }
+ Directory.CreateDirectory(inputFolder);
+ if (!Directory.Exists(outputFolder))
+ Directory.CreateDirectory(outputFolder);
- // Retrieve all PDF files in the folder (limit to three files for safe execution in evaluation mode).
+ // Retrieve all PDF files from the input folder.
string[] pdfFiles = Directory.GetFiles(inputFolder, "*.pdf");
+
+ // If no PDFs are present, create a sample PDF containing a barcode.
if (pdfFiles.Length == 0)
{
- Console.WriteLine("No PDF files found.");
- return;
+ CreateSamplePdf(Path.Combine(inputFolder, "Sample.pdf"));
+ pdfFiles = Directory.GetFiles(inputFolder, "*.pdf");
}
- int maxFiles = Math.Min(pdfFiles.Length, 3);
- var filesToProcess = pdfFiles[..maxFiles];
+ // Limit processing to a maximum of five files for safety.
+ var filesToProcess = new List(pdfFiles);
+ if (filesToProcess.Count > 5)
+ filesToProcess = filesToProcess.GetRange(0, 5);
+
+ // Configure parallel execution to use all available processor cores.
+ ParallelOptions parallelOptions = new ParallelOptions
+ {
+ MaxDegreeOfParallelism = Environment.ProcessorCount
+ };
+
+ // Process each PDF file concurrently.
+ Parallel.ForEach(filesToProcess, parallelOptions, pdfPath =>
+ {
+ try
+ {
+ ProcessPdf(pdfPath);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Error processing '{Path.GetFileName(pdfPath)}': {ex.Message}");
+ }
+ });
- // Process each selected PDF file in parallel, using a degree of parallelism equal to the processor count.
- Parallel.ForEach(
- filesToProcess,
- new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
- pdfPath =>
+ Console.WriteLine("Processing completed.");
+ }
+
+ // Generates a simple PDF containing a Code128 barcode image.
+ private static void CreateSamplePdf(string pdfPath)
+ {
+ // Create a barcode generator for Code128 with sample text.
+ using (var generator = new Aspose.BarCode.Generation.BarcodeGenerator(Aspose.BarCode.Generation.EncodeTypes.Code128, "Sample123"))
+ {
+ // Render the barcode to a bitmap.
+ using (Aspose.Drawing.Bitmap bitmap = generator.GenerateBarCodeImage())
{
- try
+ // Save the bitmap to a memory stream as PNG.
+ using (var imageStream = new MemoryStream())
{
- // Load the PDF document.
- using var pdfDocument = new Document(pdfPath);
+ bitmap.Save(imageStream, ImageFormat.Png);
+ imageStream.Position = 0;
- // Initialize a converter to render PDF pages to images.
- var converter = new PdfConverter(pdfDocument)
+ // Create a new PDF document and embed the barcode image.
+ var doc = new Document();
+ var page = doc.Pages.Add();
+ var pdfImage = new Aspose.Pdf.Image
{
- // Enable barcode optimization to improve recognition speed.
- RenderingOptions = { BarcodeOptimization = true }
+ ImageStream = imageStream
};
+ page.Paragraphs.Add(pdfImage);
+ doc.Save(pdfPath);
+ }
+ }
+ }
+ }
+
+ // Extracts images from a PDF and decodes any barcodes found on each page.
+ private static void ProcessPdf(string pdfPath)
+ {
+ // Load the PDF document.
+ using (var pdfDocument = new Document(pdfPath))
+ {
+ int totalPages = pdfDocument.Pages.Count;
+ // Process up to the first four pages to limit workload.
+ int pagesToProcess = Math.Min(totalPages, 4);
- // Limit processing to the first four pages (evaluation mode restriction).
- int pageCount = Math.Min(pdfDocument.Pages.Count, 4);
+ // Initialize a PdfConverter for image rendering.
+ using (var pdfConverter = new PdfConverter(pdfDocument))
+ {
+ pdfConverter.RenderingOptions.BarcodeOptimization = true;
+
+ // Iterate through the selected pages.
+ for (int pageNumber = 1; pageNumber <= pagesToProcess; pageNumber++)
+ {
+ pdfConverter.StartPage = pageNumber;
+ pdfConverter.EndPage = pageNumber;
+ pdfConverter.DoConvert();
- for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++)
+ // Retrieve the rendered page image.
+ using (var imageStream = new MemoryStream())
{
- // Configure the converter to process a single page.
- converter.StartPage = pageNumber;
- converter.EndPage = pageNumber;
- converter.DoConvert();
-
- // Retrieve the rendered image into a memory stream.
- using var imageStream = new MemoryStream();
- converter.GetNextImage(imageStream);
+ pdfConverter.GetNextImage(imageStream);
imageStream.Position = 0;
- // Create a barcode reader that attempts to decode all supported symbologies.
- using var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes);
-
- // Iterate through all detected barcodes and output their details.
- foreach (var result in reader.ReadBarCodes())
+ // Use BarCodeReader to detect and decode any barcodes in the image.
+ using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
{
- Console.WriteLine($"{Path.GetFileName(pdfPath)} - Page {pageNumber}: Type={result.CodeTypeName}, Text={result.CodeText}");
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"File: {Path.GetFileName(pdfPath)}, Page: {pageNumber}, Type: {result.CodeTypeName}, Text: {result.CodeText}");
+ }
}
}
}
- catch (Exception ex)
- {
- // Log any errors that occur while processing the current PDF.
- Console.WriteLine($"Error processing '{pdfPath}': {ex.Message}");
- }
- });
+ }
+ }
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/develop-console-application-that-decodes-all-barcodes-in-directory-with-stripfnc-false-and-prints-results.cs b/special-barcode-recognition-settings/develop-console-application-that-decodes-all-barcodes-in-directory-with-stripfnc-false-and-prints-results.cs
index 5ca4c36..73a67f5 100644
--- a/special-barcode-recognition-settings/develop-console-application-that-decodes-all-barcodes-in-directory-with-stripfnc-false-and-prints-results.cs
+++ b/special-barcode-recognition-settings/develop-console-application-that-decodes-all-barcodes-in-directory-with-stripfnc-false-and-prints-results.cs
@@ -1,81 +1,93 @@
-// Title: Decode all barcodes in a directory with StripFNC disabled
-// Description: This console app scans a specified folder, decodes every supported barcode in image files while preserving FNC characters, and prints detailed results.
-// Category-Description: Demonstrates Aspose.BarCode barcode recognition across multiple image formats. It uses BarCodeReader and DecodeType.AllSupportedTypes, showing how to configure BarcodeSettings (StripFNC) and iterate over BarCodeResult objects. Ideal for developers needing batch processing of barcodes in files, such as inventory audits or document digitization.
+// Title: Decode Multiple Barcodes in a Directory with StripFNC Disabled
+// Description: The example scans a folder for barcode images, decodes every barcode using Aspose.BarCode with StripFNC set to false, and prints the type and text to the console.
+// Category-Description: This sample belongs to the Aspose.BarCode recognition category, demonstrating how to use BarCodeReader to process multiple image files, configure BarcodeSettings (e.g., StripFNC), and retrieve results. Typical use cases include batch processing of scanned documents, inventory verification, or automated data extraction where developers need to read all supported symbologies from a set of images.
// Prompt: Develop a console application that decodes all barcodes in a directory with StripFNC false and prints results.
-// Tags: barcode, decoding, batch, stripfnc, console, aspose.barcode, recognition
+// Tags: barcode, symbology, recognition, batch, console, stripfnc, aspose.barcode, decode
using System;
using System.IO;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Entry point for the barcode batch decoding console application.
+/// Demonstrates decoding all barcodes in a directory with StripFNC disabled using Aspose.BarCode.
///
class Program
{
///
- /// Scans a directory for image files, decodes all supported barcodes with StripFNC disabled, and writes results to the console.
+ /// Entry point. Generates sample barcodes, scans the folder, and decodes each image.
///
- /// Optional first argument specifying the directory path; if omitted, the current directory is used.
+ /// Command‑line arguments (not used).
static void Main(string[] args)
{
- // Determine the directory to scan. Use the first argument if provided; otherwise, use the current directory.
- string directoryPath = args.Length > 0 ? args[0] : Directory.GetCurrentDirectory();
+ // Define the folder to store and read barcode images
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(folderPath))
+ {
+ Directory.CreateDirectory(folderPath);
+ }
+
+ // Generate a few sample barcode images (Code128, QR, EAN13)
+ GenerateSampleBarcodes(folderPath);
- // Verify that the directory exists before proceeding.
- if (!Directory.Exists(directoryPath))
+ // Scan the folder for image files (png, jpg, bmp)
+ string[] patterns = new[] { "*.png", "*.jpg", "*.bmp" };
+ var imageFiles = new System.Collections.Generic.List();
+ foreach (string pattern in patterns)
{
- Console.WriteLine($"Directory does not exist: {directoryPath}");
- return;
+ string[] files = Directory.GetFiles(folderPath, pattern);
+ imageFiles.AddRange(files);
}
- // Retrieve all files in the directory (non‑recursive). Adjust the filter if you want to limit to specific image extensions.
- string[] files = Directory.GetFiles(directoryPath);
- if (files.Length == 0)
+ if (imageFiles.Count == 0)
{
- Console.WriteLine($"No files found in directory: {directoryPath}");
+ Console.WriteLine("No barcode images found in the folder.");
return;
}
- // Process each file individually.
- foreach (string filePath in files)
+ // Decode each image with StripFNC set to false
+ foreach (string filePath in imageFiles)
{
- // Skip non‑existing files (should not happen) and filter out unsupported extensions.
- if (!File.Exists(filePath))
- continue;
-
- string extension = Path.GetExtension(filePath).ToLowerInvariant();
- if (extension != ".png" && extension != ".jpg" && extension != ".jpeg" && extension != ".bmp" && extension != ".tif" && extension != ".tiff")
- continue;
-
- // Use BarCodeReader to decode barcodes in the current image file.
+ Console.WriteLine($"Decoding file: {Path.GetFileName(filePath)}");
using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
- // Ensure FNC characters are not stripped (set to false as required).
+ // Ensure StripFNC is false (default, but set explicitly)
reader.BarcodeSettings.StripFNC = false;
- // Perform the recognition and obtain all results.
- BarCodeResult[] results = reader.ReadBarCodes();
-
- // If no barcodes were detected, report and continue to the next file.
- if (results.Length == 0)
- {
- Console.WriteLine($"[File: {Path.GetFileName(filePath)}] No barcodes detected.");
- continue;
- }
-
- // Output summary information for the current file.
- Console.WriteLine($"[File: {Path.GetFileName(filePath)}] Detected {results.Length} barcode(s):");
-
- // Iterate through each detected barcode and display detailed information.
- foreach (BarCodeResult result in results)
+ // Read all barcodes in the image
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
Console.WriteLine($" Type: {result.CodeTypeName}");
Console.WriteLine($" CodeText: {result.CodeText}");
- Console.WriteLine($" Confidence: {result.Confidence}");
- Console.WriteLine($" ReadingQuality: {result.ReadingQuality}");
}
}
}
}
+
+ // Helper method to generate sample barcode images
+ private static void GenerateSampleBarcodes(string folder)
+ {
+ // Code128
+ string code128Path = Path.Combine(folder, "code128.png");
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ generator.Save(code128Path);
+ }
+
+ // QR Code
+ string qrPath = Path.Combine(folder, "qr.png");
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ {
+ generator.Save(qrPath);
+ }
+
+ // EAN13
+ string ean13Path = Path.Combine(folder, "ean13.png");
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.EAN13, "1234567890128"))
+ {
+ generator.Save(ean13Path);
+ }
+ }
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/develop-service-that-reads-australia-post-barcodes-from-network-share-and-applies-ignoreendingfillingpatternsforctable.cs b/special-barcode-recognition-settings/develop-service-that-reads-australia-post-barcodes-from-network-share-and-applies-ignoreendingfillingpatternsforctable.cs
index 88701e0..211c8ac 100644
--- a/special-barcode-recognition-settings/develop-service-that-reads-australia-post-barcodes-from-network-share-and-applies-ignoreendingfillingpatternsforctable.cs
+++ b/special-barcode-recognition-settings/develop-service-that-reads-australia-post-barcodes-from-network-share-and-applies-ignoreendingfillingpatternsforctable.cs
@@ -1,103 +1,105 @@
-// Title: Read Australia Post barcodes from network share with CTable settings
-// Description: Demonstrates how to scan images on a network share for Australia Post barcodes, applying the CTable interpreting type and ignoring ending filling patterns.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on Australia Post symbology. It shows usage of BarCodeReader, DecodeType.AustraliaPost, and BarcodeSettings to configure CustomerInformationInterpretingType and IgnoreEndingFillingPatternsForCTable. Developers often need to process batches of images from shared locations and customize interpretation settings for accurate data extraction.
+// Title: Read Australia Post Barcodes with CTable Settings from Network Share
+// Description: Demonstrates reading Australia Post barcodes from image files located on a network share and configuring the reader to ignore ending filling patterns for CTable interpretation.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category. It showcases the use of BarCodeReader, DecodeType.AustraliaPost, and related settings such as CustomerInformationInterpretingType and IgnoreEndingFillingPatternsForCTable. Typical use cases include batch processing of postal barcodes stored on shared storage, where developers need to customize decoding behavior for specific symbology requirements.
// Prompt: Develop a service that reads Australia Post barcodes from a network share and applies IgnoreEndingFillingPatternsForCTable.
-// Tags: australia post, barcode recognition, ctable, ignoreendingfillingpatterns, network share, aspnet, aspose.barcode
+// Tags: australia post, barcode reading, ctable, ignoreendingfillingpatterns, aspose.barcode, image processing
using System;
using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Example service that scans image files on a network share for Australia Post barcodes,
-/// configuring the reader to use CTable interpretation and to ignore ending filling patterns.
+/// Example program that generates sample Australia Post barcodes, stores them in a folder
+/// simulating a network share, and reads them using Aspose.BarCode with specific CTable settings.
///
class Program
{
///
- /// Entry point of the example. Iterates through supported image files in a network folder,
- /// reads Australia Post barcodes, and outputs detection results to the console.
+ /// Entry point. Generates sample barcodes, then reads each image applying
+ /// CustomerInformationInterpretingType.CTable and ignoring ending filling patterns.
///
static void Main()
{
- // Network share path containing barcode images.
- string networkFolder = @"\\server\share\barcodes";
+ // Define the folder that simulates a network share.
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ EnsureFolderExists(folderPath);
- // Verify the folder exists before proceeding.
- if (!Directory.Exists(networkFolder))
- {
- Console.WriteLine($"Folder not found: {networkFolder}");
- return;
- }
-
- // Define supported image extensions for barcode scanning.
- string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff" };
- string[] files = Directory.GetFiles(networkFolder);
-
- bool anyFileProcessed = false;
+ // Generate a few sample Australia Post barcodes.
+ GenerateSampleBarcodes(folderPath, 3);
- // Process each file found in the network folder.
- foreach (string filePath in files)
+ // Process each barcode image in the folder.
+ string[] imageFiles = Directory.GetFiles(folderPath, "*.png");
+ foreach (string imagePath in imageFiles)
{
- // Skip files that do not have a supported image extension.
- if (Array.IndexOf(extensions, Path.GetExtension(filePath).ToLowerInvariant()) < 0)
- continue;
-
- anyFileProcessed = true;
-
- // Ensure the file still exists (it could have been removed after enumeration).
- if (!File.Exists(filePath))
+ if (!File.Exists(imagePath))
{
- Console.WriteLine($"File not found: {filePath}");
+ Console.WriteLine($"File not found: {imagePath}");
continue;
}
- try
+ // Read the barcode using AustraliaPost settings.
+ using (var reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost))
{
- // Load the image into a bitmap and create a barcode reader for Australia Post symbology.
- using (Bitmap bitmap = new Bitmap(filePath))
- using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost))
+ // Apply CTable interpreting type and ignore ending filling patterns.
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
+ reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = true;
+
+ // Iterate through all detected barcodes in the image.
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- // Configure the reader to interpret customer information as CTable
- // and to ignore any ending filling patterns that may be present.
- reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
- reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = true;
+ Console.WriteLine($"File: {Path.GetFileName(imagePath)}");
+ Console.WriteLine($" BarCode Type: {result.CodeType}");
+ Console.WriteLine($" BarCode CodeText: {result.CodeText}");
+ }
+ }
+ }
+ }
- bool found = false;
+ ///
+ /// Ensures that the specified folder exists, creating it if necessary.
+ ///
+ /// The folder path to verify.
+ static void EnsureFolderExists(string path)
+ {
+ if (!Directory.Exists(path))
+ {
+ Directory.CreateDirectory(path);
+ }
+ }
- // Iterate through all detected barcodes in the current image.
- foreach (var result in reader.ReadBarCodes())
- {
- found = true;
- Console.WriteLine($"File: {Path.GetFileName(filePath)}");
- Console.WriteLine($" Barcode Type : {result.CodeType}");
- Console.WriteLine($" Code Text : {result.CodeText}");
+ ///
+ /// Generates a set of sample Australia Post barcode images and saves them as PNG files.
+ ///
+ /// The folder where barcode images will be saved.
+ /// The number of barcodes to generate (up to the number of sample texts).
+ static void GenerateSampleBarcodes(string folder, int count)
+ {
+ // Sample code texts for Australia Post barcodes.
+ string[] sampleTexts = new string[]
+ {
+ "5912345678AB",
+ "5912345678CD",
+ "5912345678EF"
+ };
- // Output the region of the barcode within the image.
- var rect = result.Region.Rectangle;
- Console.WriteLine($" Region : X={rect.X}, Y={rect.Y}, Width={rect.Width}, Height={rect.Height}");
- }
+ for (int i = 0; i < count && i < sampleTexts.Length; i++)
+ {
+ string codeText = sampleTexts[i];
+ string fileName = $"AustraliaPost_{i + 1}.png";
+ string filePath = Path.Combine(folder, fileName);
- // If no barcodes were detected, inform the user.
- if (!found)
- {
- Console.WriteLine($"File: {Path.GetFileName(filePath)} - No AustraliaPost barcode detected.");
- }
- }
- }
- catch (Exception ex)
+ // Create a barcode generator for the Australia Post symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
{
- // Report any errors that occur while processing the file.
- Console.WriteLine($"Error processing file '{Path.GetFileName(filePath)}': {ex.Message}");
- }
- }
+ // Use CTable interpreting type for the generated barcode.
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- // If no supported image files were found, notify the user.
- if (!anyFileProcessed)
- {
- Console.WriteLine("No image files found in the specified folder.");
+ // Save the barcode image as PNG.
+ generator.Save(filePath, BarCodeImageFormat.Png);
+ }
}
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/develop-utility-that-converts-decoded-australia-post-barcode-data-to-json-using-custom-decoder.cs b/special-barcode-recognition-settings/develop-utility-that-converts-decoded-australia-post-barcode-data-to-json-using-custom-decoder.cs
index 2160339..efe4a54 100644
--- a/special-barcode-recognition-settings/develop-utility-that-converts-decoded-australia-post-barcode-data-to-json-using-custom-decoder.cs
+++ b/special-barcode-recognition-settings/develop-utility-that-converts-decoded-australia-post-barcode-data-to-json-using-custom-decoder.cs
@@ -1,8 +1,8 @@
-// Title: Australia Post Barcode to JSON Converter Using Custom Decoder
-// Description: Demonstrates decoding Australia Post barcodes and converting the extracted customer information into JSON format.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases how to use BarcodeGenerator, BarCodeReader, and custom decoder classes (AustraliaPostCustomerInformationDecoder) to process Australia Post symbology, a common requirement for logistics and mailing applications. Developers often need to extract embedded customer data from barcodes and transform it into structured formats such as JSON.
+// Title: Australia Post Barcode to JSON Converter with Custom Decoder
+// Description: Demonstrates generating an Australia Post barcode, decoding it with a custom customer information decoder, and outputting the extracted data as formatted JSON.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeReader for decoding, and the custom AustraliaPostCustomerInformationDecoder interface for handling customer‑specific fields. Developers often need to generate barcodes for shipping, scan them in automated workflows, and transform the raw data into structured formats such as JSON for downstream processing.
// Prompt: Develop a utility that converts decoded Australia Post barcode data to JSON using a custom decoder.
-// Tags: australia post, barcode, decoding, json, custom decoder, aspose.barcode
+// Tags: australia post,barcode,generation,recognition,custom decoder,json,aspose.barcode
using System;
using System.IO;
@@ -15,73 +15,100 @@
namespace AustraliaPostBarcodeUtility
{
///
- /// Custom decoder implementing the Aspose interface for Australia Post customer information.
+ /// Custom decoder implementing the interface for customer information field.
+ /// For demonstration it simply returns the raw field data.
///
- public class CustomCustomerInfoDecoder : AustraliaPostCustomerInformationDecoder
+ public class MyCustomerInfoDecoder : AustraliaPostCustomerInformationDecoder
{
- // Simple example: just return the raw bar values as decoded text.
- public string Decode(string barValues)
+ // Real implementation would decode based on CTable/NTable rules.
+ public string Decode(string customerInformationField)
{
- // In a real scenario, translate bar values (0‑3) to meaningful data here.
- return barValues;
+ return customerInformationField ?? string.Empty;
}
}
///
- /// Example utility that generates an Australia Post barcode, reads it using a custom decoder,
- /// and outputs the decoded customer information as JSON.
+ /// Entry point for the Australia Post barcode utility.
+ /// Generates a barcode, decodes it with a custom decoder, and prints JSON output.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, reads it, decodes customer info,
- /// and prints the JSON representation to the console.
+ /// Main method that orchestrates barcode generation, decoding, and JSON serialization.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Sample Australia Post barcode text (routing + identifier + customer info).
- const string barcodeText = "5912345678ABCde";
+ // Sample data: FCC = "59", DPID = "12345678", customer info = "AB" (CTable, up to 5 chars)
+ string sampleCodeText = "5912345678AB";
- // Create the barcode generator for Australia Post symbology.
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, barcodeText))
+ // Path for temporary barcode image
+ string imagePath = Path.Combine(Path.GetTempPath(), "australiapost.png");
+
+ // Generate Australia Post barcode and save as PNG
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, sampleCodeText))
{
- // Use CTable interpreting type for customer information.
+ // Use CTable interpreting type for customer information
generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
+
+ // Verify the image was created
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"Failed to create barcode image at {imagePath}");
+ return;
+ }
+
+ // Read and decode the barcode using the same interpreting type
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost))
+ {
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
+ // Assign custom decoder
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder = new MyCustomerInfoDecoder();
- // Generate the barcode image in memory.
- using (var image = generator.GenerateBarCodeImage())
+ // Process results (expecting a single barcode)
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- // Set up the reader with the custom decoder.
- using (var reader = new BarCodeReader(image, DecodeType.AustraliaPost))
+ if (string.IsNullOrEmpty(result.CodeText))
{
- // Configure reader to use CTable and the custom decoder.
- reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
- reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder = new CustomCustomerInfoDecoder();
-
- // Perform recognition and process each detected barcode.
- foreach (var result in reader.ReadBarCodes())
- {
- // Full code text from the barcode (may be null).
- string fullCode = result.CodeText ?? string.Empty;
+ Console.WriteLine("No CodeText detected.");
+ continue;
+ }
- // Extract the customer information part (after first 10 characters).
- string customerInfoRaw = fullCode.Length > 10 ? fullCode.Substring(10) : string.Empty;
+ // Parse FCC (first 2 chars) and DPID (next 8 chars)
+ string fcc = result.CodeText.Substring(0, 2);
+ string dpid = result.CodeText.Substring(2, 8);
+ string rawCustomerInfo = result.CodeText.Length > 10 ? result.CodeText.Substring(10) : string.Empty;
- // Decode using the custom decoder.
- string decodedInfo = ((CustomCustomerInfoDecoder)reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder)
- .Decode(customerInfoRaw);
+ // Use the custom decoder to interpret the customer information field
+ string decodedCustomerInfo = reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder.Decode(rawCustomerInfo);
- // Convert decoded information to formatted JSON.
- string json = JsonSerializer.Serialize(
- new { CustomerInfo = decodedInfo },
- new JsonSerializerOptions { WriteIndented = true });
+ // Build an anonymous object for JSON serialization
+ var jsonObject = new
+ {
+ FCC = fcc,
+ DPID = dpid,
+ RawCustomerInfo = rawCustomerInfo,
+ DecodedCustomerInfo = decodedCustomerInfo,
+ Symbology = result.CodeType.ToString()
+ };
- // Output the JSON to the console.
- Console.WriteLine(json);
- }
- }
+ // Serialize to JSON with indentation and output to console
+ string json = JsonSerializer.Serialize(jsonObject, new JsonSerializerOptions { WriteIndented = true });
+ Console.WriteLine(json);
}
}
+
+ // Clean up temporary image file
+ try
+ {
+ File.Delete(imagePath);
+ }
+ catch
+ {
+ // Ignored – file may be locked or already removed
+ }
}
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/develop-utility-that-converts-decoded-australia-post-barcode-data-to-xml-using-selected-interpreting-type.cs b/special-barcode-recognition-settings/develop-utility-that-converts-decoded-australia-post-barcode-data-to-xml-using-selected-interpreting-type.cs
index 1566cfe..73a2096 100644
--- a/special-barcode-recognition-settings/develop-utility-that-converts-decoded-australia-post-barcode-data-to-xml-using-selected-interpreting-type.cs
+++ b/special-barcode-recognition-settings/develop-utility-that-converts-decoded-australia-post-barcode-data-to-xml-using-selected-interpreting-type.cs
@@ -1,10 +1,11 @@
-// Title: Convert Australia Post barcode data to XML using interpreting type
-// Description: Demonstrates generating an Australia Post barcode, recognizing it, and converting the decoded data into an XML representation.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on Australia Post symbology. It showcases the use of BarcodeGenerator, BarCodeReader, and related settings such as CustomerInformationInterpretingType. Developers often need to generate barcodes, read them back, and transform the decoded information into structured formats like XML for integration with other systems.
+// Title: Convert Australia Post Barcode Data to XML
+// Description: Demonstrates decoding an Australia Post barcode and exporting its fields to an XML file.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to generate an Australia Post barcode, decode it using the BarCodeReader, interpret customer information, and serialize the extracted data (FCC, DPID, and optional customer info) into XML. Developers working with postal barcode automation often need to extract and store barcode data in structured formats, and this sample illustrates the key API classes (BarcodeGenerator, BarCodeReader, CustomerInformationInterpretingType) and typical usage patterns.
// Prompt: Develop a utility that converts decoded Australia Post barcode data to XML using the selected interpreting type.
-// Tags: australia post, barcode generation, barcode recognition, xml output, customerinformationinterpretingtype, aspose.barcode
+// Tags: australia post,barcode generation,barcode recognition,xml output,customer information interpreting,aspose.barcode
using System;
+using System.IO;
using System.Xml.Linq;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
@@ -12,55 +13,86 @@
using Aspose.Drawing;
///
-/// Demonstrates converting decoded Australia Post barcode data to XML using a selected interpreting type.
+/// Provides a console utility that generates an Australia Post barcode, decodes it,
+/// and writes the extracted information to an XML file.
///
class Program
{
///
- /// Entry point of the utility. Generates a barcode, reads it, and outputs XML.
+ /// Entry point of the utility. Accepts an optional command‑line argument to specify
+ /// the used for both generation and recognition.
///
- /// Command‑line arguments (not used).
+ /// Command‑line arguments; the first argument may be a valid interpreting type.
static void Main(string[] args)
{
- // Sample Australia Post barcode data (postal code + customer information)
- string codeText = "5912345678ABCde";
-
- // Choose the interpreting type for the customer information field
+ // Determine interpreting type from command‑line argument; default to CTable.
CustomerInformationInterpretingType interpretingType = CustomerInformationInterpretingType.CTable;
+ if (args.Length > 0)
+ {
+ if (Enum.TryParse(args[0], true, out CustomerInformationInterpretingType parsed))
+ interpretingType = parsed;
+ else
+ Console.WriteLine($"Unrecognized interpreting type '{args[0]}', using default CTable.");
+ }
- // Create a barcode generator for Australia Post symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ // Sample Australia Post barcode data: FCC (2) + DPID (8) + optional customer info.
+ string sampleCodeText = "5912345678ABCde";
+
+ // Generate the barcode image using the selected interpreting type.
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, sampleCodeText))
{
- // Apply the selected interpreting type to the generator settings
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = interpretingType;
+ // Apply the interpreting type for barcode generation.
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = interpretingType;
- // Generate the barcode image as a bitmap
- using (Bitmap bitmap = generator.GenerateBarCodeImage())
+ using (Aspose.Drawing.Bitmap bitmap = generator.GenerateBarCodeImage())
{
- // Initialize a barcode reader for Australia Post decoding
- using (var reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost))
+ // Recognize the barcode from the generated image.
+ using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost))
{
- // Apply the same interpreting type to the reader settings
+ // Apply the same interpreting type for recognition.
reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = interpretingType;
- // When using CTable, optionally ignore ending filling patterns
+ // Optional: ignore ending filling patterns when using CTable.
if (interpretingType == CustomerInformationInterpretingType.CTable)
- {
reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = true;
- }
- // Iterate over detected barcodes (only one expected in this example)
- foreach (var result in reader.ReadBarCodes())
+ // Read all detected barcodes (expecting a single result).
+ BarCodeResult[] results = reader.ReadBarCodes();
+ if (results.Length == 0)
{
- // Build a simple XML representation of the decoded barcode data
- XElement xml = new XElement(
- "AustraliaPostBarcode",
- new XAttribute("InterpretingType", interpretingType),
- new XElement("CodeText", result.CodeText ?? string.Empty));
+ Console.WriteLine("No Australia Post barcode detected.");
+ return;
+ }
+
+ // Use the first result as the target barcode.
+ BarCodeResult result = results[0];
+ string codeText = result.CodeText ?? string.Empty;
- // Write the XML to the console
- Console.WriteLine(xml);
+ // Validate that the decoded text contains at least FCC and DPID.
+ if (codeText.Length < 10)
+ {
+ Console.WriteLine("Decoded code text is too short to contain required FCC and DPID.");
+ return;
}
+
+ // Extract FCC (first 2 characters), DPID (next 8 characters), and any remaining customer information.
+ string fcc = codeText.Substring(0, 2);
+ string dpid = codeText.Substring(2, 8);
+ string customerInfo = codeText.Length > 10 ? codeText.Substring(10) : string.Empty;
+
+ // Build an XML document representing the decoded data.
+ XDocument xmlDoc = new XDocument(
+ new XElement("AustraliaPostBarcode",
+ new XElement("FCC", fcc),
+ new XElement("DPID", dpid),
+ new XElement("CustomerInformation", customerInfo)
+ )
+ );
+
+ // Save the XML document to the current working directory.
+ string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "AustraliaPostOutput.xml");
+ xmlDoc.Save(outputPath);
+ Console.WriteLine($"Decoded data saved to XML file: {outputPath}");
}
}
}
diff --git a/special-barcode-recognition-settings/disable-multithreaded-barcode-reading-by-setting-processorsettingsuseallcores-false-and-useonlythiscorescount-to-1.cs b/special-barcode-recognition-settings/disable-multithreaded-barcode-reading-by-setting-processorsettingsuseallcores-false-and-useonlythiscorescount-to-1.cs
index 269561d..16baa19 100644
--- a/special-barcode-recognition-settings/disable-multithreaded-barcode-reading-by-setting-processorsettingsuseallcores-false-and-useonlythiscorescount-to-1.cs
+++ b/special-barcode-recognition-settings/disable-multithreaded-barcode-reading-by-setting-processorsettingsuseallcores-false-and-useonlythiscorescount-to-1.cs
@@ -1,49 +1,60 @@
-// Title: Disable multithreaded barcode reading example
-// Description: Demonstrates how to turn off multi‑core processing for barcode recognition using Aspose.BarCode, ensuring single‑threaded execution.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of ProcessorSettings to control threading. It shows how to configure UseAllCores and UseOnlyThisCoresCount for the BarCodeReader class, a common requirement when integrating barcode scanning into environments with limited resources or when deterministic performance is needed. Developers often need to adjust these settings to match their application’s concurrency model.
+// Title: Disable Multithreaded Barcode Reading with ProcessorSettings
+// Description: Demonstrates how to generate a Code128 barcode, save it as PNG, and configure Aspose.BarCode to use a single CPU core for barcode recognition.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader with ProcessorSettings to control multithreading during decoding. Developers often need to limit CPU usage in environments with constrained resources or when deterministic performance is required.
// Prompt: Disable multithreaded barcode reading by setting ProcessorSettings.UseAllCores false and UseOnlyThisCoresCount to 1.
-// Tags: barcode, multithreading, processor settings, code128, generation, recognition, aspose.barcode
+// Tags: code128, generation, recognition, png, barcodegenerator, barcodereader, processorsettings, multithreading
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates disabling multithreaded barcode reading using Aspose.BarCode.
+/// Example program that creates a Code128 barcode, saves it as a PNG file,
+/// and reads it back using single‑core processing settings.
///
class Program
{
///
- /// Entry point. Generates a sample Code128 barcode if missing, configures single‑threaded processing, and reads the barcode.
+ /// Entry point of the application.
///
static void Main()
{
- // Define the path for the sample barcode image.
- string imagePath = "sample_barcode.png";
+ // Path where the generated barcode image will be stored
+ string imagePath = "sample.png";
- // Generate a sample barcode if it does not already exist on disk.
- if (!File.Exists(imagePath))
+ // ------------------------------------------------------------
+ // Generate a simple Code128 barcode and save it as PNG
+ // ------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
- {
- // Save the generated barcode as a PNG file.
- generator.Save(imagePath, BarCodeImageFormat.Png);
- }
+ // Save the barcode image to the specified file
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // Configure the processor to use a single core (disable multithreading).
+ // ------------------------------------------------------------
+ // Configure the barcode reader to use only one CPU core
+ // ------------------------------------------------------------
BarCodeReader.ProcessorSettings.UseAllCores = false;
BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 1;
- // Initialize the reader with the image and specify the expected barcode type.
- using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.Code128))
+ // Verify that the barcode image file exists before attempting to read it
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"Barcode image not found at path: {Path.GetFullPath(imagePath)}");
+ return;
+ }
+
+ // ------------------------------------------------------------
+ // Read the barcode from the image using the configured settings
+ // ------------------------------------------------------------
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- // Iterate through all detected barcodes and output their details.
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
+ Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
+ Console.WriteLine($"Decoded Text: {result.CodeText}");
}
}
}
diff --git a/special-barcode-recognition-settings/enable-australiapostsettingsignoreendingfillingpatternsforctable-to-suppress-filler-z-symbols-in-ctable-mode.cs b/special-barcode-recognition-settings/enable-australiapostsettingsignoreendingfillingpatternsforctable-to-suppress-filler-z-symbols-in-ctable-mode.cs
index eb97d28..71a4c01 100644
--- a/special-barcode-recognition-settings/enable-australiapostsettingsignoreendingfillingpatternsforctable-to-suppress-filler-z-symbols-in-ctable-mode.cs
+++ b/special-barcode-recognition-settings/enable-australiapostsettingsignoreendingfillingpatternsforctable-to-suppress-filler-z-symbols-in-ctable-mode.cs
@@ -1,51 +1,62 @@
// Title: Suppress filler symbols in Australia Post CTable barcode decoding
-// Description: Demonstrates how to enable IgnoreEndingFillingPatternsForCTable to remove trailing "z" filler symbols when decoding Australia Post barcodes in CTable mode.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on Australia Post symbology. It shows usage of BarcodeGenerator, BarCodeReader, and related settings such as AustralianPostEncodingTable and IgnoreEndingFillingPatternsForCTable. Developers often need to generate barcodes and accurately decode them while handling filler patterns, especially in logistics and mailing applications.
+// Description: Demonstrates generating an Australia Post barcode with CTable customer information and decoding it while ignoring the trailing filler "z" symbols.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader for extracting data. Typical use cases include postal automation and custom data encoding where developers need to control decoding behavior, such as ignoring filler patterns in CTable mode. The key API classes are BarcodeGenerator, BarCodeReader, and related settings classes.
// Prompt: Enable AustraliaPostSettings.IgnoreEndingFillingPatternsForCTable to suppress filler "z" symbols in CTable mode.
-// Tags: australia post, ctable, ignore ending filling patterns, barcode generation, barcode recognition, aspnet.barcode
+// Tags: australia post, barcode, ctable, ignore filler, generation, recognition, png, aspose.barcode
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating an Australia Post barcode in CTable mode and decoding it while suppressing filler "z" symbols.
+/// Generates an Australia Post barcode with CTable customer information,
+/// saves it as an image, and then reads it while ignoring the ending filler
+/// patterns ("z") in CTable mode.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, saves it, and reads it back with specific settings.
+ /// Entry point of the example. Performs barcode generation, saving,
+ /// and recognition with specific decoding settings.
///
static void Main()
{
- // Create a barcode generator for Australia Post with sample data
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678AB"))
- {
- // Configure the generator to use the CTable interpreting type
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable;
+ // Sample Australia Post code text:
+ // FCC = 59, DPID = 12345678, Customer info = "AB" (CTable, 2 chars)
+ const string codeText = "5912345678AB";
- // Save the generated barcode image to a file
- generator.Save("AustraliaPost.png");
+ // Initialize the barcode generator for Australia Post symbology
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ {
+ // Configure the generator to use CTable interpreting type for customer information
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- // Generate the barcode image in memory for immediate decoding
- using (Bitmap image = generator.GenerateBarCodeImage())
+ // Generate the barcode image as a bitmap
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
- // Initialize a barcode reader for the generated image, targeting Australia Post symbology
- using (BarCodeReader reader = new BarCodeReader(image, DecodeType.AustraliaPost))
+ // Save the generated image to disk for verification
+ const string imagePath = "AustraliaPost.png";
+ bitmap.Save(imagePath, ImageFormat.Png);
+ Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(imagePath)}");
+
+ // Initialize a barcode reader to decode the generated image
+ using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost))
{
// Set the reader to interpret customer information using CTable
reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
- // Enable suppression of ending filler patterns ("z") in CTable mode
+ // Enable ignoring of ending filling patterns (the "z" filler) in CTable mode
reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = true;
- // Iterate through all detected barcodes and output their details
+ // Iterate through all detected barcodes and display their type and decoded text
foreach (BarCodeResult result in reader.ReadBarCodes())
{
- Console.WriteLine("BarCode Type: " + result.CodeTypeName);
- Console.WriteLine("BarCode CodeText: " + result.CodeText);
+ Console.WriteLine($"Detected Type: {result.CodeType}");
+ Console.WriteLine($"Decoded Text : {result.CodeText}");
}
}
}
diff --git a/special-barcode-recognition-settings/implement-custom-class-inheriting-customerinformationdecoder-and-assign-it-to-australiapostsettingscustomdecoder.cs b/special-barcode-recognition-settings/implement-custom-class-inheriting-customerinformationdecoder-and-assign-it-to-australiapostsettingscustomdecoder.cs
index 283f2f0..daf4e1b 100644
--- a/special-barcode-recognition-settings/implement-custom-class-inheriting-customerinformationdecoder-and-assign-it-to-australiapostsettingscustomdecoder.cs
+++ b/special-barcode-recognition-settings/implement-custom-class-inheriting-customerinformationdecoder-and-assign-it-to-australiapostsettingscustomdecoder.cs
@@ -1,8 +1,8 @@
-// Title: Custom Australia Post barcode decoder example
-// Description: Demonstrates how to implement a custom CustomerInformationDecoder for Australia Post barcodes and apply it during recognition.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on custom decoding of Australia Post customer information fields. It showcases the use of BarcodeGenerator, BarCodeReader, AustraliaPostSettings, and the CustomerInformationDecoder interface, which developers often need when integrating Australia Post barcode processing into applications that require bespoke interpretation of encoded data.
+// Title: Custom Customer Information Decoder for Australia Post Barcodes
+// Description: Demonstrates implementing a custom CustomerInformationDecoder and assigning it to AustraliaPostSettings to decode the customer information field of an Australia Post barcode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on the Australia Post symbology. It showcases the use of BarcodeGenerator, BarCodeReader, AustraliaPostSettings, and the CustomerInformationDecoder interface to customize decoding of customer‑information fields. Developers working with postal barcodes often need to interpret encoded customer data beyond the default decoding, making custom decoders a common requirement.
// Prompt: Implement a custom class inheriting CustomerInformationDecoder and assign it to AustraliaPostSettings.CustomDecoder.
-// Tags: barcode symbology, australia post, custom decoder, generation, recognition, aspnet.barcode
+// Tags: australia post, barcode, custom decoder, customer information, generation, recognition, aspose.barcode
using System;
using Aspose.BarCode;
@@ -13,65 +13,71 @@
namespace AustraliaPostCustomDecoderDemo
{
///
- /// Custom decoder implementing the interface.
- /// Returns the raw customer information field prefixed with "Decoded:".
+ /// Custom decoder that implements
+ /// to provide bespoke decoding of the customer information field.
///
- public class MyCustomerInfoDecoder : AustraliaPostCustomerInformationDecoder
+ public class CustomCustomerInfoDecoder : AustraliaPostCustomerInformationDecoder
{
///
- /// Decodes the supplied customer information field.
+ /// Decodes the raw customer information field.
///
- /// Raw field data from the barcode.
- /// Decoded string prefixed with "Decoded:".
+ /// The raw field extracted from the barcode.
+ /// A string representing the decoded customer information.
public string Decode(string customerInformationField)
{
- // In a real scenario, decode the bar values (0,1,2,3) into meaningful text.
- return "Decoded:" + customerInformationField;
+ // In a real scenario, implement CTable/NTable decoding logic here.
+ return $"CustomDecoded[{customerInformationField}]";
}
}
///
- /// Demonstrates generation of an Australia Post barcode and reading it with a custom decoder.
+ /// Demonstrates generating an Australia Post barcode, reading it, and using a custom decoder.
///
class Program
{
///
- /// Generates an Australia Post barcode, saves it to a file, then reads it using a custom decoder.
+ /// Entry point of the demo application.
///
static void Main()
{
- const string outputFile = "australia_post.png";
+ // Sample Australia Post barcode with FCC=59, DPID=12345678, customer info "AB".
+ string codeText = "5912345678AB";
- // Generate an Australia Post barcode with CTable interpreting type.
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678AB"))
+ // Create a barcode generator for the Australia Post symbology and set the encoding table to CTable (allows letters).
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
{
- // Set the encoding table for the customer information field.
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable;
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- // Create the barcode image and save it as PNG.
- using (var image = generator.GenerateBarCodeImage())
+ // Generate the barcode image.
+ using (Bitmap image = generator.GenerateBarCodeImage())
{
- image.Save(outputFile, Aspose.Drawing.Imaging.ImageFormat.Png);
- }
- }
+ // Initialize a reader for Australia Post barcodes.
+ using (BarCodeReader reader = new BarCodeReader(image, DecodeType.AustraliaPost))
+ {
+ // Assign the custom decoder to the Australia Post settings.
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder = new CustomCustomerInfoDecoder();
- // Read the barcode and apply the custom decoder.
- using (var reader = new BarCodeReader(outputFile, DecodeType.AustraliaPost))
- {
- // Assign the custom decoder to the AustraliaPost settings.
- reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder = new MyCustomerInfoDecoder();
+ // Ensure the interpreting type matches the generator's setting.
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
- // Ensure the interpreting type matches the generator's setting.
- reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
+ // Read all detected barcodes.
+ foreach (BarCodeResult result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Code Type: {result.CodeType}");
+ Console.WriteLine($"Detected Code Text: {result.CodeText}");
- // Iterate through detected barcodes and output basic information.
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine("BarCode Type: " + result.CodeType);
- Console.WriteLine("BarCode CodeText: " + result.CodeText);
- // The custom decoder influences internal interpretation of the customer information field.
+ // Extract the raw customer information (after FCC(2) + DPID(8)).
+ string rawCustomerInfo = result.CodeText.Substring(10);
+ // Use the custom decoder directly.
+ string decodedInfo = ((AustraliaPostCustomerInformationDecoder)reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder).Decode(rawCustomerInfo);
+ Console.WriteLine($"Custom Decoded Customer Info: {decodedInfo}");
+ }
+ }
}
}
+
+ // Indicate that processing has finished.
+ Console.WriteLine("Processing completed.");
}
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/implement-diagnostic-tool-that-reports-current-threadpool-thread-counts-before-and-after-barcode-processing.cs b/special-barcode-recognition-settings/implement-diagnostic-tool-that-reports-current-threadpool-thread-counts-before-and-after-barcode-processing.cs
index 1d77b6a..19d8079 100644
--- a/special-barcode-recognition-settings/implement-diagnostic-tool-that-reports-current-threadpool-thread-counts-before-and-after-barcode-processing.cs
+++ b/special-barcode-recognition-settings/implement-diagnostic-tool-that-reports-current-threadpool-thread-counts-before-and-after-barcode-processing.cs
@@ -1,67 +1,70 @@
-// Title: ThreadPool Diagnostic for Barcode Generation and Recognition
-// Description: Demonstrates how to capture ThreadPool thread counts before and after generating and reading a Code128 barcode using Aspose.BarCode.
-// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing the use of BarcodeGenerator for creating barcodes and BarCodeReader for decoding them. Developers often need to generate barcodes in various formats (e.g., PNG) and subsequently validate them, while also monitoring resource usage such as ThreadPool threads in high‑throughput applications.
+// Title: ThreadPool Diagnostic for Aspose.BarCode Generation and Recognition
+// Description: Demonstrates how to capture ThreadPool thread counts before and after barcode generation and reading using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode processing category, illustrating the use of BarcodeGenerator for creating barcodes and BarCodeReader for decoding them. It shows typical workflow steps—setup, generation, decoding, and cleanup—while reporting ThreadPool metrics, a common need for developers optimizing concurrency and resource usage in barcode applications.
// Prompt: Implement a diagnostic tool that reports current ThreadPool thread counts before and after barcode processing.
-// Tags: code128, generation, recognition, png, threadpool, diagnostics
+// Tags: barcode, threadpool, diagnostics, generation, recognition, code128, png, aspose.barcode
using System;
using System.IO;
using System.Threading;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Provides a diagnostic demonstration of ThreadPool usage during barcode generation and recognition.
+/// Demonstrates ThreadPool diagnostics around barcode generation and recognition using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates a Code128 barcode, reads it back, and reports ThreadPool thread counts before and after processing.
+ /// Retrieves current ThreadPool information.
///
- static void Main()
+ /// A formatted string containing available and maximum worker and I/O threads.
+ static string GetThreadPoolInfo()
{
- // Capture ThreadPool thread counts before any barcode operation
- ThreadPool.GetAvailableThreads(out int workerThreadsBefore, out int completionPortsBefore);
- Console.WriteLine($"ThreadPool available worker threads before: {workerThreadsBefore}");
- Console.WriteLine($"ThreadPool available completion port threads before: {completionPortsBefore}");
+ ThreadPool.GetAvailableThreads(out int workerThreads, out int completionPortThreads);
+ ThreadPool.GetMaxThreads(out int maxWorker, out int maxCompletion);
+ return $"Available Worker Threads: {workerThreads}/{maxWorker}, Available IO Threads: {completionPortThreads}/{maxCompletion}";
+ }
- // Define a temporary file path for the generated barcode image
- string tempFile = Path.Combine(Path.GetTempPath(), "barcode.png");
+ ///
+ /// Entry point. Reports ThreadPool status, generates a Code128 barcode, reads it back, and reports ThreadPool status again.
+ ///
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
+ {
+ // Display ThreadPool info before any barcode work.
+ Console.WriteLine("ThreadPool info before barcode processing:");
+ Console.WriteLine(GetThreadPoolInfo());
- // Generate a simple Code128 barcode and save it as a PNG image
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Prepare output directory for generated barcode images.
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(outputDir))
{
- generator.Save(tempFile, BarCodeImageFormat.Png);
+ Directory.CreateDirectory(outputDir);
}
- // Initialize a barcode reader to decode the previously generated image
- using (BarCodeReader reader = new BarCodeReader(tempFile, DecodeType.Code128))
+ string barcodePath = Path.Combine(outputDir, "sample.png");
+
+ // Generate a barcode image using Code128 symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Iterate through all detected barcodes (expected one in this case)
- foreach (BarCodeResult result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected barcode type: {result.CodeTypeName}");
- Console.WriteLine($"Detected barcode text: {result.CodeText}");
- }
+ generator.Save(barcodePath);
}
- // Capture ThreadPool thread counts after barcode generation and recognition
- ThreadPool.GetAvailableThreads(out int workerThreadsAfter, out int completionPortsAfter);
- Console.WriteLine($"ThreadPool available worker threads after: {workerThreadsAfter}");
- Console.WriteLine($"ThreadPool available completion port threads after: {completionPortsAfter}");
-
- // Clean up the temporary barcode image file
- if (File.Exists(tempFile))
+ // Read the generated barcode to simulate processing work.
+ if (File.Exists(barcodePath))
{
- try
+ using (var reader = new BarCodeReader(barcodePath, DecodeType.Code128))
{
- File.Delete(tempFile);
- }
- catch
- {
- // Suppress any exceptions during cleanup to avoid interrupting the diagnostic flow
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Read barcode: Type={result.CodeTypeName}, Text={result.CodeText}");
+ }
}
}
+
+ // Display ThreadPool info after barcode work.
+ Console.WriteLine("ThreadPool info after barcode processing:");
+ Console.WriteLine(GetThreadPoolInfo());
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/implement-error-handling-for-unsupported-barcode-types-when-stripfnc-is-true-and-fnc-symbols-are-present.cs b/special-barcode-recognition-settings/implement-error-handling-for-unsupported-barcode-types-when-stripfnc-is-true-and-fnc-symbols-are-present.cs
index b966f85..317c105 100644
--- a/special-barcode-recognition-settings/implement-error-handling-for-unsupported-barcode-types-when-stripfnc-is-true-and-fnc-symbols-are-present.cs
+++ b/special-barcode-recognition-settings/implement-error-handling-for-unsupported-barcode-types-when-stripfnc-is-true-and-fnc-symbols-are-present.cs
@@ -1,106 +1,96 @@
-// Title: StripFNC Support Validation for Barcode Types
-// Description: Demonstrates generating a barcode, enabling StripFNC during reading, and validating that the barcode symbology supports FNC stripping.
-// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader with BarcodeSettings to decode them. Developers often need to handle FNC (Function) characters, especially in GS1 implementations, and must verify that the selected symbology supports stripping these characters. The code illustrates typical error‑handling patterns for unsupported barcode types.
+// Title: StripFNC handling for unsupported barcode types in Aspose.BarCode
+// Description: Demonstrates generating a GS1‑128 barcode, reading it with StripFNC enabled, and handling cases where the barcode type does not support stripping FNC symbols.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the BarcodeGenerator, BarCodeReader, and BarcodeSettings classes for creating GS1‑128 barcodes, configuring decoding options such as StripFNC, and implementing error handling for unsupported symbologies. Developers working with barcode preprocessing, data sanitization, or compliance with GS1 standards can use these patterns when integrating Aspose.BarCode into .NET applications.
// Prompt: Implement error handling for unsupported barcode types when StripFNC is true and FNC symbols are present.
-// Tags: barcode symbology, fnc stripping, error handling, aspose.barcode, generation, recognition, c#
+// Tags: barcode, gs1-128, stripfnc, error-handling, generation, recognition, aspose.barcode, .net
using System;
+using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode;
+using Aspose.Drawing;
///
-/// Example program that generates a barcode, enables StripFNC during reading,
-/// and validates whether the barcode type supports FNC stripping.
+/// Demonstrates barcode generation, reading with StripFNC, and error handling for unsupported barcode types.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, configures the reader,
- /// checks for FNC support, and decodes the barcode while handling possible errors.
+ /// Entry point of the example. Generates a GS1‑128 barcode, saves it, and attempts to read it with StripFNC enabled.
///
static void Main()
{
- // Define the barcode type and a code text that includes an FNC placeholder.
- // In real scenarios FNC characters are represented differently,
- // but for demonstration we use the string "".
- BaseEncodeType barcodeType = EncodeTypes.Code128;
- string originalCodeText = "ABCDEF";
+ // Prepare output directory and file path.
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Output");
+ Directory.CreateDirectory(outputDir);
+ string imagePath = Path.Combine(outputDir, "barcode.png");
- // --------------------------------------------------------------------
- // Generate and save the barcode image.
- // --------------------------------------------------------------------
- using (var generator = new BarcodeGenerator(barcodeType, originalCodeText))
+ // Generate a GS1‑128 barcode that contains an implicit FNC1 (via AI parentheses).
+ try
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, "(01)12345678901231"))
+ {
+ // Save the generated barcode image to disk.
+ generator.Save(imagePath);
+ Console.WriteLine($"Barcode image saved to: {imagePath}");
+ }
+ }
+ catch (Exception ex)
{
- generator.Save("barcode.png");
+ Console.WriteLine($"Error during barcode generation: {ex.Message}");
+ return;
}
- // --------------------------------------------------------------------
- // Prepare the barcode reader with StripFNC enabled.
- // --------------------------------------------------------------------
- using (var reader = new BarCodeReader("barcode.png", DecodeType.Code128))
+ // Attempt to read the barcode with StripFNC enabled.
+ // DecodeType.Code128 (non‑GS1) is used to simulate an unsupported scenario.
+ try
{
- // Enable stripping of FNC characters during decoding.
- reader.BarcodeSettings.StripFNC = true;
-
- // List of symbologies that support FNC stripping.
- BaseEncodeType[] fncSupported = new[]
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- EncodeTypes.GS1Code128,
- EncodeTypes.GS1QR,
- EncodeTypes.GS1DataMatrix,
- EncodeTypes.GS1Aztec,
- EncodeTypes.GS1HanXin,
- EncodeTypes.GS1CompositeBar,
- EncodeTypes.GS1DotCode,
- EncodeTypes.GS1MicroPdf417,
- EncodeTypes.QR,
- EncodeTypes.DataMatrix,
- EncodeTypes.Aztec
- };
+ // Enable stripping of FNC characters during decoding.
+ reader.BarcodeSettings.StripFNC = true;
- // ----------------------------------------------------------------
- // Validate that the selected barcode type supports StripFNC
- // when an FNC placeholder is present in the original code text.
- // ----------------------------------------------------------------
- if (reader.BarcodeSettings.StripFNC && originalCodeText.Contains(""))
- {
- bool isSupported = false;
- foreach (var supported in fncSupported)
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- if (barcodeType.Equals(supported))
+ // If StripFNC is true but control characters remain, treat this as an unsupported barcode type.
+ if (reader.BarcodeSettings.StripFNC && ContainsControlCharacters(result.CodeText))
{
- isSupported = true;
- break;
+ throw new ArgumentException(
+ $"StripFNC is not supported for barcode type '{result.CodeTypeName}' when FNC symbols are present.");
}
- }
- if (!isSupported)
- {
- // Report the unsupported scenario; developers may choose to throw.
- Console.WriteLine($"Error: StripFNC is enabled, but barcode type '{barcodeType.GetType().Name}' does not support FNC characters.");
- // throw new ArgumentException("Unsupported barcode type for StripFNC.");
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"CodeText : {result.CodeText}");
}
}
+ }
+ catch (ArgumentException argEx)
+ {
+ Console.WriteLine($"Argument error: {argEx.Message}");
+ }
+ catch (BarCodeException bcEx)
+ {
+ Console.WriteLine($"Barcode library error: {bcEx.Message}");
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Unexpected error: {ex.Message}");
+ }
+ }
- // ----------------------------------------------------------------
- // Attempt to read the barcode and handle any Aspose.BarCode exceptions.
- // ----------------------------------------------------------------
- try
- {
- foreach (BarCodeResult result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Decoded CodeText: {result.CodeText}");
- }
- }
- catch (Aspose.BarCode.BarCodeException ex)
- {
- Console.WriteLine($"BarCodeException caught: {ex.Message}");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Unexpected exception: {ex.Message}");
- }
+ // Helper method: checks for control characters (e.g., FNC1 = 0x1D) in the decoded text.
+ private static bool ContainsControlCharacters(string text)
+ {
+ if (string.IsNullOrEmpty(text))
+ return false;
+
+ foreach (char ch in text)
+ {
+ // ASCII control range 0x00‑0x1F (excluding common whitespace characters).
+ if (ch < 0x20 && ch != '\r' && ch != '\n' && ch != '\t')
+ return true;
}
+ return false;
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/implement-fallback-decoder-that-switches-to-single-thread-mode-if-multithreaded-processing-exceeds-memory-limits.cs b/special-barcode-recognition-settings/implement-fallback-decoder-that-switches-to-single-thread-mode-if-multithreaded-processing-exceeds-memory-limits.cs
index bed1b0d..f53c45a 100644
--- a/special-barcode-recognition-settings/implement-fallback-decoder-that-switches-to-single-thread-mode-if-multithreaded-processing-exceeds-memory-limits.cs
+++ b/special-barcode-recognition-settings/implement-fallback-decoder-that-switches-to-single-thread-mode-if-multithreaded-processing-exceeds-memory-limits.cs
@@ -1,72 +1,101 @@
-// Title: Fallback barcode decoder with single‑thread fallback
-// Description: Demonstrates reading a barcode using multithreaded processing and automatically falling back to single‑thread mode when memory limits are exceeded.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to configure BarCodeReader processor settings for multi‑core and single‑core execution. It illustrates typical use cases such as handling large images or memory‑constrained environments where developers need to switch processing modes dynamically.
+// Title: Fallback Barcode Decoder with Single‑Thread Fallback
+// Description: Demonstrates decoding a barcode using multithreaded processing and automatically falling back to single‑thread mode when memory limits are exceeded.
+// Category-Description: This example belongs to the Aspose.BarCode decoding category, showcasing how to configure BarCodeReader.ProcessorSettings for high‑performance, multithreaded barcode recognition. It illustrates typical use cases such as processing large images or batch decoding where memory consumption may vary, and provides a graceful fallback strategy for developers who need reliable decoding without crashes.
// Prompt: Implement a fallback decoder that switches to single‑thread mode if multithreaded processing exceeds memory limits.
-// Tags: qr, fallback, multithread, singlethread, memory, barcodereader, aspose.barcode, decode
+// Tags: barcode, decoding, multithread, fallback, memory, aspose.barcode, code128, processorsettings
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Example program that generates a QR barcode, attempts to read it using multithreaded processing,
-/// and falls back to single‑threaded processing if an exception (e.g., memory pressure) occurs.
+/// Sample program that decodes a barcode image, using multithreaded processing with a fallback to single‑thread mode on .
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, reads it with multithreading,
- /// and retries with a single thread on failure.
+ /// Entry point. Generates a sample barcode if needed, then attempts to decode it using multithreaded processing,
+ /// falling back to single‑thread mode if memory is insufficient.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Generate a sample QR barcode and keep it in memory
- using (var ms = new MemoryStream())
+ // Define a sample barcode image path
+ string imagePath = "sample.png";
+
+ // Ensure a barcode image exists (generate if missing)
+ if (!File.Exists(imagePath))
{
- var generator = new BarcodeGenerator(EncodeTypes.QR, "Sample fallback barcode");
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading
+ GenerateSampleBarcode(imagePath);
+ }
- // Load the image into a bitmap for recognition
- using (var bitmap = new Bitmap(ms))
- {
- // Enable multi‑threaded processing (use all available CPU cores)
- BarCodeReader.ProcessorSettings.UseAllCores = true;
+ // Attempt to decode using multithreaded mode
+ bool decoded = false;
+ try
+ {
+ // Enable all CPU cores for processing
+ BarCodeReader.ProcessorSettings.UseAllCores = true;
+ decoded = DecodeBarcodes(imagePath);
+ }
+ catch (OutOfMemoryException)
+ {
+ Console.WriteLine("OutOfMemoryException caught: switching to single‑thread mode.");
+ // Fallback to single‑thread mode
+ BarCodeReader.ProcessorSettings.UseAllCores = false;
+ BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 1;
+ decoded = DecodeBarcodes(imagePath);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Unexpected error: {ex.Message}");
+ }
- try
- {
- // Attempt to read using multi‑threaded mode
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
- {
- Console.WriteLine("Reading with multi‑threaded mode:");
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}");
- }
- }
- }
- catch (Exception ex)
- {
- // If any exception occurs (e.g., memory pressure), fall back to single‑thread mode
- Console.WriteLine($"Multi‑threaded read failed: {ex.Message}");
- Console.WriteLine("Switching to single‑thread mode...");
+ if (!decoded)
+ {
+ Console.WriteLine("No barcodes were detected.");
+ }
+ }
- // Configure processor to use only one core
- BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 1;
+ // Generates a simple Code128 barcode and saves it to the specified path
+ private static void GenerateSampleBarcode(string path)
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ generator.Save(path);
+ Console.WriteLine($"Generated sample barcode at '{path}'.");
+ }
+ }
- // Re‑attempt reading with single‑threaded settings
- using (var singleReader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
- {
- Console.WriteLine("Reading with single‑threaded mode:");
- foreach (var result in singleReader.ReadBarCodes())
- {
- Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}");
- }
- }
- }
+ // Decodes barcodes from the given image file and prints results
+ private static bool DecodeBarcodes(string imagePath)
+ {
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"File not found: {imagePath}");
+ return false;
+ }
+
+ // Use DecodeType.Code128 as an example; you can add more types if needed
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
+ {
+ // Optionally set quality preset (default is NormalQuality)
+ // reader.QualitySettings = QualitySettings.HighPerformance;
+
+ var results = reader.ReadBarCodes();
+ if (results.Length == 0)
+ {
+ Console.WriteLine("No barcodes found in the image.");
+ return false;
+ }
+
+ foreach (var result in results)
+ {
+ Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}");
}
+
+ return true;
}
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/implement-fallback-mechanism-that-retries-decoding-with-stripfnc-true-if-initial-attempt-with-false-fails.cs b/special-barcode-recognition-settings/implement-fallback-mechanism-that-retries-decoding-with-stripfnc-true-if-initial-attempt-with-false-fails.cs
index 8f0567d..a37ab4f 100644
--- a/special-barcode-recognition-settings/implement-fallback-mechanism-that-retries-decoding-with-stripfnc-true-if-initial-attempt-with-false-fails.cs
+++ b/special-barcode-recognition-settings/implement-fallback-mechanism-that-retries-decoding-with-stripfnc-true-if-initial-attempt-with-false-fails.cs
@@ -1,67 +1,87 @@
-// Title: Barcode decoding with fallback StripFNC setting
-// Description: Demonstrates decoding a Code128 barcode and retrying with StripFNC enabled if the first attempt fails.
-// Category-Description: This example belongs to Aspose.BarCode recognition operations, showcasing the use of BarCodeReader, BarcodeSettings, and DecodeType to read barcodes from images. Developers often need to handle Function Code (FNC) characters that may be present in Code128 symbols; toggling the StripFNC property provides a fallback mechanism for reliable decoding. The snippet serves as a reference for implementing robust barcode reading in .NET applications.
+// Title: Barcode decoding with fallback StripFNC handling
+// Description: Demonstrates generating a GS1 Code128 barcode containing FNC characters and decoding it with a fallback that retries with StripFNC enabled if the first attempt fails.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator (for creating barcodes) and BarCodeReader (for decoding). Typical scenarios include handling GS1 barcodes where Function Code (FNC) characters may need to be stripped during recognition. Developers often need a reliable fallback strategy to ensure successful decoding when initial settings do not yield results.
// Prompt: Implement a fallback mechanism that retries decoding with StripFNC true if initial attempt with false fails.
-// Tags: code128, decoding, stripfnc, fallback, barcodereader, aspose.barcode, .net
+// Tags: barcode, gs1code128, stripfnc, fallback, decoding, generation, aspose.barcode, csharp
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Demonstrates barcode generation and recognition with a fallback StripFNC setting.
+/// Example program showing how to generate a GS1 Code128 barcode and decode it with a fallback mechanism for StripFNC.
///
class Program
{
///
- /// Entry point. Generates a Code128 barcode, attempts to decode it, and retries with StripFNC enabled if needed.
+ /// Entry point. Generates a sample barcode, decodes it with fallback, and outputs the result.
///
static void Main()
{
- // Generate a Code128 barcode image in memory.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123"))
+ // Path for the sample barcode image
+ string imagePath = "sample.png";
+
+ // Generate a barcode that contains FNC characters (GS1 Code128)
+ GenerateSampleBarcode(imagePath);
+
+ // Decode with fallback mechanism (first without stripping FNC, then with stripping)
+ string decodedText = DecodeWithFallback(imagePath);
+
+ // Output the final decoded text (or "null" if decoding failed)
+ Console.WriteLine($"Final decoded text: {(decodedText ?? "null")}");
+ }
+
+ // Generates a GS1 Code128 barcode and saves it to the specified file
+ static void GenerateSampleBarcode(string path)
+ {
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.GS1Code128, "(01)12345678901231(10)ABC"))
{
- using (var ms = new MemoryStream())
- {
- // Save the generated barcode to the memory stream as PNG.
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading.
+ generator.Save(path);
+ }
+ }
- // Load the image from the stream into a Bitmap for recognition.
- using (var bitmap = new Bitmap(ms))
- {
- // Create a reader that supports all barcode types.
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
- {
- // First attempt: do not strip Function Code (FNC) characters.
- reader.BarcodeSettings.StripFNC = false;
- var results = reader.ReadBarCodes();
+ // Attempts to decode the image; if the first attempt (StripFNC = false) fails,
+ // it retries with StripFNC = true.
+ static string DecodeWithFallback(string imagePath)
+ {
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"File not found: {imagePath}");
+ return null;
+ }
+
+ // First attempt: do not strip FNC characters
+ string result = TryDecode(imagePath, stripFnc: false);
+ if (!string.IsNullOrEmpty(result))
+ return result;
+
+ // Second attempt: enable StripFNC to ignore FNC characters
+ return TryDecode(imagePath, stripFnc: true);
+ }
- // Check if decoding succeeded.
- if (results.Length > 0 && !string.IsNullOrEmpty(results[0].CodeText))
- {
- Console.WriteLine("Decoded with StripFNC = false: " + results[0].CodeText);
- }
- else
- {
- // Fallback: enable StripFNC and retry decoding.
- reader.BarcodeSettings.StripFNC = true;
- var retryResults = reader.ReadBarCodes();
+ // Performs a single decode attempt with the specified StripFNC setting
+ static string TryDecode(string imagePath, bool stripFnc)
+ {
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.Code128))
+ {
+ // Configure the reader to strip or retain FNC characters based on the parameter
+ reader.BarcodeSettings.StripFNC = stripFnc;
- if (retryResults.Length > 0 && !string.IsNullOrEmpty(retryResults[0].CodeText))
- {
- Console.WriteLine("Decoded with StripFNC = true: " + retryResults[0].CodeText);
- }
- else
- {
- Console.WriteLine("Failed to decode the barcode.");
- }
- }
- }
+ // Read all barcodes found in the image
+ BarCodeResult[] results = reader.ReadBarCodes();
+ foreach (BarCodeResult res in results)
+ {
+ if (!string.IsNullOrEmpty(res.CodeText))
+ {
+ // Log the successful decode details
+ Console.WriteLine($"StripFNC={stripFnc}, Type={res.CodeTypeName}, Text={res.CodeText}");
+ return res.CodeText;
}
}
}
+
+ // No valid barcode text found in this attempt
+ return null;
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/implement-feature-flag-that-enables-or-disables-multithreaded-barcode-reading-at-application-startup.cs b/special-barcode-recognition-settings/implement-feature-flag-that-enables-or-disables-multithreaded-barcode-reading-at-application-startup.cs
index 799349f..c0cbba1 100644
--- a/special-barcode-recognition-settings/implement-feature-flag-that-enables-or-disables-multithreaded-barcode-reading-at-application-startup.cs
+++ b/special-barcode-recognition-settings/implement-feature-flag-that-enables-or-disables-multithreaded-barcode-reading-at-application-startup.cs
@@ -1,74 +1,88 @@
-// Title: Multithreaded Barcode Reading Feature Flag Demo
-// Description: Demonstrates how to enable or disable multithreaded barcode reading using a startup feature flag.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader and its ProcessorSettings to control threading. Developers often need to toggle multithreading for performance tuning or resource constraints; this snippet shows command‑line configuration of the UseAllCores and UseOnlyThisCoresCount properties.
+// Title: Feature Flag for Multithreaded Barcode Reading
+// Description: Demonstrates how to enable or disable multithreaded barcode reading at application startup using a command‑line flag.
+// Category-Description: This example belongs to the Aspose.BarCode reading category, illustrating the use of BarCodeReader.ProcessorSettings to control CPU core utilization. Developers often need to toggle multithreading for performance tuning or resource‑constrained environments; the key API classes involved are BarCodeReader, ProcessorSettings, and BarcodeGenerator. The snippet shows typical steps: configure settings, generate a barcode, and read it.
// Prompt: Implement a feature flag that enables or disables multithreaded barcode reading at application startup.
-// Tags: barcode symbology, multithreading, feature flag, aspose.barcode, code128, image generation, recognition
+// Tags: barcode symbology, barcode reading, multithreading, processor settings, aspose.barcode, console app, code128
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode;
///
-/// Sample console application that demonstrates a feature flag for enabling or disabling
-/// multithreaded barcode reading using Aspose.BarCode's .
+/// Sample console application that shows how to toggle multithreaded barcode reading using a feature flag.
///
class Program
{
///
- /// Application entry point. Accepts an optional command‑line argument ("true" or "false")
- /// to control whether barcode reading should use all CPU cores.
+ /// Application entry point. Parses a boolean flag to enable or disable multithreading, configures the Aspose.BarCode processor,
+ /// generates a sample Code128 barcode, and reads it.
///
- /// Command‑line arguments; first argument toggles multithreading.
+ /// Command‑line arguments; first argument should be 'true' or 'false' to control multithreading.
static void Main(string[] args)
{
- // Determine whether multithreading is enabled via a feature flag.
- // Default is true; can be overridden by a command‑line argument.
+ // --------------------------------------------------------------------
+ // Parse feature flag from command line (default: true)
+ // --------------------------------------------------------------------
bool enableMultithreading = true;
- if (args.Length > 0 && bool.TryParse(args[0], out bool parsed))
- {
- enableMultithreading = parsed;
- }
-
- // Path to the sample barcode image.
- string imagePath = "sample.png";
-
- // Generate a sample barcode image if it does not already exist.
- if (!File.Exists(imagePath))
+ if (args.Length > 0)
{
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ if (!bool.TryParse(args[0], out enableMultithreading))
{
- generator.Save(imagePath, BarCodeImageFormat.Png);
+ Console.WriteLine("Invalid flag value. Use 'true' or 'false'. Defaulting to true.");
+ enableMultithreading = true;
}
}
- // Configure processor settings based on the feature flag.
- // These settings affect all BarCodeReader instances.
+ // --------------------------------------------------------------------
+ // Configure processor settings based on the flag
+ // --------------------------------------------------------------------
BarCodeReader.ProcessorSettings.UseAllCores = enableMultithreading;
if (!enableMultithreading)
{
- // When multithreading is disabled, restrict processing to a single core.
+ // Restrict to a single core when multithreading is disabled.
BarCodeReader.ProcessorSettings.UseAllCores = false;
BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 1;
}
- // Verify the image file exists before attempting to read.
+ // --------------------------------------------------------------------
+ // Generate a sample barcode image
+ // --------------------------------------------------------------------
+ string imagePath = "sample_barcode.png";
+ GenerateSampleBarcode(imagePath);
+
+ // --------------------------------------------------------------------
+ // Verify the image exists before attempting to read
+ // --------------------------------------------------------------------
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Image file not found: {imagePath}");
+ Console.WriteLine($"Barcode image not found at '{imagePath}'.");
return;
}
- // Read the barcode using BarCodeReader.
+ // --------------------------------------------------------------------
+ // Read the barcode using the configured processor settings
+ // --------------------------------------------------------------------
using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
foreach (var result in reader.ReadBarCodes())
{
Console.WriteLine($"Detected Type: {result.CodeTypeName}");
Console.WriteLine($"Code Text: {result.CodeText}");
- Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
}
}
}
+
+ // ------------------------------------------------------------------------
+ // Generates a simple Code128 barcode and saves it to the specified path.
+ // ------------------------------------------------------------------------
+ private static void GenerateSampleBarcode(string path)
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789"))
+ {
+ // Save as PNG using the appropriate overload.
+ generator.Save(path, BarCodeImageFormat.Png);
+ }
+ }
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/implement-logging-of-each-barcode-decoding-operation-indicating-whether-fnc-symbols-were-stripped-or-retained.cs b/special-barcode-recognition-settings/implement-logging-of-each-barcode-decoding-operation-indicating-whether-fnc-symbols-were-stripped-or-retained.cs
index dac5e84..6e57808 100644
--- a/special-barcode-recognition-settings/implement-logging-of-each-barcode-decoding-operation-indicating-whether-fnc-symbols-were-stripped-or-retained.cs
+++ b/special-barcode-recognition-settings/implement-logging-of-each-barcode-decoding-operation-indicating-whether-fnc-symbols-were-stripped-or-retained.cs
@@ -1,62 +1,92 @@
// Title: GS1 Code128 barcode generation and decoding with optional FNC stripping
-// Description: Demonstrates creating a GS1 Code128 barcode image and decoding it twice—once preserving FNC symbols and once stripping them.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for image creation and BarCodeReader for decoding, highlighting the StripFNC setting. Developers often need to control FNC character handling when working with GS1 symbologies, making this pattern common in inventory and logistics applications.
+// Description: The example creates a GS1 Code128 barcode containing FNC characters, saves it as PNG, then decodes it twice—once preserving and once stripping the FNC symbols—while logging the outcomes.
+// Category-Description: This sample belongs to the Aspose.BarCode generation and recognition category, demonstrating how to use BarcodeGenerator to create GS1 Code128 barcodes and BarCodeReader to recognize them. It highlights handling of FNC (Function) characters via the StripFNC setting, a common requirement in GS1 applications such as product labeling and inventory tracking. Developers often need to toggle FNC stripping to meet different data processing rules, making this pattern useful across many barcode‑related projects.
// Prompt: Implement logging of each barcode decoding operation, indicating whether FNC symbols were stripped or retained.
-// Tags: gs1code128, barcode, generation, decoding, fnc, stripfnc, png, aspnet.barcode, barcodegenerator, barcodereader
+// Tags: gs1, code128, fnc, barcode-generation, barcode-recognition, strip-fnc, aspose.barcode, png
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates generating a GS1 Code128 barcode image and decoding it with and without stripping FNC characters.
+/// Demonstrates generating a GS1 Code128 barcode with FNC characters,
+/// then decoding it with and without stripping those characters while logging the results.
///
class Program
{
///
- /// Entry point of the example. Generates the barcode if needed and performs two decoding runs, logging the results.
+ /// Entry point of the example. Generates a barcode image, verifies its creation,
+ /// and runs two decoding scenarios: preserving and stripping FNC symbols.
///
static void Main()
{
- // Path for the sample barcode image
- const string imagePath = "sample_gs1code128.png";
+ // Prepare output directory
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output");
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
+
+ // Path for the generated barcode image
+ string barcodePath = Path.Combine(outputDir, "gs1code128.png");
- // Sample GS1 Code128 text containing FNC characters (represented by parentheses)
- const string codeText = "(02)04006664241007(37)1(400)7019590754";
+ // Sample GS1 Code128 text containing FNC characters (application identifiers)
+ string sampleText = "(02)04006664241007(37)1(400)7019590754";
- // Generate the barcode image if it does not exist
- if (!File.Exists(imagePath))
+ // Generate the barcode image using BarcodeGenerator
+ using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, sampleText))
{
- using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, codeText))
- {
- // Save the generated barcode to a PNG file
- generator.Save(imagePath);
- Console.WriteLine($"Barcode image generated: {imagePath}");
- }
+ // Save the generated barcode as a PNG file
+ generator.Save(barcodePath, BarCodeImageFormat.Png);
}
- else
+
+ // Verify that the image was successfully created
+ if (!File.Exists(barcodePath))
{
- Console.WriteLine($"Using existing barcode image: {imagePath}");
+ Console.WriteLine("Failed to create barcode image.");
+ return;
}
- // Perform two decoding runs: one without stripping FNC, one with stripping FNC
- bool[] stripFncOptions = new[] { false, true };
+ // Decode the barcode without stripping FNC characters
+ DecodeAndLog(barcodePath, stripFnc: false);
+
+ // Decode the barcode with FNC characters stripped
+ DecodeAndLog(barcodePath, stripFnc: true);
+ }
- foreach (bool stripFnc in stripFncOptions)
+ ///
+ /// Decodes the barcode image and logs the result, indicating whether FNC symbols were stripped.
+ ///
+ /// Path to the barcode image.
+ /// If true, FNC characters will be stripped from the decoded text.
+ private static void DecodeAndLog(string imagePath, bool stripFnc)
+ {
+ Console.WriteLine($"--- Decoding (StripFNC = {stripFnc}) ---");
+
+ // Initialize a reader for Code128 (GS1Code128 is a variant of Code128)
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- using (var reader = new BarCodeReader(imagePath, DecodeType.GS1Code128))
+ // Configure the reader to strip or retain FNC characters based on the parameter
+ reader.BarcodeSettings.StripFNC = stripFnc;
+
+ // Read all barcodes present in the image
+ BarCodeResult[] results = reader.ReadBarCodes();
+
+ if (results.Length == 0)
+ {
+ Console.WriteLine("No barcodes detected.");
+ return;
+ }
+
+ // Log each detected barcode and its decoding details
+ foreach (var result in results)
{
- // Configure whether FNC characters should be stripped from the decoded text
- reader.BarcodeSettings.StripFNC = stripFnc;
-
- // Read all barcodes from the image
- foreach (var result in reader.ReadBarCodes())
- {
- // Log the decoding operation, indicating the StripFNC setting and decoded data
- Console.WriteLine($"StripFNC = {stripFnc} | Detected Type: {result.CodeTypeName} | CodeText: {result.CodeText}");
- }
+ // result.CodeText reflects the StripFNC setting applied above
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"CodeText : {result.CodeText}");
+ Console.WriteLine($"StripFNC : {stripFnc}");
+ Console.WriteLine();
}
}
}
diff --git a/special-barcode-recognition-settings/implement-wrapper-class-that-encapsulates-processorsettings-configuration-for-easy-reuse-across-projects.cs b/special-barcode-recognition-settings/implement-wrapper-class-that-encapsulates-processorsettings-configuration-for-easy-reuse-across-projects.cs
index a4baae7..7986168 100644
--- a/special-barcode-recognition-settings/implement-wrapper-class-that-encapsulates-processorsettings-configuration-for-easy-reuse-across-projects.cs
+++ b/special-barcode-recognition-settings/implement-wrapper-class-that-encapsulates-processorsettings-configuration-for-easy-reuse-across-projects.cs
@@ -1,112 +1,80 @@
-// Title: Wrapper for Aspose.BarCode ProcessorSettings
-// Description: Demonstrates a reusable ProcessorSettings wrapper that configures barcode generation parameters for consistent output across projects.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to encapsulate common barcode settings using the BarcodeGenerator class and related parameter objects. Developers often need a centralized configuration to apply consistent symbology, dimensions, colors, and padding when creating barcodes in .NET applications.
+// Title: Demonstrate configuring Aspose.BarCode ProcessorSettings via a wrapper
+// Description: Shows how to encapsulate ProcessorSettings configuration in a reusable wrapper and uses it to generate and read a Code128 barcode.
+// Category-Description: This example belongs to the Aspose.BarCode processing configuration category, illustrating the use of BarCodeReader.ProcessorSettings and related API classes such as BarcodeGenerator, BarCodeReader, and EncodeTypes. Developers often need to adjust parallel processing settings for performance optimization when handling large volumes of barcode images; this snippet provides a reusable pattern for setting such options across projects.
// Prompt: Implement a wrapper class that encapsulates ProcessorSettings configuration for easy reuse across projects.
-// Tags: barcode symbology, generation, png, aspose.barcode, aspose.drawing
+// Tags: barcode symbology, configuration, parallelism, processor settings, aspose.barcode, generation, recognition
using System;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
+using Aspose.BarCode.BarCodeRecognition;
-///
-/// Encapsulates common barcode generation settings for reuse across projects.
-///
-public class ProcessorSettings
+namespace AsposeBarcodeProcessorSettingsDemo
{
- // Symbology type (e.g., Code128, QR, etc.)
- public BaseEncodeType EncodeType { get; set; }
-
- // Text to encode into the barcode
- public string CodeText { get; set; }
-
- // Module size (x-dimension) in points; default 2f
- public float XDimension { get; set; } = 2f;
-
- // Height of 1D bars when AutoSize is disabled; default 40f
- public float BarHeight { get; set; } = 40f;
-
- // Determines whether the generator should auto‑size the image
- public bool AutoSize { get; set; } = false;
-
- // Foreground (bar) color; default black
- public Color BarColor { get; set; } = Color.Black;
-
- // Background color; default white
- public Color BackColor { get; set; } = Color.White;
-
- // Uniform padding around the barcode in points; default 5f
- public float Padding { get; set; } = 5f;
-
///
- /// Applies the stored settings to the specified instance.
+ /// Provides a static wrapper to configure the ProcessorSettings used by .
///
- /// The barcode generator to configure.
- public void Apply(BarcodeGenerator generator)
+ public static class ProcessorSettingsWrapper
{
- if (generator == null) throw new ArgumentNullException(nameof(generator));
-
- // Set the text to encode (fallback to empty string if null)
- generator.CodeText = CodeText ?? string.Empty;
-
- // Configure X‑dimension (module size)
- generator.Parameters.Barcode.XDimension.Point = XDimension;
-
- // Handle auto‑size mode and bar height
- if (AutoSize)
+ ///
+ /// Configures the maximum degree of parallelism for barcode processing if the underlying setting is available.
+ ///
+ /// The desired maximum number of parallel threads.
+ public static void Configure(int maxDegreeOfParallelism)
{
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Retrieve the static ProcessorSettings instance from BarCodeReader
+ var settings = BarCodeReader.ProcessorSettings;
+ if (settings == null)
+ {
+ Console.WriteLine("ProcessorSettings is null; cannot configure.");
+ return;
+ }
+
+ // Attempt to set a property named MaxDegreeOfParallelism via reflection
+ var prop = settings.GetType().GetProperty("MaxDegreeOfParallelism");
+ if (prop != null && prop.CanWrite)
+ {
+ prop.SetValue(settings, maxDegreeOfParallelism);
+ Console.WriteLine($"ProcessorSettings: MaxDegreeOfParallelism set to {maxDegreeOfParallelism}.");
+ }
+ else
+ {
+ Console.WriteLine("ProcessorSettings does not expose a writable MaxDegreeOfParallelism property.");
+ }
}
- else
- {
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
- generator.Parameters.Barcode.BarHeight.Point = BarHeight;
- }
-
- // Apply foreground and background colors
- generator.Parameters.Barcode.BarColor = BarColor;
- generator.Parameters.BackColor = BackColor;
-
- // Apply uniform padding on all sides
- generator.Parameters.Barcode.Padding.Left.Point = Padding;
- generator.Parameters.Barcode.Padding.Top.Point = Padding;
- generator.Parameters.Barcode.Padding.Right.Point = Padding;
- generator.Parameters.Barcode.Padding.Bottom.Point = Padding;
}
-}
-class Program
-{
- ///
- /// Entry point demonstrating the use of with Aspose.BarCode.
- ///
- static void Main()
+ class Program
{
- // Create a reusable settings instance with desired configuration
- var settings = new ProcessorSettings
- {
- EncodeType = EncodeTypes.Code128,
- CodeText = "Sample123",
- XDimension = 2f,
- BarHeight = 50f,
- AutoSize = false,
- BarColor = Color.Blue,
- BackColor = Color.White,
- Padding = 4f
- };
-
- // Instantiate the generator using the specified symbology
- using (var generator = new BarcodeGenerator(settings.EncodeType))
+ ///
+ /// Entry point demonstrating barcode generation, reading, and processor settings configuration.
+ ///
+ /// Command-line arguments (not used).
+ static void Main(string[] args)
{
- // Apply the common configuration to the generator
- settings.Apply(generator);
-
- // Define output file path and save the barcode image as PNG
- const string outputPath = "barcode.png";
- generator.Save(outputPath);
-
- // Inform the user where the file was saved
- Console.WriteLine($"Barcode saved to {outputPath}");
+ // Configure processor settings to use 2 parallel threads
+ ProcessorSettingsWrapper.Configure(2);
+
+ // Define the output path for the generated barcode image
+ const string imagePath = "sample.png";
+
+ // Generate a simple Code128 barcode and save it to the specified file
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ generator.Save(imagePath);
+ Console.WriteLine($"Barcode image saved to '{imagePath}'.");
+ }
+
+ // Read the barcode back from the saved image using BarCodeReader
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
+ {
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Read CodeText: {result.CodeText}");
+ }
+ }
+
+ // Indicate that the demo has finished executing
+ Console.WriteLine("Demo completed.");
}
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/instantiate-australiapostsettings-and-assign-it-to-barcodereaderrecognitionsettings-for-custom-australia-post-decoding.cs b/special-barcode-recognition-settings/instantiate-australiapostsettings-and-assign-it-to-barcodereaderrecognitionsettings-for-custom-australia-post-decoding.cs
index 68b59c8..dadd4c0 100644
--- a/special-barcode-recognition-settings/instantiate-australiapostsettings-and-assign-it-to-barcodereaderrecognitionsettings-for-custom-australia-post-decoding.cs
+++ b/special-barcode-recognition-settings/instantiate-australiapostsettings-and-assign-it-to-barcodereaderrecognitionsettings-for-custom-australia-post-decoding.cs
@@ -1,8 +1,8 @@
-// Title: Custom Australia Post barcode decoding with Aspose.BarCode
-// Description: Demonstrates how to assign a custom AustraliaPostCustomerInformationDecoder to the BarCodeReader's RecognitionSettings for tailored decoding of Australia Post barcodes.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on customizing decoding behavior for specific symbologies. It showcases the use of BarCodeReader, AustraliaPostSettings, and the AustraliaPostCustomerInformationDecoder interface to implement custom logic, a common requirement when default decoding does not meet business needs. Developers can adapt this pattern for other symbologies requiring specialized post‑processing.
+// Title: Custom Australia Post Barcode Decoding with Aspose.BarCode
+// Description: Demonstrates how to configure AustraliaPostSettings on a BarCodeReader to use a custom customer information decoder for Australia Post barcodes.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on the Australia Post symbology. It showcases the use of BarcodeGenerator, BarCodeReader, and the RecognitionSettings hierarchy (AustraliaPostSettings) to customize decoding behavior. Developers working with postal services often need to interpret customer information fields, apply specific encoding tables, or plug in custom decoders; this snippet provides a clear pattern for those scenarios.
// Prompt: Instantiate AustraliaPostSettings and assign it to BarCodeReader.RecognitionSettings for custom Australia Post decoding.
-// Tags: australia post, barcode decoding, custom decoder, aspose.barcode, recognitionsettings
+// Tags: australia post, barcode, custom decoder, recognition, generation, aspose.barcode
using System;
using Aspose.BarCode;
@@ -10,56 +10,61 @@
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
-namespace AsposeBarcodeAustraliaPostDemo
+namespace AustraliaPostDemo
{
- // Custom decoder implementing the AustraliaPostCustomerInformationDecoder interface
- public class MyAustraliaPostDecoder : AustraliaPostCustomerInformationDecoder
+ ///
+ /// Custom decoder implementing the interface.
+ /// Returns the raw row data prefixed with a label for demonstration purposes.
+ ///
+ public class CustomAustraliaPostDecoder : AustraliaPostCustomerInformationDecoder
{
- // Simple implementation that returns a fixed string for demonstration
- public string Decode(string barValues)
+ ///
+ /// Decodes the supplied row data.
+ ///
+ /// The raw customer information row data extracted from the barcode.
+ /// A string containing a custom label followed by the original row data.
+ public string Decode(string rowData)
{
- // In a real scenario, decode the barValues according to custom logic
- return "CustomDecodedInfo";
+ return $"CustomDecoded:{rowData}";
}
}
- ///
- /// Demonstrates custom decoding of Australia Post barcodes using Aspose.BarCode.
- ///
class Program
{
///
- /// Entry point that generates a sample barcode, configures custom decoding, and outputs results.
+ /// Entry point of the example. Generates an Australia Post barcode, configures custom decoding settings,
+ /// and reads the barcode to display the detected type and text.
///
static void Main()
{
- // Generate a sample Australia Post barcode image
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678AB"))
+ // Sample Australia Post code text (FCC 59, 8‑digit DPID, 2 CTable chars)
+ const string codeText = "5912345678AB";
+
+ // Generate the barcode image using the Australia Post symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
{
- // Use CTable interpreting type for the customer information field
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable;
+ // Set the encoding table to CTable for the customer information field
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- // Create the barcode image
+ // Produce the bitmap image of the barcode
using (Bitmap barcodeImage = generator.GenerateBarCodeImage())
{
- // Initialize a reader for the generated image, specifying Australia Post decode type
+ // Create a reader for the generated image, specifying AustraliaPost as the decode type
using (var reader = new BarCodeReader(barcodeImage, DecodeType.AustraliaPost))
{
- // Access the AustraliaPost decoding settings
- AustraliaPostSettings auPostSettings = reader.BarcodeSettings.AustraliaPost;
-
- // Assign a custom decoder implementation
- auPostSettings.CustomerInformationDecoder = new MyAustraliaPostDecoder();
+ // Access the AustraliaPost decoding settings from the reader
+ var australiaPostSettings = reader.BarcodeSettings.AustraliaPost;
- // Ensure the interpreting type matches the generation settings
- auPostSettings.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
+ // Apply custom decoding parameters
+ australiaPostSettings.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
+ australiaPostSettings.IgnoreEndingFillingPatternsForCTable = true;
+ australiaPostSettings.CustomerInformationDecoder = new CustomAustraliaPostDecoder();
- // Perform barcode recognition and output results
+ // Perform recognition and output results
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected Type: {result.CodeType}");
- Console.WriteLine($"Code Text: {result.CodeText}");
- // The custom decoder does not affect CodeText directly; it would be used internally
+ Console.WriteLine($"Detected Type : {result.CodeTypeName}");
+ Console.WriteLine($"Detected Text : {result.CodeText}");
}
}
}
diff --git a/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-ctable-for-ctable-format-decoding-of-australia-post-barc.cs b/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-ctable-for-ctable-format-decoding-of-australia-post-barc.cs
index ba4fccd..6637977 100644
--- a/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-ctable-for-ctable-format-decoding-of-australia-post-barc.cs
+++ b/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-ctable-for-ctable-format-decoding-of-australia-post-barc.cs
@@ -1,48 +1,53 @@
-// Title: Decode Australia Post barcode using CTable format
-// Description: Demonstrates setting CustomerInformationInterpretingType to CTable for decoding Australia Post barcodes and prints the decoded values.
-// Category-Description: This example belongs to the Aspose.BarCode barcode decoding category, focusing on Australia Post symbology. It showcases the use of BarcodeGenerator, BarCodeReader, and related settings to generate and decode barcodes, a common task for developers handling postal services integration.
+// Title: Australia Post barcode generation and CTable decoding example
+// Description: Demonstrates generating an Australia Post barcode with customer information encoded using the CTable format and then decoding it back, interpreting the customer data as CTable.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader for decoding them. Typical use cases include printing Australia Post barcodes with custom customer information and later extracting that information programmatically. Developers often work with EncodeTypes, DecodeType, and specific settings such as AustralianPost.EncodingTable and AustraliaPost.CustomerInformationInterpretingType.
// Prompt: Set AustraliaPostSettings.CustomerInformationInterpretingType to CTable for CTable format decoding of Australia Post barcodes.
-// Tags: barcode symbology, australia post, decoding, ctable, aspose.barcode, generation, recognition
+// Tags: australia post, barcode, ctable, generation, recognition, aspose.barcode
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Program demonstrating generation and CTable decoding of an Australia Post barcode.
+/// Example program that generates an Australia Post barcode with CTable‑encoded customer information
+/// and then reads it back, interpreting the customer data as CTable.
///
class Program
{
///
- /// Entry point. Generates a barcode, decodes it using CTable interpreting type, and writes results to console.
+ /// Entry point. Generates the barcode, saves to a memory stream, and reads it back using Aspose.BarCode.
///
static void Main()
{
- // Sample Australia Post barcode text (postal code + customer info)
- const string codeText = "5912345678AB";
+ // Sample Australia Post code text:
+ // FCC = 59 (allows customer info), DPID = 12345678, 5 CTable characters "ABCDE"
+ string codeText = "5912345678ABCDE";
- // Initialize a barcode generator for Australia Post symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ // Generate the barcode with CTable encoding for customer information
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
{
- // Configure the generator to use CTable encoding for the customer information segment
+ // Set the encoding table to CTable for the generated barcode
generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- // Generate the barcode image in memory
- using (Bitmap image = generator.GenerateBarCodeImage())
+ // Save the generated barcode to a memory stream in PNG format
+ using (MemoryStream ms = new MemoryStream())
{
- // Create a barcode reader for the generated image, specifying Australia Post decoding
- using (var reader = new BarCodeReader(image, DecodeType.AustraliaPost))
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading
+
+ // Recognize the barcode from the memory stream
+ using (BarCodeReader reader = new BarCodeReader(ms, DecodeType.AustraliaPost))
{
- // Set the reader to interpret the customer information using CTable format
+ // Configure the reader to interpret customer information as CTable
reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
- // Iterate through all decoded barcode results
- foreach (var result in reader.ReadBarCodes())
+ // Read and output barcode information
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- Console.WriteLine("BarCode Type: " + result.CodeType);
- Console.WriteLine("BarCode CodeText: " + result.CodeText);
+ Console.WriteLine($"Code Type: {result.CodeType}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
}
}
}
diff --git a/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-ntable-for-ntable-format-decoding-of-australia-post-barc.cs b/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-ntable-for-ntable-format-decoding-of-australia-post-barc.cs
index 9dab69c..eda3277 100644
--- a/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-ntable-for-ntable-format-decoding-of-australia-post-barc.cs
+++ b/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-ntable-for-ntable-format-decoding-of-australia-post-barc.cs
@@ -1,62 +1,64 @@
-// Title: Decode Australia Post barcode using NTable format
-// Description: Demonstrates setting CustomerInformationInterpretingType to NTable for both generation and decoding of Australia Post barcodes.
-// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases how to configure the AustraliaPostSettings.CustomerInformationInterpretingType property for NTable format, a common requirement when working with Australia Post barcodes that include customer information. Developers often need to generate barcodes with specific encoding tables and then decode them accurately using matching settings.
-// Prompt: Set AustraliaPostSettings.CustomerInformationInterpretingType to NTable for NTable format decoding of Australia Post barcodes.
-// Tags: barcode symbology, australia post, ntable, generation, recognition, aspose.barcode
+// Title: Australia Post barcode generation and NTable decoding example
+// Description: Demonstrates how to generate an Australia Post barcode using the NTable encoding table and then decode it with NTable customer information interpretation.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing the use of BarcodeGenerator and BarCodeReader classes. It illustrates typical use cases such as creating barcodes for postal services and decoding them with specific settings, which developers often need when integrating mailing solutions.
+/// Prompt: Set AustraliaPostSettings.CustomerInformationInterpretingType to NTable for NTable format decoding of Australia Post barcodes.
+/// Tags: barcode symbology, australia post, encoding, decoding, png, barcodegenerator, barcodereader, aspose.barcode
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Example program that generates an Australia Post barcode using the NTable encoding
-/// and then decodes it with the same NTable interpreting type.
+/// Program demonstrating generation and recognition of an Australia Post barcode with NTable settings.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode image, verifies its creation,
- /// and reads the barcode back using NTable decoding settings.
+ /// Generates an Australia Post barcode with NTable encoding, saves it as PNG, and then reads it back using NTable decoding.
///
static void Main()
{
- // Sample Australia Post barcode text (FCC 59, DPID 8 digits, no customer info)
- string codeText = "5980123456";
+ // Define the output file path for the generated barcode image
+ string imagePath = "australia_post.png";
- // Output image path
- string imagePath = "AustraliaPost_NTable.png";
+ // Ensure a clean start by deleting any existing file with the same name
+ if (File.Exists(imagePath))
+ {
+ File.Delete(imagePath);
+ }
- // Generate the barcode with NTable encoding table
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ // -------------------- Barcode Generation --------------------
+ // Create a generator for an Australia Post barcode with the sample data
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678"))
{
- // Set the encoding table to NTable for generation
+ // Configure the generator to use the NTable encoding (digits only)
generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.NTable;
- // Save the barcode image to the specified path
- generator.Save(imagePath);
+ // Save the generated barcode as a PNG image
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // Verify that the image file was created successfully
+ // Verify that the barcode image was successfully created
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Failed to create barcode image at '{imagePath}'.");
+ Console.WriteLine("Failed to generate the barcode image.");
return;
}
- // Read and decode the barcode, setting the decoding interpreting type to NTable
- using (var reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost))
+ // -------------------- Barcode Recognition --------------------
+ // Initialize a reader for the saved image, specifying the Australia Post decode type
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost))
{
- // Apply NTable interpreting type for decoding
+ // Set the decoder to interpret customer information using the NTable format
reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.NTable;
- // Iterate through detected barcodes and output their details
+ // Iterate through all detected barcodes and output their details
foreach (BarCodeResult result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected Barcode Type: {result.CodeType}");
- Console.WriteLine($"Decoded CodeText: {result.CodeText}");
+ Console.WriteLine($"BarCode Type: {result.CodeType}");
+ Console.WriteLine($"BarCode CodeText: {result.CodeText}");
}
}
}
diff --git a/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-other-for-custom-decoding-of-australia-post-barcodes.cs b/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-other-for-custom-decoding-of-australia-post-barcodes.cs
index f2eaeb7..f456e4a 100644
--- a/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-other-for-custom-decoding-of-australia-post-barcodes.cs
+++ b/special-barcode-recognition-settings/set-australiapostsettingscustomerinformationinterpretingtype-to-other-for-custom-decoding-of-australia-post-barcodes.cs
@@ -1,56 +1,49 @@
-// Title: Custom decoding of Australia Post barcodes using Other interpreting type
-// Description: Demonstrates how to generate and read an Australia Post barcode with CustomerInformationInterpretingType set to Other, allowing custom handling of the customer information segment.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator, BarCodeReader, and AustraliaPostSettings to control encoding and decoding of Australia Post barcodes. Developers often need to customize how the customer information part of the barcode is interpreted, especially when integrating with proprietary systems.
+// Title: Custom Decoding of Australia Post Barcodes Using CustomerInformationInterpretingType
+// Description: Demonstrates how to generate an Australia Post barcode and decode it with a custom CustomerInformationInterpretingType setting.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader for decoding them, focusing on the Australia Post symbology. Developers often need to customize decoding behavior, such as interpreting customer information differently, and this snippet illustrates the required API calls.
// Prompt: Set AustraliaPostSettings.CustomerInformationInterpretingType to Other for custom decoding of Australia Post barcodes.
-// Tags: barcode symbology, australia post, encoding, decoding, png, aspose.barcode, aspose.barcode.generation, aspose.barcode.recognition
+// Tags: australia post, barcode symbology, custom decoding, png output, barcodegenerator, barcodereader
-using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Generates an Australia Post barcode with custom customer information interpretation
-/// and then reads it back using the same custom settings.
+/// Generates an Australia Post barcode, saves it as PNG, and then reads it back using a custom
+/// CustomerInformationInterpretingType setting. This demonstrates how to control decoding behavior
+/// for Australia Post barcodes with Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, saves it as PNG,
- /// verifies the file, and reads the barcode using the Other interpreting type.
+ /// Entry point of the example. Performs barcode generation, saves the image, and reads it back
+ /// with custom decoding settings.
///
static void Main()
{
- // Sample barcode text (customer information part can be empty for Other interpreting type)
- const string codeText = "59123456780123012301230123";
- const string imagePath = "AustraliaPost.png";
+ // Path for the generated barcode image
+ const string imagePath = "australiapost.png";
- // Generate Australia Post barcode with CustomerInformationInterpretingType set to Other
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ // -------------------- Generate Australia Post barcode --------------------
+ // Create a generator for the Australia Post symbology with a sample postal code.
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "1100000000"))
{
- // Configure the generator to treat the customer information segment as 'Other' (no built‑in interpretation)
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.Other;
+ // Set the interpreting type for the customer information to 'Other'.
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.Other;
- // Save the generated barcode image in PNG format
+ // Save the generated barcode as a PNG image.
generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // Verify that the image file was created successfully
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"Failed to create barcode image at '{imagePath}'.");
- return;
- }
-
- // Initialize a reader for Australia Post barcodes
+ // -------------------- Recognize the barcode with custom settings --------------------
+ // Initialize a reader for the saved image, specifying the Australia Post decode type.
using (var reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost))
{
- // Apply the same 'Other' interpreting type for decoding the customer information segment
+ // Apply the same interpreting type for decoding the customer information.
reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.Other;
- // Iterate through all recognized barcodes (should be one in this case)
+ // Iterate through all detected barcodes and output their type and text.
foreach (var result in reader.ReadBarCodes())
{
Console.WriteLine($"BarCode Type: {result.CodeType}");
diff --git a/special-barcode-recognition-settings/set-barcodereaderstripfnc-to-false-to-remove-fnc-symbols-from-decoded-results.cs b/special-barcode-recognition-settings/set-barcodereaderstripfnc-to-false-to-remove-fnc-symbols-from-decoded-results.cs
index 33fcc44..7af825f 100644
--- a/special-barcode-recognition-settings/set-barcodereaderstripfnc-to-false-to-remove-fnc-symbols-from-decoded-results.cs
+++ b/special-barcode-recognition-settings/set-barcodereaderstripfnc-to-false-to-remove-fnc-symbols-from-decoded-results.cs
@@ -1,64 +1,75 @@
-// Title: Strip FNC Characters from Barcode Decoding
-// Description: Demonstrates how to prevent stripping of FNC symbols when reading a GS1 Code128 barcode using Aspose.BarCode.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to generate a GS1 Code128 barcode containing FNC1 characters, save it as a PNG image, and read it back while configuring BarCodeReader.StripFNC to retain those symbols. Developers working with GS1 symbologies often need to preserve FNC characters for accurate data extraction, making this pattern common in inventory, logistics, and retail applications.
+// Title: BarCodeReader StripFNC Example
+// Description: Demonstrates how to disable stripping of FNC characters when reading a GS1 Code128 barcode using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It shows how to create a GS1 Code128 barcode with possible FNC symbols using BarcodeGenerator, save it as an image, and then read it back with BarCodeReader while configuring BarcodeSettings.StripFNC. Developers working with GS1 barcodes often need to preserve FNC characters for accurate data extraction, making this pattern common in inventory, logistics, and retail applications.
// Prompt: Set BarCodeReader.StripFNC to false to remove FNC symbols from decoded results.
-// Tags: gs1, code128, stripfnc, barcode decoding, aspose.barcode, image generation, png
+// Tags: barcode, gs1, code128, stripfnc, recognition, generation, aspose.barcode, c#
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Generates a GS1 Code128 barcode containing FNC1 characters, saves it as an image,
-/// and reads it back while preserving the FNC symbols in the decoded text.
+/// Example program that generates a GS1 Code128 barcode, saves it to disk,
+/// and reads it back with StripFNC disabled to retain any FNC characters in the result.
///
class Program
{
///
- /// Entry point of the example. Executes barcode generation, recognition, and cleanup.
+ /// Entry point of the example. Executes barcode generation, saves the image,
+ /// and performs recognition with StripFNC set to false.
///
static void Main()
{
- // Define the full path for the generated barcode image.
- string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "sample_barcode.png");
+ // Define temporary output directory and barcode image path
+ string outputDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeDemo");
+ string barcodePath = Path.Combine(outputDir, "barcode.png");
- // Create a GS1 Code128 barcode that includes FNC1 characters (represented by parentheses).
- using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, "(01)12345678901231(10)ABC123"))
+ // Ensure the output directory exists
+ if (!Directory.Exists(outputDir))
{
- // Save the barcode image to a PNG file.
- generator.Save(imagePath, BarCodeImageFormat.Png);
+ Directory.CreateDirectory(outputDir);
}
- // Verify that the image file was successfully created.
- if (!File.Exists(imagePath))
+ // Generate a GS1 Code128 barcode that may contain FNC characters
+ using (BarcodeGenerator generator = new BarcodeGenerator(
+ EncodeTypes.GS1Code128,
+ "(02)04006664241007(37)1(400)7019590754"))
{
- Console.WriteLine($"Failed to create barcode image at '{imagePath}'.");
+ // Save the generated barcode as a PNG image
+ generator.Save(barcodePath, BarCodeImageFormat.Png);
+ }
+
+ // Verify that the barcode image was successfully created
+ if (!File.Exists(barcodePath))
+ {
+ Console.WriteLine("Failed to create barcode image.");
return;
}
- // Initialize a barcode reader for Code128 and configure it to retain FNC characters.
- using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
+ // Read the barcode image and configure the reader to keep FNC characters
+ using (BarCodeReader reader = new BarCodeReader(barcodePath, DecodeType.Code128))
{
- // According to the task, set StripFNC to false (do not strip FNC characters).
+ // Disable stripping of FNC characters (set to false as requested)
reader.BarcodeSettings.StripFNC = false;
- // Iterate through all detected barcodes in the image.
- foreach (var result in reader.ReadBarCodes())
+ // Perform barcode recognition
+ BarCodeResult[] results = reader.ReadBarCodes();
+
+ // Output recognition results
+ if (results.Length == 0)
{
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Decoded Text: {result.CodeText}");
+ Console.WriteLine("No barcodes were detected.");
+ }
+ else
+ {
+ foreach (BarCodeResult result in results)
+ {
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text : {result.CodeText}");
+ }
}
- }
-
- // Optional cleanup: delete the generated image file.
- try
- {
- File.Delete(imagePath);
- }
- catch
- {
- // Suppress any exceptions that occur during cleanup.
}
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/set-barcodereaderstripfnc-to-true-to-retain-fnc-symbols-in-decoded-results.cs b/special-barcode-recognition-settings/set-barcodereaderstripfnc-to-true-to-retain-fnc-symbols-in-decoded-results.cs
index 4246ee6..79ff673 100644
--- a/special-barcode-recognition-settings/set-barcodereaderstripfnc-to-true-to-retain-fnc-symbols-in-decoded-results.cs
+++ b/special-barcode-recognition-settings/set-barcodereaderstripfnc-to-true-to-retain-fnc-symbols-in-decoded-results.cs
@@ -1,8 +1,8 @@
-// Title: Retain FNC Symbols Using BarCodeReader.StripFNC
-// Description: Demonstrates how to generate a GS1 Code128 barcode containing FNC characters, then read it with StripFNC set to true so the FNC symbols are kept in the decoded text.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader and BarcodeGenerator for handling GS1 Code128 symbology. It shows how to configure BarcodeSettings.StripFNC to control whether function characters (FNC) are stripped or retained during decoding—common when processing GS1 data streams that include application identifiers. Developers often need to preserve FNC symbols to maintain data integrity in supply‑chain and inventory systems.
+// Title: Retaining FNC Symbols in GS1-128 Barcode Decoding with Aspose.BarCode
+// Description: This example generates a GS1-128 barcode containing FNC characters, then reads it while preserving those FNC symbols in the decoded text.
+// Category-Description: Demonstrates Aspose.BarCode generation and recognition for GS1-128 symbology. It showcases the use of BarcodeGenerator to create barcodes and BarCodeReader to decode them, highlighting how to configure BarcodeSettings (StripFNC) to retain functional characters. Ideal for developers needing precise GS1 data handling, such as inventory or logistics applications.
// Prompt: Set BarCodeReader.StripFNC to true to retain FNC symbols in decoded results.
-// Tags: barcode symbology, gs1, code128, stripfnc, barcode generation, barcode recognition, aspose.barcode
+// Tags: gs1-128, fnc, barcode, encoding, decoding, aspose.barcode, barcodegenerator, barcodereader
using System;
using System.IO;
@@ -11,45 +11,44 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that generates a GS1 Code128 barcode containing FNC characters,
-/// then reads it back with StripFNC enabled to retain those characters in the result.
+/// Demonstrates how to retain FNC symbols when reading a GS1-128 barcode using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, saves it to disk,
- /// and reads it back while preserving FNC symbols.
+ /// Entry point of the example. Generates a barcode with FNC characters, saves it, and reads it back preserving FNC symbols.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Path where the barcode image will be saved
- string imagePath = "sample_barcode.png";
+ // Define the full path for the output barcode image.
+ string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png");
- // Generate a GS1 Code128 barcode that includes FNC characters (e.g., application identifiers)
- using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, "(02)04006664241007(37)1(400)7019590754"))
+ // Generate a GS1-128 barcode that includes FNC characters in its data string.
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.GS1Code128, "(02)04006664241007(37)1(400)7019590754"))
{
- // Save the generated barcode as a PNG file
- generator.Save(imagePath, BarCodeImageFormat.Png);
+ // Save the generated barcode image to the specified path.
+ generator.Save(imagePath);
}
- // Ensure the barcode image was successfully created before attempting to read it
+ // Verify that the barcode image was successfully created.
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Failed to create barcode image at '{imagePath}'.");
+ Console.WriteLine("Failed to create the barcode image.");
return;
}
- // Initialize a reader for Code128 barcodes and configure it to retain FNC symbols
- using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
+ // Initialize a reader for the saved image, specifying the GS1-128 decode type.
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.GS1Code128))
{
- // Set StripFNC to true so function characters are NOT stripped from the decoded text
+ // Configure the reader to retain FNC symbols in the decoded result.
reader.BarcodeSettings.StripFNC = true;
- // Iterate through all detected barcodes in the image
+ // Iterate through all detected barcodes and output their type and decoded text.
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Decoded Text: {result.CodeText}");
+ Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
+ Console.WriteLine($"BarCode CodeText: {result.CodeText}");
}
}
}
diff --git a/special-barcode-recognition-settings/set-processorsettingsmaxadditionalallowedthreads-to-2-to-cap-extra-worker-threads-for-controlled-multithreading.cs b/special-barcode-recognition-settings/set-processorsettingsmaxadditionalallowedthreads-to-2-to-cap-extra-worker-threads-for-controlled-multithreading.cs
index cd787b1..45ecaa0 100644
--- a/special-barcode-recognition-settings/set-processorsettingsmaxadditionalallowedthreads-to-2-to-cap-extra-worker-threads-for-controlled-multithreading.cs
+++ b/special-barcode-recognition-settings/set-processorsettingsmaxadditionalallowedthreads-to-2-to-cap-extra-worker-threads-for-controlled-multithreading.cs
@@ -1,47 +1,47 @@
-// Title: Cap barcode processor threads and generate/read a Code128 barcode
-// Description: Demonstrates how to limit the number of additional worker threads used by Aspose.BarCode's processor, then creates a Code128 barcode image and reads it back.
-// Category-Description: This example belongs to the Aspose.BarCode multithreading and processing category. It shows how to configure ProcessorSettings (specifically MaxAdditionalAllowedThreads) to control resource usage, a common need when running barcode operations in parallel or in constrained environments. The sample also covers basic barcode generation (BarcodeGenerator) and recognition (BarCodeReader), typical tasks for developers integrating barcode functionality into .NET applications.
+// Title: Limit Additional Worker Threads for Barcode Processing
+// Description: Shows how to cap the number of extra worker threads used by Aspose.BarCode's processor settings and then reads barcodes from an image.
+// Category-Description: This example belongs to the Aspose.BarCode configuration and recognition category. It demonstrates using the static ProcessorSettings class to control multithreading resources, a common requirement when integrating barcode scanning into high‑throughput or resource‑constrained applications. Developers typically adjust ProcessorSettings to balance performance and CPU usage while using BarCodeReader for image‑based barcode detection.
// Prompt: Set ProcessorSettings.MaxAdditionalAllowedThreads to 2 to cap extra worker threads for controlled multithreading.
-// Tags: code128, generation, recognition, threading, aspose.barcode, processorsettings
+// Tags: barcode, multithreading, configuration, barcodereader, processorsettings, aspose.barcode
using System;
-using Aspose.BarCode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates setting a thread limit for the barcode processor, generating a Code128 barcode,
-/// and then reading the generated barcode using Aspose.BarCode APIs.
+/// Demonstrates setting a limit on additional worker threads for barcode processing
+/// and optionally reads barcodes from a sample image file.
///
class Program
{
///
- /// Entry point of the example. Configures thread limits, creates a barcode image,
- /// and reads the barcode back, outputting its type and text to the console.
+ /// Entry point of the example. Configures thread limits and performs barcode reading if a sample image is present.
///
static void Main()
{
- // Limit the number of additional worker threads the barcode processor may spawn.
+ // Set the maximum number of additional worker threads to 2.
BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = 2;
+ Console.WriteLine("ProcessorSettings.MaxAdditionalAllowedThreads set to " + BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads);
- // Define the output file path for the generated barcode image.
- const string imagePath = "sample.png";
+ // Path to a sample image that may contain barcodes.
+ string sampleImage = "sample.png";
- // Generate a Code128 barcode with the value "123456" and save it as a PNG file.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Check if the sample image exists before attempting to read.
+ if (System.IO.File.Exists(sampleImage))
{
- generator.Save(imagePath);
- }
-
- // Initialize a barcode reader for the saved image, specifying the expected symbology.
- using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
- {
- // Iterate through all detected barcodes (in this case, just one) and display details.
- foreach (var result in reader.ReadBarCodes())
+ // Initialize the barcode reader with the image file.
+ using (var reader = new BarCodeReader(sampleImage))
{
- Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Barcode Text: {result.CodeText}");
+ // Iterate through all detected barcodes and output their type and text.
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected barcode: Type={result.CodeTypeName}, Text={result.CodeText}");
+ }
}
}
+ else
+ {
+ // Inform the user that the sample image was not found.
+ Console.WriteLine($"Sample image '{sampleImage}' not found. Skipping barcode reading.");
+ }
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/set-processorsettingsuseonlythiscorescount-to-4-to-restrict-barcode-recognition-to-four-cpu-cores.cs b/special-barcode-recognition-settings/set-processorsettingsuseonlythiscorescount-to-4-to-restrict-barcode-recognition-to-four-cpu-cores.cs
index ac37f0b..6e34d72 100644
--- a/special-barcode-recognition-settings/set-processorsettingsuseonlythiscorescount-to-4-to-restrict-barcode-recognition-to-four-cpu-cores.cs
+++ b/special-barcode-recognition-settings/set-processorsettingsuseonlythiscorescount-to-4-to-restrict-barcode-recognition-to-four-cpu-cores.cs
@@ -1,62 +1,63 @@
-// Title: Restrict Barcode Recognition to Specific CPU Cores
-// Description: Demonstrates how to limit Aspose.BarCode recognition to a fixed number of CPU cores using ProcessorSettings.
-// Category-Description: This example belongs to the Aspose.BarCode recognition configuration category. It shows how to control multi‑core processing via the ProcessorSettings API, a common requirement when optimizing performance or managing resources in server environments. Developers often need to adjust core usage to balance throughput and CPU load when processing large batches of images.
+// Title: Restrict barcode recognition to a specific number of CPU cores
+// Description: Demonstrates how to limit Aspose.BarCode barcode recognition to four processor cores using ProcessorSettings.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, showcasing how to control multithreading behavior via the ProcessorSettings class. Developers often need to balance performance and resource usage when processing large batches of images; setting UseOnlyThisCoresCount allows precise core allocation. Typical use cases include server environments, CI pipelines, or desktop applications where CPU usage must be constrained.
// Prompt: Set ProcessorSettings.UseOnlyThisCoresCount to 4 to restrict barcode recognition to four CPU cores.
-// Tags: barcode symbology, recognition, multithreading, core count, aspose.barcode, processorsettings, qualitysettings
+// Tags: barcode symbology, recognition, multithreading, processor settings, core count, aspose.barcode, code128, image generation
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Example program that restricts barcode recognition to a specific number of CPU cores
-/// and demonstrates barcode generation and reading using Aspose.BarCode.
+/// Example program that generates a Code128 barcode, restricts recognition to four CPU cores,
+/// and reads the barcode back from the generated image.
///
class Program
{
///
/// Entry point of the application.
- /// Configures core usage, ensures a sample barcode image exists, and reads barcodes from it.
///
static void Main()
{
- // Restrict barcode recognition to four CPU cores
- BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 4;
-
- // Path to the barcode image file
+ // Define the file path for the sample barcode image.
string imagePath = "sample_barcode.png";
- // Generate a sample barcode image if it does not already exist
+ // Generate a simple barcode image if it does not already exist.
if (!File.Exists(imagePath))
{
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Save the generated barcode as a PNG file
- generator.Save(imagePath, BarCodeImageFormat.Png);
+ // Set visual appearance: black bars on a white background.
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+
+ // Save the generated barcode image to the specified file.
+ generator.Save(imagePath);
+ Console.WriteLine($"Barcode image created at: {Path.GetFullPath(imagePath)}");
}
}
- // Verify that the image file is present before attempting recognition
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"Image file not found: {imagePath}");
- return;
- }
+ // Restrict barcode recognition to use only 4 CPU cores.
+ BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 4;
+ Console.WriteLine($"ProcessorSettings.UseOnlyThisCoresCount set to {BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}");
- // Perform barcode recognition using the configured core count
- using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // Perform barcode recognition on the generated image.
+ if (File.Exists(imagePath))
{
- // Apply a high‑performance quality preset for faster processing
- reader.QualitySettings = QualitySettings.HighPerformance;
-
- // Iterate through all detected barcodes and output their details
- foreach (var result in reader.ReadBarCodes())
+ using (var reader = new BarCodeReader(imagePath))
{
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
- Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Detected Text: {result.CodeText}");
+ }
}
}
+ else
+ {
+ Console.WriteLine($"Image file not found: {imagePath}");
+ }
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-benchmark-comparing-decoding-speed-when-processorsettingsuseallcores-is-true-versus-false.cs b/special-barcode-recognition-settings/write-benchmark-comparing-decoding-speed-when-processorsettingsuseallcores-is-true-versus-false.cs
index dcbe639..a04b04d 100644
--- a/special-barcode-recognition-settings/write-benchmark-comparing-decoding-speed-when-processorsettingsuseallcores-is-true-versus-false.cs
+++ b/special-barcode-recognition-settings/write-benchmark-comparing-decoding-speed-when-processorsettingsuseallcores-is-true-versus-false.cs
@@ -1,99 +1,110 @@
-// Title: Benchmark decoding speed with and without multi‑core processing
-// Description: Demonstrates measuring the time required to decode a set of Code128 barcodes using Aspose.BarCode, comparing ProcessorSettings.UseAllCores true vs false.
-// Category-Description: This example belongs to the Aspose.BarCode decoding performance category. It shows how to generate barcodes, configure the BarCodeReader processor settings, and benchmark decoding using BarCodeReader and DecodeType. Developers often need to evaluate multi‑core decoding impact for bulk barcode processing scenarios.
+// Title: Barcode decoding speed benchmark using ProcessorSettings.UseAllCores
+// Description: Demonstrates how to measure the decoding performance of Code128 barcodes when Aspose.BarCode's ProcessorSettings.UseAllCores is enabled versus disabled.
+// Category-Description: This example belongs to the Aspose.BarCode performance tuning category, illustrating the use of BarCodeReader.ProcessorSettings to control multi‑core processing. Developers often need to benchmark decoding speed for different core utilization scenarios, especially when optimizing server‑side barcode processing pipelines. The sample shows image generation, configuration of UseAllCores and UseOnlyThisCoresCount, and timing of the decoding loop.
// Prompt: Write a benchmark comparing decoding speed when ProcessorSettings.UseAllCores is true versus false.
-// Tags: barcode symbology, decoding, performance, benchmark, code128, aspnet, aspose.barcode, processorsettings, useallcores
+// Tags: barcode, decoding, benchmark, processorsettings, useallcores, code128, aspose.barcode
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode.Common;
+using Aspose.Drawing;
///
-/// Provides a simple benchmark that compares barcode decoding speed when
-/// is enabled versus disabled.
+/// Provides a simple benchmark that compares barcode decoding speed with
+/// Aspose.BarCode's ProcessorSettings.UseAllCores enabled and disabled.
///
class Program
{
///
- /// Entry point of the benchmark application.
- /// Generates sample Code128 barcodes, runs two decoding measurements,
- /// and writes the elapsed times to the console.
+ /// Entry point that creates sample Code128 barcodes, runs the benchmark,
+ /// and outputs the elapsed time for each configuration.
///
static void Main()
{
- // --------------------------------------------------------------------
- // 1. Generate a collection of in‑memory barcode images (PNG format)
- // --------------------------------------------------------------------
- List barcodeStreams = new List();
- for (int i = 0; i < 5; i++)
+ // Prepare a temporary folder for sample barcode images
+ string tempFolder = Path.Combine(Path.GetTempPath(), "BarcodeBenchmark");
+ if (Directory.Exists(tempFolder))
+ Directory.Delete(tempFolder, true);
+ Directory.CreateDirectory(tempFolder);
+
+ // Generate sample barcode images
+ int sampleCount = 5;
+ List imagePaths = new List();
+ for (int i = 0; i < sampleCount; i++)
{
- // Create a Code128 barcode with distinct text for each iteration
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}"))
- {
- MemoryStream ms = new MemoryStream();
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream for later reading
- barcodeStreams.Add(ms);
- }
+ string text = $"Sample{i + 1}";
+ string filePath = Path.Combine(tempFolder, $"barcode_{i}.png");
+ GenerateBarcodeImage(text, filePath);
+ imagePaths.Add(filePath);
}
- // ---------------------------------------------------------------
- // 2. Measure decoding time with multi‑core processing enabled
- // ---------------------------------------------------------------
- BarCodeReader.ProcessorSettings.UseAllCores = true;
- double timeAllCores = MeasureDecodingTime(barcodeStreams);
+ // Benchmark with UseAllCores = true
+ long timeAllCores = BenchmarkDecoding(imagePaths, useAllCores: true);
+ Console.WriteLine($"Decoding with UseAllCores = true took {timeAllCores} ms");
- // ---------------------------------------------------------------
- // 3. Measure decoding time with single‑core processing
- // ---------------------------------------------------------------
+ // Benchmark with UseAllCores = false (use half of the cores)
BarCodeReader.ProcessorSettings.UseAllCores = false;
- double timeSingleCore = MeasureDecodingTime(barcodeStreams);
+ BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Math.Max(1, Environment.ProcessorCount / 2);
+ long timePartialCores = BenchmarkDecoding(imagePaths, useAllCores: false);
+ Console.WriteLine($"Decoding with UseAllCores = false took {timePartialCores} ms");
+
+ // Clean up temporary files
+ Directory.Delete(tempFolder, true);
+ }
+
+ // Generates a Code128 barcode image and saves it to the specified path
+ static void GenerateBarcodeImage(string codeText, string filePath)
+ {
+ // Resolve EncodeTypes.Code128 via reflection (EncodeTypes.TryParse does not exist)
+ var field = typeof(EncodeTypes).GetField("Code128");
+ if (field == null)
+ throw new ArgumentException("Encode type 'Code128' not found.");
- // ---------------------------------------------------------------
- // 4. Output benchmark results
- // ---------------------------------------------------------------
- Console.WriteLine($"Decoding time with UseAllCores = true : {timeAllCores} ms");
- Console.WriteLine($"Decoding time with UseAllCores = false: {timeSingleCore} ms");
+ BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
- // ---------------------------------------------------------------
- // 5. Release all memory streams
- // ---------------------------------------------------------------
- foreach (MemoryStream ms in barcodeStreams)
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
{
- ms.Dispose();
+ // Save as PNG
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
}
- ///
- /// Measures the total time required to decode a list of barcode image streams.
- ///
- /// The collection of barcode image streams to decode.
- /// Total elapsed time in milliseconds.
- private static double MeasureDecodingTime(List streams)
+ // Measures the time required to decode all images with the specified ProcessorSettings
+ static long BenchmarkDecoding(List imagePaths, bool useAllCores)
{
+ // Configure ProcessorSettings
+ BarCodeReader.ProcessorSettings.UseAllCores = useAllCores;
+ if (!useAllCores)
+ {
+ // Example: limit to half of the available cores
+ BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Math.Max(1, Environment.ProcessorCount / 2);
+ }
+
Stopwatch sw = Stopwatch.StartNew();
- foreach (MemoryStream ms in streams)
+ foreach (string path in imagePaths)
{
- // Ensure the stream is positioned at the beginning before each read
- ms.Position = 0;
+ if (!File.Exists(path))
+ continue; // Skip missing files gracefully
- // Initialize a reader that supports all barcode types
- using (BarCodeReader reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes))
+ using (var reader = new BarCodeReader(path, DecodeType.Code128))
{
- // Iterate through all detected barcodes (results are ignored)
- foreach (var result in reader.ReadBarCodes())
+ // Perform the decoding; results are not used further
+ var results = reader.ReadBarCodes();
+
+ // Iterate results to ensure full processing and avoid compiler optimizations
+ foreach (var result in results)
{
- // No additional processing required; iteration forces decoding
+ var _ = result.CodeText; // No-op access
}
}
}
sw.Stop();
- return sw.Elapsed.TotalMilliseconds;
+ return sw.ElapsedMilliseconds;
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-benchmark-comparing-performance-when-processorsettingsmaxadditionalallowedthreads-is-zero-single-thread-versus-gre.cs b/special-barcode-recognition-settings/write-benchmark-comparing-performance-when-processorsettingsmaxadditionalallowedthreads-is-zero-single-thread-versus-gre.cs
index 99f1a8a..8557a6a 100644
--- a/special-barcode-recognition-settings/write-benchmark-comparing-performance-when-processorsettingsmaxadditionalallowedthreads-is-zero-single-thread-versus-gre.cs
+++ b/special-barcode-recognition-settings/write-benchmark-comparing-performance-when-processorsettingsmaxadditionalallowedthreads-is-zero-single-thread-versus-gre.cs
@@ -1,87 +1,95 @@
-// Title: Benchmark ProcessorSettings.MaxAdditionalAllowedThreads performance
-// Description: Demonstrates measuring barcode recognition speed using single‑thread vs multi‑thread settings.
-// Category-Description: This example belongs to Aspose.BarCode performance tuning, showing how to configure BarCodeReader.ProcessorSettings for threading. It uses BarcodeGenerator to create sample Code128 barcodes and BarCodeReader to decode them, a common scenario when developers need to optimize bulk barcode processing in server or batch jobs.
+// Title: Benchmarking Barcode Recognition Threading Performance
+// Description: Demonstrates how to measure the execution time of Aspose.BarCode barcode recognition when using single‑threaded versus multi‑threaded processing.
+// Category-Description: This example belongs to the Aspose.BarCode performance tuning category. It shows how to configure BarCodeReader.ProcessorSettings, generate sample Code128 barcodes, and benchmark recognition using different MaxAdditionalAllowedThreads values. Developers often need to evaluate threading impact on barcode scanning workloads, especially when processing large image batches in server or desktop applications.
// Prompt: Write a benchmark comparing performance when ProcessorSettings.MaxAdditionalAllowedThreads is zero (single‑thread) versus greater than zero.
-// Tags: barcode, code128, performance, multithreading, aspnet, aspose.barcode, generation, recognition
+// Tags: barcode symbology, performance benchmark, threading, processor settings, aspose.barcode, code128, image generation, recognition
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates benchmarking barcode recognition with different thread settings.
+/// Provides a simple benchmark that compares single‑threaded and multi‑threaded barcode recognition
+/// using Aspose.BarCode's BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads setting.
///
class Program
{
///
- /// Entry point. Generates sample barcodes, runs single‑ and multi‑thread benchmarks, and outputs elapsed times.
+ /// Entry point of the benchmark application.
+ /// Generates sample barcode images, runs recognition with different threading settings,
+ /// and outputs the elapsed time for each configuration.
///
static void Main()
{
- const int sampleCount = 5;
- var barcodeStreams = new List();
-
- // Generate sample barcode images in memory
- for (int i = 0; i < sampleCount; i++)
+ // Prepare a temporary folder for barcode images
+ string folderPath = Path.Combine(Path.GetTempPath(), "AsposeBarcodeBenchmark");
+ if (!Directory.Exists(folderPath))
{
- var codeText = $"Sample{i}";
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
- {
- var ms = new MemoryStream();
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0;
- barcodeStreams.Add(ms);
- }
+ Directory.CreateDirectory(folderPath);
}
+ // Generate sample barcode images (5 items)
+ List imagePaths = GenerateSampleBarcodes(folderPath, 5);
+
// Benchmark with single‑thread (MaxAdditionalAllowedThreads = 0)
- long singleThreadTicks = RunBenchmark(barcodeStreams, 0);
- Console.WriteLine($"Single‑thread elapsed: {TimeSpan.FromTicks(singleThreadTicks).TotalMilliseconds} ms");
+ long singleThreadMs = RunRecognitionBenchmark(imagePaths, 0);
+ Console.WriteLine($"Single‑thread recognition time: {singleThreadMs} ms");
- // Benchmark with multi‑thread (MaxAdditionalAllowedThreads > 0)
- int additionalThreads = Math.Max(1, Environment.ProcessorCount - 1);
- long multiThreadTicks = RunBenchmark(barcodeStreams, additionalThreads);
- Console.WriteLine($"Multi‑thread (MaxAdditionalAllowedThreads={additionalThreads}) elapsed: {TimeSpan.FromTicks(multiThreadTicks).TotalMilliseconds} ms");
+ // Benchmark with multi‑thread (MaxAdditionalAllowedThreads = Environment.ProcessorCount)
+ long multiThreadMs = RunRecognitionBenchmark(imagePaths, Environment.ProcessorCount);
+ Console.WriteLine($"Multi‑thread recognition time (threads={Environment.ProcessorCount}): {multiThreadMs} ms");
+ }
- // Clean up streams
- foreach (var ms in barcodeStreams)
+ // Generates 'count' barcode PNG files and returns their full paths
+ private static List GenerateSampleBarcodes(string folder, int count)
+ {
+ var paths = new List();
+ for (int i = 1; i <= count; i++)
{
- ms.Dispose();
+ string codeText = $"Sample{i:D3}";
+ string filePath = Path.Combine(folder, $"barcode_{i}.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ {
+ // Save directly to PNG file
+ generator.Save(filePath);
+ }
+ paths.Add(filePath);
}
+ return paths;
}
- ///
- /// Runs the recognition benchmark on the provided streams using the specified thread count.
- ///
- /// Memory streams containing barcode images.
- /// Maximum additional threads allowed for processing.
- /// Elapsed ticks for the benchmark.
- static long RunBenchmark(List streams, int maxAdditionalThreads)
+ // Runs recognition on all provided images with the specified MaxAdditionalAllowedThreads
+ private static long RunRecognitionBenchmark(List imagePaths, int maxAdditionalThreads)
{
// Configure processor settings
BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = maxAdditionalThreads;
var stopwatch = Stopwatch.StartNew();
- foreach (var stream in streams)
+ foreach (string path in imagePaths)
{
- // Ensure the stream is positioned at the beginning for each read
- stream.Position = 0;
- using (var reader = new BarCodeReader(stream, DecodeType.Code128))
+ // Ensure the file exists before processing
+ if (!File.Exists(path))
+ continue;
+
+ using (var reader = new BarCodeReader(path, DecodeType.Code128))
{
- // Perform recognition
+ // Read all barcodes in the image (there is only one per image)
foreach (var result in reader.ReadBarCodes())
{
- // Access result to ensure processing (no output needed)
- var _ = result.CodeText;
+ // Access result properties to prevent compiler optimizations from removing the loop
+ string typeName = result.CodeTypeName;
+ string codeText = result.CodeText;
+ // Variables are intentionally unused; they demonstrate access to result data
}
}
}
stopwatch.Stop();
- return stopwatch.ElapsedTicks;
+ return stopwatch.ElapsedMilliseconds;
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-code-that-records-cpu-usage-statistics-while-processorsettingsuseallcores-processes-large-image-set.cs b/special-barcode-recognition-settings/write-code-that-records-cpu-usage-statistics-while-processorsettingsuseallcores-processes-large-image-set.cs
index 11e148e..a0ef16c 100644
--- a/special-barcode-recognition-settings/write-code-that-records-cpu-usage-statistics-while-processorsettingsuseallcores-processes-large-image-set.cs
+++ b/special-barcode-recognition-settings/write-code-that-records-cpu-usage-statistics-while-processorsettingsuseallcores-processes-large-image-set.cs
@@ -1,8 +1,8 @@
-// Title: CPU Usage Statistics while processing barcodes with multi‑core support
-// Description: Demonstrates recording CPU usage while reading a set of barcode images using ProcessorSettings.UseAllCores.
-// Category-Description: This example belongs to the Aspose.BarCode processing category, showcasing multi‑core barcode reading with BarCodeReader and ProcessorSettings. It illustrates generating barcode images, enabling parallel processing, and measuring performance metrics—common tasks for developers optimizing barcode recognition workloads.
+// Title: Record CPU Usage While Processing Barcodes with Multi-Core Support
+// Description: Demonstrates generating barcode images, enabling multi‑core processing, and measuring CPU time and wall‑clock duration during barcode recognition.
+// Category-Description: This example belongs to the Aspose.BarCode processing category, illustrating how to use BarCodeGenerator to create barcodes, BarCodeReader with ProcessorSettings.UseAllCores for parallel decoding, and .NET diagnostics to capture CPU usage. Developers working with bulk barcode image sets often need to optimize performance by leveraging all CPU cores and monitoring resource consumption. The sample shows typical use cases such as batch generation, multi‑threaded recognition, and performance reporting.
// Prompt: Write code that records CPU usage statistics while ProcessorSettings.UseAllCores processes a large image set.
-// Tags: barcode symbology, code128, cpu usage, multithreading, performance, aspose.barcode, generation, recognition
+// Tags: barcode generation, barcode recognition, multithreading, cpu usage, performance monitoring, aspose.barcode, code128, png
using System;
using System.IO;
@@ -10,119 +10,87 @@
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Example program that generates a set of Code128 barcodes, reads them using
-/// multi‑core processing, and records CPU usage statistics for the operation.
+/// Demonstrates generating sample Code128 barcodes, enabling multi‑core barcode
+/// recognition, and measuring CPU and elapsed time for processing a set of images.
///
class Program
{
///
- /// Entry point. Generates temporary barcode images, enables multi‑core reading,
- /// measures CPU and wall‑clock time, outputs results, and cleans up.
+ /// Entry point of the sample. Generates barcode images, processes them with
+ /// BarCodeReader using all CPU cores, and reports performance metrics.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // --------------------------------------------------------------------
- // Prepare a temporary folder for barcode images
- // --------------------------------------------------------------------
- string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodes");
- if (!Directory.Exists(tempFolder))
+ // Define a temporary folder for barcode images
+ string folderPath = Path.Combine(Path.GetTempPath(), "AsposeBarcodesSample");
+ if (!Directory.Exists(folderPath))
{
- Directory.CreateDirectory(tempFolder);
+ Directory.CreateDirectory(folderPath);
}
- // --------------------------------------------------------------------
- // Define sample data to encode and allocate array for image paths
- // --------------------------------------------------------------------
- string[] sampleTexts = new string[] { "ABC123", "DEF456", "GHI789", "JKL012", "MNO345" };
- string[] imagePaths = new string[sampleTexts.Length];
+ // Number of sample images (kept small for CI safety)
+ int sampleCount = 5;
- // --------------------------------------------------------------------
- // Generate barcode images using BarcodeGenerator
- // --------------------------------------------------------------------
- for (int i = 0; i < sampleTexts.Length; i++)
+ // Generate sample barcode images
+ for (int i = 0; i < sampleCount; i++)
{
- string filePath = Path.Combine(tempFolder, $"barcode_{i}.png");
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, sampleTexts[i]))
+ string filePath = Path.Combine(folderPath, $"barcode_{i}.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
- // Simple visual settings
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 100f;
- generator.Save(filePath);
+ generator.CodeText = $"Sample{i}";
+ // Optional: set colors using Aspose.Drawing
+ generator.Parameters.Barcode.BarColor = Color.Black;
+ generator.Parameters.BackColor = Color.White;
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
- imagePaths[i] = filePath;
}
- // --------------------------------------------------------------------
- // Enable multi‑core processing for barcode reading
- // --------------------------------------------------------------------
+ // Ensure the generated files exist
+ string[] imageFiles = Directory.GetFiles(folderPath, "*.png");
+ if (imageFiles.Length == 0)
+ {
+ Console.WriteLine("No barcode images found to process.");
+ return;
+ }
+
+ // Enable multi-core processing for BarCodeReader
BarCodeReader.ProcessorSettings.UseAllCores = true;
- // --------------------------------------------------------------------
- // Record CPU usage and wall‑clock time before processing
- // --------------------------------------------------------------------
+ // Record CPU usage and elapsed time
Process currentProcess = Process.GetCurrentProcess();
TimeSpan cpuStart = currentProcess.TotalProcessorTime;
- Stopwatch wallClock = Stopwatch.StartNew();
+ Stopwatch sw = Stopwatch.StartNew();
- // --------------------------------------------------------------------
- // Read each generated barcode image
- // --------------------------------------------------------------------
- foreach (string path in imagePaths)
+ // Process each image and read barcodes
+ foreach (string imagePath in imageFiles)
{
- if (!File.Exists(path))
+ using (var reader = new BarCodeReader())
{
- Console.WriteLine($"File not found: {path}");
- continue;
- }
-
- using (var reader = new BarCodeReader(path))
- {
- // Iterate through all detected barcodes in the image
+ // Set the image for recognition
+ reader.SetBarCodeImage(imagePath);
+ // Optionally set decode types (e.g., Code128)
+ reader.BarCodeReadType = DecodeType.Code128;
+ // Read barcodes
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"File: {Path.GetFileName(path)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
+ Console.WriteLine($"File: {Path.GetFileName(imagePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
}
}
}
- // --------------------------------------------------------------------
- // Stop timing and calculate CPU usage statistics
- // --------------------------------------------------------------------
- wallClock.Stop();
+ // Stop timing and calculate CPU usage
+ sw.Stop();
TimeSpan cpuEnd = currentProcess.TotalProcessorTime;
TimeSpan cpuUsed = cpuEnd - cpuStart;
- // --------------------------------------------------------------------
- // Output performance metrics
- // --------------------------------------------------------------------
+ // Output performance summary
Console.WriteLine();
- Console.WriteLine("CPU Usage Statistics:");
- Console.WriteLine($"Wall‑clock time: {wallClock.Elapsed.TotalSeconds:F2} seconds");
- Console.WriteLine($"CPU time used : {cpuUsed.TotalSeconds:F2} seconds");
- Console.WriteLine($"CPU usage ratio (CPU time / wall time): {(cpuUsed.TotalSeconds / wallClock.Elapsed.TotalSeconds):P2}");
-
- // --------------------------------------------------------------------
- // Clean up temporary barcode image files
- // --------------------------------------------------------------------
- foreach (string path in imagePaths)
- {
- try
- {
- File.Delete(path);
- }
- catch
- {
- // Ignore any deletion errors
- }
- }
-
- // --------------------------------------------------------------------
- // Reset processor settings (optional)
- // --------------------------------------------------------------------
- BarCodeReader.ProcessorSettings.UseAllCores = false;
+ Console.WriteLine("Processing completed.");
+ Console.WriteLine($"Elapsed wall-clock time: {sw.Elapsed.TotalSeconds:F2} seconds");
+ Console.WriteLine($"CPU time used: {cpuUsed.TotalSeconds:F2} seconds");
+ Console.WriteLine($"CPU usage ratio: {(cpuUsed.TotalSeconds / sw.Elapsed.TotalSeconds * 100):F2}%");
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-code-that-switches-australiapostsettingscustomerinformationinterpretingtype-at-runtime-based-on-user-selection.cs b/special-barcode-recognition-settings/write-code-that-switches-australiapostsettingscustomerinformationinterpretingtype-at-runtime-based-on-user-selection.cs
index 4f84af9..a45b074 100644
--- a/special-barcode-recognition-settings/write-code-that-switches-australiapostsettingscustomerinformationinterpretingtype-at-runtime-based-on-user-selection.cs
+++ b/special-barcode-recognition-settings/write-code-that-switches-australiapostsettingscustomerinformationinterpretingtype-at-runtime-based-on-user-selection.cs
@@ -1,64 +1,83 @@
-// Title: Switch AustraliaPost CustomerInformationInterpretingType at Runtime
-// Description: Demonstrates how to set the CustomerInformationInterpretingType for Australia Post barcodes based on a command‑line argument, then generate and read the barcode using the same setting.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to work with the AustraliaPostSettings class, specifically the CustomerInformationInterpretingType property, which controls how customer information is interpreted during encoding and decoding. Developers creating shipping labels or postal barcodes often need to switch this setting at runtime to match different postal service requirements.
+// Title: Dynamic AustraliaPost Customer Information Interpreting Type
+// Description: Demonstrates how to switch the AustraliaPostSettings.CustomerInformationInterpretingType at runtime based on a command‑line argument and generate/recognize the barcode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on Australia Post symbology. It shows usage of BarcodeGenerator, BarCodeReader, and the AustraliaPost settings such as EncodingTable and CustomerInformationInterpretingType. Developers often need to create or read Australia Post barcodes with different customer information tables (CTable, NTable, Other) depending on business rules.
// Prompt: Write code that switches AustraliaPostSettings.CustomerInformationInterpretingType at runtime based on user selection.
-// Tags: barcode symbology, australia post, runtime configuration, generation, recognition, aspose.barcode
+// Tags: barcode symbology, australia post, customer information, interpreting type, runtime selection, aspose.barcode, generation, recognition
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that switches AustraliaPostSettings.CustomerInformationInterpretingType at runtime,
-/// generates an Australia Post barcode, and then reads it back using the same interpreting type.
+/// Demonstrates runtime selection of Australia Post customer information interpreting type,
+/// barcode generation, and recognition using Aspose.BarCode.
///
class Program
{
///
- /// Entry point. Accepts an optional command‑line argument specifying the desired CustomerInformationInterpretingType.
+ /// Entry point. Parses a command‑line argument to choose the interpreting type,
+ /// builds a valid Australia Post codetext, and calls the generation/reading routine.
///
- /// Command‑line arguments; first argument should be a valid CustomerInformationInterpretingType value.
+ /// Command‑line arguments; first argument selects the interpreting type.
static void Main(string[] args)
{
- // Determine interpreting type from command‑line argument; default to Other if parsing fails.
- CustomerInformationInterpretingType interpretingType;
- if (args.Length > 0 && Enum.TryParse(args[0], true, out CustomerInformationInterpretingType parsed))
+ // Determine interpreting type from command‑line argument or default to CTable
+ string typeArg = args.Length > 0 ? args[0] : "CTable";
+ CustomerInformationInterpretingType interpretingType = typeArg switch
{
- interpretingType = parsed;
- }
- else
- {
- interpretingType = CustomerInformationInterpretingType.Other;
- }
+ "CTable" => CustomerInformationInterpretingType.CTable,
+ "NTable" => CustomerInformationInterpretingType.NTable,
+ "Other" => CustomerInformationInterpretingType.Other,
+ _ => CustomerInformationInterpretingType.CTable
+ };
- // Sample Australia Post code text (FCC=11, DPID=8 digits, no customer info).
- const string codeText = "1100000000";
-
- // Generate barcode with the selected interpreting type.
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ // Build a valid AustraliaPost codetext for the selected type
+ // FCC 59 allows up to 5 CTable chars or 10 NTable digits or 4 symbols (0‑3) for Other.
+ string fcc = "59";
+ string dpid = "01234567"; // 8‑digit DPID
+ string customerInfo = interpretingType switch
{
- // Apply the runtime interpreting type to the generator settings.
- generator.Parameters.Barcode.AustralianPost.EncodingTable = interpretingType;
+ CustomerInformationInterpretingType.CTable => "ABCD", // letters allowed, <=5 chars
+ CustomerInformationInterpretingType.NTable => "1234", // digits only
+ CustomerInformationInterpretingType.Other => "0123", // symbols 0‑3 only
+ _ => ""
+ };
+ string codeText = fcc + dpid + customerInfo;
+
+ string outputPath = "AustraliaPostBarcode.png";
- const string imagePath = "AustraliaPost.png";
+ GenerateAndReadBarcode(codeText, interpretingType, outputPath);
+ }
- // Save the generated barcode image to disk.
- generator.Save(imagePath);
- Console.WriteLine($"Barcode generated with CustomerInformationInterpretingType = {interpretingType}");
- Console.WriteLine($"Image saved to: {imagePath}");
+ static void GenerateAndReadBarcode(string codeText, CustomerInformationInterpretingType type, string outputPath)
+ {
+ // Generate barcode image with the specified interpreting type
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ {
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = type;
- // Recognize the barcode and apply the same interpreting type for decoding.
- using (var reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost))
+ using (MemoryStream ms = new MemoryStream())
{
- // Configure the reader to use the same interpreting type as the generator.
- reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = interpretingType;
+ // Save barcode as PNG into the memory stream
+ generator.Save(ms, BarCodeImageFormat.Png);
+ // Write the image to a file for visual verification (optional)
+ File.WriteAllBytes(outputPath, ms.ToArray());
- // Iterate through all detected barcodes (should be one) and output details.
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ // Reset stream position for reading
+ ms.Position = 0;
+
+ // Recognize the barcode using the same interpreting type
+ using (BarCodeReader reader = new BarCodeReader(ms, DecodeType.AustraliaPost))
{
- Console.WriteLine($"Decoded Type: {result.CodeType}");
- Console.WriteLine($"Decoded Text: {result.CodeText}");
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = type;
+
+ foreach (BarCodeResult result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Interpreting Type: {type}");
+ Console.WriteLine($"Decoded CodeText: {result.CodeText}");
+ }
}
}
}
diff --git a/special-barcode-recognition-settings/write-configuration-loader-that-reads-processorsettings-values-from-json-file-at-application-startup.cs b/special-barcode-recognition-settings/write-configuration-loader-that-reads-processorsettings-values-from-json-file-at-application-startup.cs
index 0eec269..29dfdd8 100644
--- a/special-barcode-recognition-settings/write-configuration-loader-that-reads-processorsettings-values-from-json-file-at-application-startup.cs
+++ b/special-barcode-recognition-settings/write-configuration-loader-that-reads-processorsettings-values-from-json-file-at-application-startup.cs
@@ -1,89 +1,98 @@
// Title: Load ProcessorSettings from JSON Configuration
// Description: Demonstrates loading Aspose.BarCode processor settings from a JSON file at application startup and applying them to the BarCodeReader.
-// Category-Description: This example belongs to the Aspose.BarCode configuration management category. It shows how to use the BarCodeReader.ProcessorSettings class to control multithreading behavior. Typical use cases include optimizing performance on multi‑core machines by toggling UseAllCores or limiting the number of cores. Developers often need to read such settings from external configuration files (e.g., JSON) to make the application adaptable without recompilation.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category. It shows how to use the BarCodeReader.ProcessorSettings class to control multithreading behavior based on a JSON configuration file. Typical use cases include optimizing barcode processing performance on different hardware environments. Developers often need to read settings from external files, deserialize them, and apply them to Aspose.BarCode APIs.
// Prompt: Write a configuration loader that reads ProcessorSettings values from a JSON file at application startup.
-// Tags: processor settings, configuration, json, aspose.barcode, barcodereader
+// Tags: json, configuration, processor settings, aspose.barcode, barcodereader, multithreading, cpu cores
using System;
using System.IO;
using System.Text.Json;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode.Common;
-///
-/// Represents the processor configuration that can be loaded from a JSON file.
-///
-class ProcessorConfig
-{
- // Indicates whether the BarCodeReader should use all available CPU cores.
- public bool UseAllCores { get; set; } = true;
-
- // Specifies the exact number of cores to use when UseAllCores is false.
- public int UseOnlyThisCoresCount { get; set; } = Environment.ProcessorCount;
-}
-
-///
-/// Entry point of the application that loads processor settings and applies them to Aspose.BarCode.
-///
-class Program
+namespace ProcessorSettingsLoader
{
///
- /// Application startup method. Loads configuration, applies settings, and reports the applied values.
+ /// Model matching the JSON structure for ProcessorSettings.
///
- static void Main()
+ public class ProcessorSettingsConfig
{
- const string configPath = "processorSettings.json";
-
- // Load configuration from JSON file (or use defaults if missing/invalid).
- ProcessorConfig config = LoadConfig(configPath);
-
- // Apply the loaded settings to the Aspose.BarCode processor.
- ApplyProcessorSettings(config);
-
- // Output the effective processor settings.
- Console.WriteLine(
- $"ProcessorSettings applied: UseAllCores={BarCodeReader.ProcessorSettings.UseAllCores}, " +
- $"UseOnlyThisCoresCount={BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}");
+ public bool UseAllCores { get; set; } = true;
+ public int UseOnlyThisCoresCount { get; set; } = 1;
+ public int MaxAdditionalAllowedThreads { get; set; } = 0;
}
///
- /// Reads the processor configuration from the specified JSON file.
+ /// Entry point that loads processor settings from a JSON file and applies them to Aspose.BarCode.
///
- /// Path to the JSON configuration file.
- /// A instance populated with values from the file or defaults.
- static ProcessorConfig LoadConfig(string path)
+ class Program
{
- if (!File.Exists(path))
+ ///
+ /// Application startup method. Creates a default configuration file if missing,
+ /// reads the JSON, deserializes it, and applies the values to BarCodeReader.ProcessorSettings.
+ ///
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Config file missing; fall back to default settings.
- return new ProcessorConfig();
- }
+ const string configFileName = "processorSettings.json";
- // Open the file for reading within a using block to ensure proper disposal.
- using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
- {
+ // Ensure a configuration file exists; create a default one if missing
+ if (!File.Exists(configFileName))
+ {
+ var defaultConfig = new ProcessorSettingsConfig
+ {
+ UseAllCores = true,
+ UseOnlyThisCoresCount = Math.Max(1, Environment.ProcessorCount / 2),
+ MaxAdditionalAllowedThreads = Environment.ProcessorCount
+ };
+
+ string defaultJson = JsonSerializer.Serialize(
+ defaultConfig,
+ new JsonSerializerOptions { WriteIndented = true });
+
+ File.WriteAllText(configFileName, defaultJson);
+ Console.WriteLine($"Created default configuration file '{configFileName}'.");
+ }
+
+ // Load configuration from JSON
+ ProcessorSettingsConfig config;
try
{
- // Deserialize JSON into ProcessorConfig; handle null result gracefully.
- ProcessorConfig? cfg = JsonSerializer.Deserialize(stream);
- return cfg ?? new ProcessorConfig();
+ using (var reader = new StreamReader(configFileName))
+ {
+ string json = reader.ReadToEnd();
+ config = JsonSerializer.Deserialize(json);
+ }
+
+ if (config == null)
+ {
+ throw new InvalidOperationException("Deserialized configuration is null.");
+ }
}
- catch (JsonException ex)
+ catch (Exception ex)
{
- // Invalid JSON format; log the error and use default settings.
- Console.WriteLine($"Error parsing config: {ex.Message}");
- return new ProcessorConfig();
+ Console.WriteLine($"Failed to load configuration: {ex.Message}");
+ return;
}
- }
- }
- ///
- /// Applies the provided processor configuration to the Aspose.BarCode BarCodeReader.
- ///
- /// The configuration to apply.
- static void ApplyProcessorSettings(ProcessorConfig config)
- {
- // Transfer settings to the static ProcessorSettings used by BarCodeReader.
- BarCodeReader.ProcessorSettings.UseAllCores = config.UseAllCores;
- BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = config.UseOnlyThisCoresCount;
+ // Apply settings to Aspose.BarCode ProcessorSettings
+ try
+ {
+ BarCodeReader.ProcessorSettings.UseAllCores = config.UseAllCores;
+ BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = config.UseOnlyThisCoresCount;
+ BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = config.MaxAdditionalAllowedThreads;
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to apply processor settings: {ex.Message}");
+ return;
+ }
+
+ // Output the applied settings for verification
+ Console.WriteLine("ProcessorSettings applied:");
+ Console.WriteLine($" UseAllCores = {BarCodeReader.ProcessorSettings.UseAllCores}");
+ Console.WriteLine($" UseOnlyThisCoresCount = {BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}");
+ Console.WriteLine($" MaxAdditionalAllowedThreads = {BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads}");
+ }
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-helper-method-that-configures-threadpoolsetminthreads-based-on-number-of-barcode-files-to-process.cs b/special-barcode-recognition-settings/write-helper-method-that-configures-threadpoolsetminthreads-based-on-number-of-barcode-files-to-process.cs
index bd582f7..2e42412 100644
--- a/special-barcode-recognition-settings/write-helper-method-that-configures-threadpoolsetminthreads-based-on-number-of-barcode-files-to-process.cs
+++ b/special-barcode-recognition-settings/write-helper-method-that-configures-threadpoolsetminthreads-based-on-number-of-barcode-files-to-process.cs
@@ -1,99 +1,62 @@
-// Title: Demonstrates barcode generation, reading, and ThreadPool configuration
-// Description: Generates sample Code128 barcodes, reads them, and adjusts ThreadPool minimum threads based on file count.
-// Category-Description: This example belongs to Aspose.BarCode usage for barcode generation and recognition, showcasing how to work with BarcodeGenerator, BarCodeReader, and ThreadPool settings. Developers often need to process multiple barcode images efficiently, requiring proper thread pool tuning to improve throughput in batch operations.
+// Title: Generate Sample Barcodes and Configure ThreadPool Minimum Threads
+// Description: This example creates a set of Code128 barcode PNG images using Aspose.BarCode and then adjusts the .NET ThreadPool minimum worker threads based on the number of generated files.
+// Category-Description: Demonstrates basic Aspose.BarCode generation combined with .NET ThreadPool tuning. It showcases the BarcodeGenerator class, EncodeTypes enumeration, and common file I/O patterns. Developers working on bulk barcode creation or processing pipelines often need to balance thread resources; this snippet illustrates how to calculate and set appropriate minimum threads for improved concurrency.
// Prompt: Write a helper method that configures ThreadPool.SetMinThreads based on the number of barcode files to process.
-// Tags: barcode symbology, generation, recognition, threadpool, multithreading, aspose.barcode, code128, png
+// Tags: barcode symbology, generation, threadpool, multithreading, aspose.barcode, png, code128
using System;
using System.IO;
using System.Threading;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Sample program demonstrating barcode generation, reading, and ThreadPool configuration.
+/// Demonstrates generating sample barcode images and configuring the ThreadPool minimum worker threads based on the file count.
///
class Program
{
///
- /// Entry point. Generates sample barcodes if needed, configures ThreadPool, and reads each barcode.
+ /// Entry point. Generates barcode PNG files, counts them, and configures the ThreadPool.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Directory to hold sample barcode images
- const string barcodeDir = "Barcodes";
+ // Prepare a folder for sample barcode images
+ string folder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ Directory.CreateDirectory(folder);
- // Ensure the directory exists and contains a few sample files
- if (!Directory.Exists(barcodeDir))
+ // Generate a few sample barcode files (default 5)
+ int sampleCount = 5;
+ for (int i = 1; i <= sampleCount; i++)
{
- Directory.CreateDirectory(barcodeDir);
- GenerateSampleBarcodes(barcodeDir, 5);
- }
-
- // Retrieve all PNG files in the directory
- string[] barcodeFiles = Directory.GetFiles(barcodeDir, "*.png");
- Console.WriteLine($"Found {barcodeFiles.Length} barcode file(s) to process.");
-
- // Configure ThreadPool based on the number of files to process
- ConfigureThreadPool(barcodeFiles.Length);
-
- // Process each barcode file: read and output its type and text
- foreach (string filePath in barcodeFiles)
- {
- using (var reader = new BarCodeReader(filePath))
+ string filePath = Path.Combine(folder, $"barcode_{i}.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}"))
{
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"File: {Path.GetFileName(filePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
- }
+ // Save each barcode as a PNG image
+ generator.Save(filePath);
}
}
- // Program ends here; no waiting for user input.
- }
-
- // Generates a given number of sample Code128 barcode images.
- private static void GenerateSampleBarcodes(string directory, int count)
- {
- if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
+ // Count the generated barcode files
+ string[] files = Directory.GetFiles(folder, "*.png");
+ int barcodeFileCount = files.Length;
+ Console.WriteLine($"Found {barcodeFileCount} barcode files in '{folder}'.");
- for (int i = 1; i <= count; i++)
- {
- string fileName = Path.Combine(directory, $"sample_{i}.png");
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}"))
- {
- // Optional: set a modest image size
- generator.Parameters.ImageWidth.Point = 200f;
- generator.Parameters.ImageHeight.Point = 100f;
- generator.Save(fileName, BarCodeImageFormat.Png);
- }
- }
+ // Configure ThreadPool based on the number of files
+ ConfigureThreadPool(barcodeFileCount);
}
- // Adjusts the ThreadPool's minimum worker threads based on workload size.
- private static void ConfigureThreadPool(int fileCount)
+ // Helper method that sets ThreadPool minimum worker threads
+ static void ConfigureThreadPool(int barcodeFileCount)
{
- if (fileCount < 0) throw new ArgumentOutOfRangeException(nameof(fileCount));
+ // Retrieve current minimum thread settings
+ ThreadPool.GetMinThreads(out int workerThreads, out int completionPortThreads);
- // Retrieve current minimum thread settings.
- ThreadPool.GetMinThreads(out int currentWorkerMin, out int currentCompletionPortMin);
+ // Desired worker threads: at least the number of files and at least 2 * processor count
+ int desiredWorkerThreads = Math.Max(workerThreads, Math.Max(barcodeFileCount, Environment.ProcessorCount * 2));
- // Determine a reasonable minimum: at least the current setting,
- // the number of files, and twice the processor count.
- int desiredWorkerMin = Math.Max(currentWorkerMin,
- Math.Max(fileCount, Environment.ProcessorCount * 2));
+ // Apply the new minimum thread settings
+ bool success = ThreadPool.SetMinThreads(desiredWorkerThreads, completionPortThreads);
- // Apply the new minimum; keep the completion port minimum unchanged.
- bool success = ThreadPool.SetMinThreads(desiredWorkerMin, currentCompletionPortMin);
- if (!success)
- {
- Console.WriteLine("Warning: Unable to set the desired minimum thread count.");
- }
- else
- {
- Console.WriteLine($"ThreadPool minimum worker threads set to {desiredWorkerMin}.");
- }
+ Console.WriteLine($"ThreadPool minimum worker threads set to {desiredWorkerThreads} (success: {success}).");
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-script-that-generates-synthetic-barcode-images-containing-embedded-fnc-symbols-for-testing-stripfnc-behavior.cs b/special-barcode-recognition-settings/write-script-that-generates-synthetic-barcode-images-containing-embedded-fnc-symbols-for-testing-stripfnc-behavior.cs
index 233b03f..bc39927 100644
--- a/special-barcode-recognition-settings/write-script-that-generates-synthetic-barcode-images-containing-embedded-fnc-symbols-for-testing-stripfnc-behavior.cs
+++ b/special-barcode-recognition-settings/write-script-that-generates-synthetic-barcode-images-containing-embedded-fnc-symbols-for-testing-stripfnc-behavior.cs
@@ -1,99 +1,111 @@
-// Title: Generate GS1 Code128 barcode with embedded FNC symbols for StripFNC testing
-// Description: This example creates a PNG barcode image containing GS1 FNC symbols and demonstrates reading it with and without stripping those symbols.
-// Category-Description: Demonstrates Aspose.BarCode generation and recognition for GS1 Code128 symbology, focusing on the StripFNC setting. It uses BarcodeGenerator, BarCodeReader, and related parameter classes to control appearance and decoding behavior, a common need for developers testing barcode data preprocessing.
+// Title: Generate Barcodes with Embedded FNC Symbols and Test StripFNC Behavior
+// Description: Creates synthetic barcode images containing FNC symbols for GS1-128, PDF417, and QR code symbologies, then reads them with and without stripping FNC characters to demonstrate the StripFNC setting.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes with special function characters (FNC1, group separators) and BarCodeReader for decoding them while toggling the StripFNC option. Developers working with GS1, PDF417, or QR codes often need to test how embedded function characters are handled during scanning, making this pattern useful for unit tests and data validation pipelines.
// Prompt: Write a script that generates synthetic barcode images containing embedded FNC symbols for testing StripFNC behavior.
-// Tags: gs1code128, fnc, stripfnc, barcode generation, barcode recognition, png, aspose.barcode
+// Tags: barcode generation, barcode recognition, fnc symbols, stripfnc, gs1-128, pdf417, qr code, aspose.barcode, synthetic test images
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation; // for BarCodeImageFormat
+using Aspose.BarCode.Generation; // for QrExtCodetextBuilder
+using Aspose.BarCode.Generation; // for QREncodeMode
///
-/// Demonstrates how to generate a GS1 Code128 barcode containing FNC symbols
-/// and how to read it with and without stripping those symbols using Aspose.BarCode.
+/// Demonstrates how to generate barcodes that contain FNC symbols and how to read them
+/// with the StripFNC option enabled or disabled using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode image, then reads it twice:
- /// once with the default StripFNC behavior and once with StripFNC enabled.
+ /// Entry point of the example. Generates barcode images, then reads them to show
+ /// the effect of the StripFNC setting.
///
static void Main()
{
// --------------------------------------------------------------------
- // Prepare output directory
+ // Prepare output directory for generated barcode images
// --------------------------------------------------------------------
- string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output");
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
// --------------------------------------------------------------------
- // Define barcode parameters
+ // 1. Generate a GS1-128 barcode (FNC1 is inserted automatically for AI format)
// --------------------------------------------------------------------
- string filePath = Path.Combine(outputDir, "gs1code128.png");
- // Sample GS1 Code128 data containing FNC1 (parentheses) delimiters
- string codeText = "(02)04006664241007(37)1(400)7019590754";
+ string gs1Path = Path.Combine(outputDir, "gs1code128.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, "(02)04006664241007(37)1(400)7019590754"))
+ {
+ generator.Save(gs1Path, BarCodeImageFormat.Png);
+ }
// --------------------------------------------------------------------
- // Generate barcode with embedded FNC characters (GS1 Code128)
+ // 2. Generate a PDF417 barcode with Code128 emulation (FNC1 encoded as Group Separator \u001D)
// --------------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, codeText))
+ string pdf417Path = Path.Combine(outputDir, "pdf417.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "a\u001d1222322323"))
{
- // Basic appearance settings
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
-
- // Size settings
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
- generator.Parameters.Barcode.BarHeight.Point = 50f;
- generator.Parameters.Barcode.XDimension.Point = 2f;
-
- // Disable filled bars to keep thin lines
- generator.Parameters.Barcode.FilledBars = false;
-
- // Prevent exceptions on automatic correction of the code text
- generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
-
- // Human‑readable text styling (optional)
- generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial";
- generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f;
- generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center;
-
- // Save the generated barcode image as PNG
- generator.Save(filePath, BarCodeImageFormat.Png);
+ generator.Parameters.Barcode.Pdf417.IsCode128Emulation = true;
+ generator.Save(pdf417Path, BarCodeImageFormat.Png);
}
- Console.WriteLine($"Barcode image saved to: {filePath}");
-
// --------------------------------------------------------------------
- // Read barcode without stripping FNC characters (default behavior)
+ // 3. Generate a QR code using Extended mode with FNC1 in the first position
// --------------------------------------------------------------------
- using (var reader = new BarCodeReader(filePath, DecodeType.Code128))
+ string qrPath = Path.Combine(outputDir, "qr_fnc1.png");
+ var qrBuilder = new QrExtCodetextBuilder();
+ qrBuilder.AddFNC1FirstPosition(); // at first position
+ qrBuilder.AddPlainCodetext("12345"); // data segment
+ qrBuilder.AddFNC1GroupSeparator(); // group separator (GS)
+ qrBuilder.AddPlainCodetext("67890"); // second data segment
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR))
{
- Console.WriteLine("\nReading without StripFNC (default):");
- foreach (BarCodeResult result in reader.ReadBarCodes())
- {
- Console.WriteLine($"CodeText: {result.CodeText}");
- }
+ generator.CodeText = qrBuilder.GetExtendedCodetext();
+ generator.Parameters.Barcode.QR.EncodeMode = QREncodeMode.Extended;
+ generator.Parameters.Barcode.CodeTextParameters.TwoDDisplayText = "QR with FNC1";
+ generator.Save(qrPath, BarCodeImageFormat.Png);
}
// --------------------------------------------------------------------
- // Read barcode with StripFNC enabled
+ // Local function: reads a barcode image with StripFNC false and true,
+ // then prints the decoded CodeText values.
// --------------------------------------------------------------------
- using (var reader = new BarCodeReader(filePath, DecodeType.Code128))
+ void ReadAndDisplay(string imagePath, BaseDecodeType decodeType)
{
- // Enable stripping of FNC symbols during decoding
- reader.BarcodeSettings.StripFNC = true;
- Console.WriteLine("\nReading with StripFNC = true:");
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ Console.WriteLine($"Reading '{Path.GetFileName(imagePath)}' without stripping FNC:");
+ using (var reader = new BarCodeReader(imagePath, decodeType))
+ {
+ reader.BarcodeSettings.StripFNC = false;
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($" CodeText: {result.CodeText}");
+ }
+ }
+
+ Console.WriteLine($"Reading '{Path.GetFileName(imagePath)}' with StripFNC enabled:");
+ using (var reader = new BarCodeReader(imagePath, decodeType))
{
- Console.WriteLine($"CodeText: {result.CodeText}");
+ reader.BarcodeSettings.StripFNC = true;
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($" CodeText: {result.CodeText}");
+ }
}
+
+ Console.WriteLine();
}
+
+ // --------------------------------------------------------------------
+ // Execute reading tests for each generated barcode
+ // --------------------------------------------------------------------
+ ReadAndDisplay(gs1Path, DecodeType.GS1Code128);
+ ReadAndDisplay(pdf417Path, DecodeType.Pdf417);
+ ReadAndDisplay(qrPath, DecodeType.QR);
+
+ Console.WriteLine("Barcode generation and StripFNC testing completed.");
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-script-that-processes-list-of-image-paths-in-parallel-using-tpl-while-respecting-processorsettings-limits.cs b/special-barcode-recognition-settings/write-script-that-processes-list-of-image-paths-in-parallel-using-tpl-while-respecting-processorsettings-limits.cs
index a30e828..84dd1ea 100644
--- a/special-barcode-recognition-settings/write-script-that-processes-list-of-image-paths-in-parallel-using-tpl-while-respecting-processorsettings-limits.cs
+++ b/special-barcode-recognition-settings/write-script-that-processes-list-of-image-paths-in-parallel-using-tpl-while-respecting-processorsettings-limits.cs
@@ -1,104 +1,115 @@
-// Title: Parallel barcode recognition from multiple images
-// Description: Demonstrates how to read barcodes from a collection of image files concurrently using TPL while respecting the processor limit defined in Aspose.BarCode's ProcessorSettings.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the use of BarCodeReader to detect and extract barcode data from images. It illustrates typical scenarios such as batch processing of scanned documents or photos, where developers need to maximize throughput while honoring the library's MaxProcessorCount setting. The code leverages Parallel.ForEach and reflection to adapt to runtime configuration, a common pattern for high‑performance barcode processing pipelines.
+// Title: Parallel Barcode Image Processing with TPL and ProcessorSettings
+// Description: Demonstrates generating sample Code128 barcode images and reading them in parallel while limiting CPU usage via BarCodeReader.ProcessorSettings.
+// Category-Description: This example belongs to the Aspose.BarCode operations collection focusing on barcode generation, recognition, and performance tuning. It showcases key API classes such as BarcodeGenerator, BarCodeReader, and ProcessorSettings, illustrating typical scenarios where developers need to process large batches of barcode images efficiently using TPL while controlling resource consumption.
// Prompt: Write a script that processes a list of image paths in parallel using TPL while respecting ProcessorSettings limits.
-// Tags: barcode, recognition, parallel, tpl, aspose.barcode, barcodereader
+// Tags: code128, barcode-generation, barcode-recognition, parallel-processing, tpls, processorsettings, aspose-barcode
using System;
using System.IO;
-using System.Reflection;
+using System.Collections.Generic;
using System.Threading.Tasks;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that processes a list of image files in parallel,
-/// reading any barcodes they contain using Aspose.BarCode's .
-/// The degree of parallelism respects the library's ProcessorSettings.MaxProcessorCount if available.
+/// Sample program that generates barcode images, then reads them in parallel
+/// while respecting the ProcessorSettings limits to control CPU usage.
///
class Program
{
///
/// Entry point of the application.
+ /// Generates sample barcode images, configures parallel processing limits,
+ /// reads barcodes from the images in parallel, and cleans up temporary files.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Sample list of image paths (replace with actual paths as needed)
- string[] imagePaths = new string[]
- {
- "sample1.png",
- "sample2.png",
- "sample3.png",
- "sample4.png",
- "sample5.png"
- };
+ // --------------------------------------------------------------------
+ // Create a temporary folder for sample barcode images
+ // --------------------------------------------------------------------
+ string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeSample");
+ Directory.CreateDirectory(tempFolder);
- // Determine the maximum degree of parallelism.
- // Default to the number of logical processors; override if ProcessorSettings provides a limit.
- int maxDegree = Environment.ProcessorCount;
+ // --------------------------------------------------------------------
+ // Generate a few sample barcode images (Code128)
+ // --------------------------------------------------------------------
+ var sampleTexts = new[] { "ABC123", "XYZ789", "HELLO", "WORLD", "TEST01" };
+ var imagePaths = new List();
- // Use reflection to safely access BarCodeReader.ProcessorSettings.MaxProcessorCount.
- PropertyInfo procSettingsProp = typeof(BarCodeReader).GetProperty(
- "ProcessorSettings",
- BindingFlags.Static | BindingFlags.Public);
-
- if (procSettingsProp != null)
+ foreach (var text in sampleTexts)
{
- object procSettings = procSettingsProp.GetValue(null);
- if (procSettings != null)
+ string filePath = Path.Combine(tempFolder, $"{text}.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text))
{
- PropertyInfo maxProp = procSettings.GetType().GetProperty(
- "MaxProcessorCount",
- BindingFlags.Instance | BindingFlags.Public);
-
- if (maxProp != null && maxProp.PropertyType == typeof(int))
- {
- maxDegree = (int)maxProp.GetValue(procSettings);
- }
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
+ imagePaths.Add(filePath);
}
- // Configure ParallelOptions with the resolved degree of parallelism.
- var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = maxDegree };
+ // --------------------------------------------------------------------
+ // Configure ProcessorSettings to limit parallelism
+ // Use only half of the available cores (at least 1)
+ // --------------------------------------------------------------------
+ BarCodeReader.ProcessorSettings.UseAllCores = false;
+ BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Math.Max(1, Environment.ProcessorCount / 2);
+ BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = Environment.ProcessorCount;
- // Process each image path concurrently.
- Parallel.ForEach(imagePaths, parallelOptions, path =>
+ // --------------------------------------------------------------------
+ // Prepare ParallelOptions respecting the configured core count
+ // --------------------------------------------------------------------
+ var parallelOptions = new ParallelOptions
{
- // Verify that the file exists before attempting to read.
- if (!File.Exists(path))
+ MaxDegreeOfParallelism = BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount
+ };
+
+ Console.WriteLine($"Processing {imagePaths.Count} images using up to {parallelOptions.MaxDegreeOfParallelism} parallel tasks.");
+
+ // --------------------------------------------------------------------
+ // Process the list of image paths in parallel
+ // --------------------------------------------------------------------
+ Parallel.ForEach(imagePaths, parallelOptions, imagePath =>
+ {
+ if (!File.Exists(imagePath))
{
- Console.WriteLine($"File not found: {path}");
+ Console.WriteLine($"File not found: {imagePath}");
return;
}
try
{
- // Initialize BarCodeReader for the current image file.
- using (var reader = new BarCodeReader(path))
+ using (var reader = new BarCodeReader(imagePath))
{
- // Read all barcodes present in the image.
var results = reader.ReadBarCodes();
-
- // Output results or indicate that no barcodes were found.
- if (results == null || results.Length == 0)
+ if (results.Length == 0)
{
- Console.WriteLine($"No barcodes detected in: {path}");
+ Console.WriteLine($"No barcode detected in {Path.GetFileName(imagePath)}");
}
else
{
foreach (var result in results)
{
- Console.WriteLine($"File: {path}");
- Console.WriteLine($" Type: {result.CodeTypeName}");
- Console.WriteLine($" CodeText: {result.CodeText}");
+ Console.WriteLine($"File: {Path.GetFileName(imagePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
}
}
}
}
catch (Exception ex)
{
- // Log any exceptions that occur during processing of the current file.
- Console.WriteLine($"Error processing {path}: {ex.Message}");
+ Console.WriteLine($"Error processing {Path.GetFileName(imagePath)}: {ex.Message}");
}
});
+
+ // --------------------------------------------------------------------
+ // Cleanup: delete temporary files and folder
+ // --------------------------------------------------------------------
+ foreach (var path in imagePaths)
+ {
+ try { File.Delete(path); } catch { /* ignore */ }
+ }
+ try { Directory.Delete(tempFolder, true); } catch { /* ignore */ }
+
+ Console.WriteLine("Processing completed.");
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-script-that-resets-processorsettings-to-default-values-after-completing-multithreaded-barcode-job.cs b/special-barcode-recognition-settings/write-script-that-resets-processorsettings-to-default-values-after-completing-multithreaded-barcode-job.cs
index 574793b..ded42b3 100644
--- a/special-barcode-recognition-settings/write-script-that-resets-processorsettings-to-default-values-after-completing-multithreaded-barcode-job.cs
+++ b/special-barcode-recognition-settings/write-script-that-resets-processorsettings-to-default-values-after-completing-multithreaded-barcode-job.cs
@@ -1,99 +1,68 @@
-// Title: Reset ProcessorSettings after multithreaded barcode processing
-// Description: Demonstrates generating barcode images, configuring multithreaded recognition, and resetting ProcessorSettings to defaults.
-// Category-Description: This example belongs to the Aspose.BarCode multithreading and performance tuning category. It showcases key API classes such as BarcodeGenerator, BarCodeReader, and ProcessorSettings, illustrating typical use cases like batch barcode generation, parallel recognition, and proper cleanup of processor configurations. Developers often need to adjust these settings for optimal CPU utilization and then restore defaults to avoid side effects in subsequent operations.
+// Title: Multithreaded barcode generation, reading, and ProcessorSettings reset
+// Description: Demonstrates generating Code128 barcodes in parallel, reading them, and restoring Aspose.BarCode ProcessorSettings to default values after the job.
+// Category-Description: This example belongs to the Aspose.BarCode multithreading and performance tuning category. It showcases the use of BarCodeReader.ProcessorSettings to control CPU core utilization, BarcodeGenerator for creating barcodes, and BarCodeReader for decoding. Developers often need to maximize throughput for bulk barcode processing and then clean up settings to avoid side effects in subsequent operations.
// Prompt: Write a script that resets ProcessorSettings to default values after completing a multithreaded barcode job.
-// Tags: code128, generation, recognition, multithreading, png, barcodgenerator, barcodereader, processorsettings
+// Tags: code128, multithreading, png, processorsettings, barcodegenerator, barcodereader, aspose.barcode
using System;
using System.IO;
+using System.Threading.Tasks;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Example program that generates barcode images, configures multithreaded barcode recognition,
-/// and resets ProcessorSettings to their default values after processing.
+/// Demonstrates multithreaded barcode generation and reading, then resets processor settings.
///
class Program
{
///
- /// Entry point of the example. Executes barcode generation, multithreaded reading, and settings reset.
+ /// Entry point. Configures ProcessorSettings for parallel execution, runs barcode tasks, and restores defaults.
///
- static void Main()
+ static void Main(string[] args)
{
- // Prepare a temporary folder for barcode images
- string outputDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodes");
- if (!Directory.Exists(outputDir))
- {
- Directory.CreateDirectory(outputDir);
- }
-
- // Sample barcode texts to encode
- string[] texts = { "ABC123", "XYZ789", "HELLO", "WORLD", "TEST5" };
- string[] imagePaths = new string[texts.Length];
-
- // Generate barcode images using default settings
- for (int i = 0; i < texts.Length; i++)
- {
- string filePath = Path.Combine(outputDir, $"barcode_{i}.png");
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, texts[i]))
- {
- // Save the barcode as PNG
- generator.Save(filePath, BarCodeImageFormat.Png);
- }
- imagePaths[i] = filePath;
- }
-
- // Configure ProcessorSettings for a controlled multithreaded job
- BarCodeReader.ProcessorSettings.UseAllCores = false;
+ // Enable maximum multithreaded performance for the barcode job
+ BarCodeReader.ProcessorSettings.UseAllCores = true;
+ // Optionally limit cores (example: half of the available cores)
BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Math.Max(1, Environment.ProcessorCount / 2);
- BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = Environment.ProcessorCount * 2;
- Console.WriteLine("ProcessorSettings configured for multithreaded job:");
- Console.WriteLine($" UseAllCores = {BarCodeReader.ProcessorSettings.UseAllCores}");
- Console.WriteLine($" UseOnlyThisCoresCount = {BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}");
- Console.WriteLine($" MaxAdditionalAllowedThreads = {BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads}");
+ const int jobCount = 5; // safe sample size
+ Task[] tasks = new Task[jobCount];
- // Perform barcode reading using the configured ProcessorSettings
- foreach (string path in imagePaths)
+ for (int i = 0; i < jobCount; i++)
{
- if (!File.Exists(path))
+ int index = i; // capture loop variable for closure
+ tasks[i] = Task.Run(() =>
{
- Console.WriteLine($"File not found: {path}");
- continue;
- }
-
- using (BarCodeReader reader = new BarCodeReader(path, DecodeType.Code128))
- {
- // Iterate through all detected barcodes in the image
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ // Generate a simple Code128 barcode in memory
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"CODE{index:D3}"))
{
- Console.WriteLine($"Detected barcode: Type={result.CodeTypeName}, Text={result.CodeText}");
+ using (var ms = new MemoryStream())
+ {
+ // Save barcode image as PNG to the memory stream
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // rewind stream for reading
+
+ // Read the barcode back using a BarCodeReader
+ using (var reader = new BarCodeReader(ms, DecodeType.Code128))
+ {
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Task {index}: Detected CodeText = {result.CodeText}");
+ }
+ }
+ }
}
- }
+ });
}
+ // Wait for all barcode tasks to complete
+ Task.WaitAll(tasks);
+
// Reset ProcessorSettings to their default values
BarCodeReader.ProcessorSettings.UseAllCores = false;
BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 0;
- BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = 0;
- Console.WriteLine("ProcessorSettings have been reset to defaults:");
- Console.WriteLine($" UseAllCores = {BarCodeReader.ProcessorSettings.UseAllCores}");
- Console.WriteLine($" UseOnlyThisCoresCount = {BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}");
- Console.WriteLine($" MaxAdditionalAllowedThreads = {BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads}");
-
- // Cleanup generated files (optional)
- foreach (string path in imagePaths)
- {
- if (File.Exists(path))
- {
- File.Delete(path);
- }
- }
- if (Directory.Exists(outputDir))
- {
- Directory.Delete(outputDir, true);
- }
+ Console.WriteLine("ProcessorSettings have been reset to default values.");
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-test-confirming-processorsettingsuseallcores-respects-system-s-hyper-threading-configuration.cs b/special-barcode-recognition-settings/write-test-confirming-processorsettingsuseallcores-respects-system-s-hyper-threading-configuration.cs
index 381b7f1..a0b4e6e 100644
--- a/special-barcode-recognition-settings/write-test-confirming-processorsettingsuseallcores-respects-system-s-hyper-threading-configuration.cs
+++ b/special-barcode-recognition-settings/write-test-confirming-processorsettingsuseallcores-respects-system-s-hyper-threading-configuration.cs
@@ -1,72 +1,95 @@
-// Title: Demonstrate ProcessorSettings.UseAllCores with Code128 barcode
-// Description: Generates a Code128 barcode, saves it as PNG, then reads it using Aspose.BarCode while toggling the UseAllCores setting to show core utilization.
-// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, illustrating how to control multi‑core processing via ProcessorSettings. It showcases BarcodeGenerator for creating barcodes, BarCodeReader for decoding, and the ProcessorSettings API for managing CPU core usage—common tasks for developers optimizing performance in high‑throughput scanning scenarios.
+// Title: Demonstrate ProcessorSettings.UseAllCores with barcode recognition
+// Description: Shows how to generate a Code128 barcode, then read it while toggling ProcessorSettings.UseAllCores to observe core usage behavior.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It illustrates the use of BarcodeGenerator, BarCodeReader, and the ProcessorSettings class to control multithreading during barcode processing. Developers often need to optimize performance on multi‑core or hyper‑threaded systems, and this snippet demonstrates typical configuration patterns for such scenarios.
// Prompt: Write a test confirming ProcessorSettings.UseAllCores respects the system's hyper‑threading configuration.
-// Tags: code128, generation, recognition, png, barcodegenerator, barcodereader, processorsettings
+// Tags: barcode symbology, generation, recognition, processor settings, multithreading, csharp, aspose.barcode
using System;
+using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
+using Aspose.BarCode.Common;
///
-/// Example program that creates a Code128 barcode, saves it as an image,
-/// and demonstrates the effect of ProcessorSettings.UseAllCores on barcode reading performance.
+/// Example program that generates a Code128 barcode, then reads it using Aspose.BarCode
+/// while toggling ProcessorSettings.UseAllCores to demonstrate core usage behavior.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, verifies the file,
- /// and reads it twice: once with all CPU cores enabled and once with a limited core count.
+ /// Entry point. Generates a barcode image, runs recognition with different ProcessorSettings,
+ /// and outputs the found barcode counts.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Define the output path for the generated barcode image.
- string imagePath = "barcode.png";
+ // Create a temporary folder for the barcode image
+ string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeTest");
+ Directory.CreateDirectory(tempFolder);
+ string barcodePath = Path.Combine(tempFolder, "test.png");
- // Generate a simple Code128 barcode and save it to the specified file.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123"))
+ // Generate a simple Code128 barcode and save it to the temporary folder
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123"))
{
- generator.Save(imagePath);
+ generator.Save(barcodePath);
}
- // Verify that the image file was successfully created.
- if (!System.IO.File.Exists(imagePath))
+ // Verify that the barcode image was successfully created
+ if (!File.Exists(barcodePath))
{
Console.WriteLine("Failed to create barcode image.");
return;
}
- // Display the default ProcessorSettings.UseAllCores value.
- Console.WriteLine($"Default UseAllCores: {BarCodeReader.ProcessorSettings.UseAllCores}");
-
- // Enable the use of all processor cores for barcode reading.
+ // ------------------------------------------------------------
+ // Test 1: Enable UseAllCores to allow the reader to use all logical processors
+ // ------------------------------------------------------------
BarCodeReader.ProcessorSettings.UseAllCores = true;
- Console.WriteLine($"After setting UseAllCores = true: {BarCodeReader.ProcessorSettings.UseAllCores}");
+ Console.WriteLine($"ProcessorSettings.UseAllCores set to: {BarCodeReader.ProcessorSettings.UseAllCores}");
+ Console.WriteLine($"Logical processor count (including hyper‑threading): {Environment.ProcessorCount}");
- // Read the barcode using all available cores.
- using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
- {
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"[AllCores] Detected CodeText: {result.CodeText}");
- }
- }
+ int foundCountAllCores = ReadBarcodes(barcodePath);
+ Console.WriteLine($"FoundCount with UseAllCores=true: {foundCountAllCores}");
+ Console.WriteLine();
- // Disable UseAllCores and limit the number of cores used for processing.
+ // ------------------------------------------------------------
+ // Test 2: Disable UseAllCores and limit the number of cores used
+ // ------------------------------------------------------------
BarCodeReader.ProcessorSettings.UseAllCores = false;
- int limitedCores = Math.Max(1, Environment.ProcessorCount / 2);
- BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = limitedCores;
- Console.WriteLine($"After disabling UseAllCores: {BarCodeReader.ProcessorSettings.UseAllCores}");
- Console.WriteLine($"Limited cores count: {BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}");
+ BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Math.Max(1, Environment.ProcessorCount / 2);
+ Console.WriteLine($"ProcessorSettings.UseAllCores set to: {BarCodeReader.ProcessorSettings.UseAllCores}");
+ Console.WriteLine($"ProcessorSettings.UseOnlyThisCoresCount set to: {BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}");
+
+ int foundCountLimitedCores = ReadBarcodes(barcodePath);
+ Console.WriteLine($"FoundCount with limited cores: {foundCountLimitedCores}");
+
+ // Clean up temporary files and folder
+ try
+ {
+ File.Delete(barcodePath);
+ Directory.Delete(tempFolder);
+ }
+ catch
+ {
+ // Ignored - cleanup failure should not affect test result
+ }
+ }
- // Read the barcode again, this time using the limited core count.
- using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
+ ///
+ /// Reads barcodes from the specified image file and returns the number of barcodes found.
+ ///
+ /// Path to the image containing barcodes.
+ /// The count of detected barcodes.
+ static int ReadBarcodes(string imagePath)
+ {
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"[LimitedCores] Detected CodeText: {result.CodeText}");
- }
+ // Perform recognition
+ reader.ReadBarCodes();
+
+ // Return the count of detected barcodes
+ return reader.FoundCount;
}
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-test-confirming-processorsettingsuseonlythiscorescount-does-not-exceed-physical-core-count.cs b/special-barcode-recognition-settings/write-test-confirming-processorsettingsuseonlythiscorescount-does-not-exceed-physical-core-count.cs
index ca9f95a..9afe8af 100644
--- a/special-barcode-recognition-settings/write-test-confirming-processorsettingsuseonlythiscorescount-does-not-exceed-physical-core-count.cs
+++ b/special-barcode-recognition-settings/write-test-confirming-processorsettingsuseonlythiscorescount-does-not-exceed-physical-core-count.cs
@@ -1,45 +1,76 @@
// Title: Verify ProcessorSettings core count does not exceed physical cores
-// Description: Demonstrates how to test that Aspose.BarCode's ProcessorSettings.UseOnlyThisCoresCount is limited to the machine's physical core count.
-// Category-Description: This example belongs to the Aspose.BarCode performance tuning category, illustrating the use of BarCodeReader.ProcessorSettings to control multi‑core processing. Developers often need to limit CPU usage for barcode recognition tasks in server environments; the key API classes include BarCodeReader and its nested ProcessorSettings. Typical scenarios involve configuring core usage to balance performance and resource constraints.
+// Description: Demonstrates creating a barcode image, configuring Aspose.BarCode processor settings, and confirming that UseOnlyThisCoresCount is not set beyond the machine's physical core count.
+// Category-Description: This example belongs to the Aspose.BarCode processing configuration category, illustrating how to control multi‑core usage via BarCodeReader.ProcessorSettings. It shows typical use of EncodeTypes, BarcodeGenerator, BarCodeReader, and DecodeType for generating and reading barcodes while managing CPU resources—common tasks for developers optimizing performance in batch scanning or server environments.
// Prompt: Write a test confirming ProcessorSettings.UseOnlyThisCoresCount does not exceed the physical core count.
-// Tags: barcode, processor-settings, core-count, performance, aspose.barcode, test
+// Tags: barcode, code128, core count, processor settings, aspnet, aspnet-barcode, generation, recognition
using System;
+using System.IO;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode.Common;
///
-/// Example program that validates the configured core count for Aspose.BarCode's
-/// processor settings does not exceed the physical core count of the host machine.
+/// Example program that generates a barcode, configures processor settings,
+/// and validates that the core count setting does not exceed the physical core count.
///
class Program
{
///
- /// Entry point of the example. Retrieves the physical core count, configures
- /// to use that many cores, and
- /// verifies the configuration does not exceed the actual core count.
+ /// Entry point of the example. Generates a barcode image, sets processor core usage,
+ /// validates the configuration, and reads the barcode back.
///
static void Main()
{
- // Retrieve the number of logical processors reported by the runtime.
- // In most environments this corresponds to the physical core count.
- int physicalCoreCount = Environment.ProcessorCount;
+ // ------------------------------------------------------------
+ // 1. Generate a temporary barcode image (Code128) for testing.
+ // ------------------------------------------------------------
+ string tempPath = Path.Combine(Path.GetTempPath(), "sample_barcode.png");
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123"))
+ {
+ generator.Save(tempPath);
+ }
- // Disable automatic core selection and explicitly set the core count.
+ // ------------------------------------------------------------
+ // 2. Verify that the image file was successfully created.
+ // ------------------------------------------------------------
+ if (!File.Exists(tempPath))
+ {
+ Console.WriteLine("Failed to create barcode image.");
+ return;
+ }
+
+ // ------------------------------------------------------------
+ // 3. Configure processor settings for barcode reading.
+ // - Disable automatic use of all cores.
+ // - Attempt to use the maximum number of physical cores.
+ // ------------------------------------------------------------
BarCodeReader.ProcessorSettings.UseAllCores = false;
- BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = physicalCoreCount; // attempt to use all available cores
+ int physicalCores = Environment.ProcessorCount;
+ BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = physicalCores; // attempt to use maximum cores
- // Read back the configured core count for validation.
- int configuredCoreCount = BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount;
+ // ------------------------------------------------------------
+ // 4. Validate that the configured core count does not exceed the physical core count.
+ // ------------------------------------------------------------
+ if (BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount > physicalCores)
+ {
+ throw new InvalidOperationException("UseOnlyThisCoresCount exceeds the number of physical cores.");
+ }
- // Ensure the configured value does not exceed the actual core count.
- if (configuredCoreCount > physicalCoreCount)
+ // ------------------------------------------------------------
+ // 5. Perform a simple barcode read to demonstrate that the settings work.
+ // ------------------------------------------------------------
+ using (BarCodeReader reader = new BarCodeReader(tempPath, DecodeType.Code128))
{
- throw new InvalidOperationException(
- $"Configured core count ({configuredCoreCount}) exceeds physical core count ({physicalCoreCount}).");
+ foreach (BarCodeResult result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected barcode: {result.CodeText}");
+ }
}
- // Output success message; this line is safe for non‑interactive CI pipelines.
- Console.WriteLine($"Test passed: Configured core count ({configuredCoreCount}) is within the physical core count ({physicalCoreCount}).");
+ // ------------------------------------------------------------
+ // 6. Output the final verification result.
+ // ------------------------------------------------------------
+ Console.WriteLine($"ProcessorSettings.UseOnlyThisCoresCount = {BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}, Physical cores = {physicalCores}. Test passed.");
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-unit-test-confirming-ignoreendingfillingpatternsforctable-only-affects-decoding-when-customerinformationinterpreti.cs b/special-barcode-recognition-settings/write-unit-test-confirming-ignoreendingfillingpatternsforctable-only-affects-decoding-when-customerinformationinterpreti.cs
index ecb0c40..5f66af3 100644
--- a/special-barcode-recognition-settings/write-unit-test-confirming-ignoreendingfillingpatternsforctable-only-affects-decoding-when-customerinformationinterpreti.cs
+++ b/special-barcode-recognition-settings/write-unit-test-confirming-ignoreendingfillingpatternsforctable-only-affects-decoding-when-customerinformationinterpreti.cs
@@ -1,95 +1,79 @@
-// Title: Demonstrate effect of IgnoreEndingFillingPatternsForCTable on AustraliaPost barcode decoding
-// Description: Shows that the IgnoreEndingFillingPatternsForCTable flag only influences decoding when the CustomerInformationInterpretingType is set to CTable.
-// Category-Description: This example belongs to the Aspose.BarCode decoding configuration category. It illustrates how to configure the AustraliaPost barcode reader using the CustomerInformationInterpretingType enum (CTable/NTable) and the IgnoreEndingFillingPatternsForCTable property. Developers working with Australian Post barcodes often need to control ending filling pattern handling to obtain correct customer information during decoding. The sample uses BarcodeGenerator, BarCodeReader, and related settings classes.
+// Title: Demonstrate effect of IgnoreEndingFillingPatternsForCTable on Australia Post barcode decoding
+// Description: Shows how the IgnoreEndingFillingPatternsForCTable flag influences decoding of Australia Post barcodes when using CTable interpreting type.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on Australia Post symbology. It illustrates using BarcodeGenerator, BarCodeReader, and related settings such as CustomerInformationInterpretingType and IgnoreEndingFillingPatternsForCTable. Developers often need to control how trailing filler patterns are handled during decoding, especially when working with CTable customer information.
// Prompt: Write a unit test confirming IgnoreEndingFillingPatternsForCTable only affects decoding when CustomerInformationInterpretingType is CTable.
-// Tags: australiapost, barcode, decoding, ctable, ntable, ignoreendingfillingpatterns, aspose.barcode
+// Tags: australia post, barcode generation, barcode recognition, ctable, ntable, ignoreendingfillingpatterns, unit test, aspnet, aspose.barcode
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Example program that generates an AustraliaPost barcode and validates the impact of
-/// IgnoreEndingFillingPatternsForCTable on decoding for different CustomerInformationInterpretingType settings.
+/// Demonstrates the impact of the IgnoreEndingFillingPatternsForCTable flag on decoding
+/// Australia Post barcodes with different CustomerInformationInterpretingType settings.
///
class Program
{
///
- /// Entry point. Generates a barcode, decodes it under three scenarios and prints test results.
+ /// Entry point that generates an Australia Post barcode, decodes it under various
+ /// configurations, and prints verification results.
///
static void Main()
{
- // Sample code text containing the ending filling pattern "333"
- const string originalCodeText = "5912345678AB333";
+ // Sample code text for an Australia Post barcode
+ const string codeText = "5912345678AB";
- // Generate an AustraliaPost barcode image in memory
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, originalCodeText))
+ // Generate a barcode image using CTable interpreting type
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
{
- // Use CTable interpreting type for generation
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable;
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- using (var ms = new MemoryStream())
+ using (Bitmap barcodeImage = generator.GenerateBarCodeImage())
{
- // Save the barcode as PNG into the memory stream
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0;
+ // Decode with CTable interpreting type, flag set to false
+ string resultCFalse = Decode(barcodeImage, CustomerInformationInterpretingType.CTable, false);
+ // Decode with CTable interpreting type, flag set to true
+ string resultCTrue = Decode(barcodeImage, CustomerInformationInterpretingType.CTable, true);
- // ---------- Test 1: CTable with IgnoreEndingFillingPatternsForCTable = true ----------
- string decodedWithIgnore = DecodeBarcode(ms, CustomerInformationInterpretingType.CTable, true);
+ // Decode with NTable interpreting type, flag set to false
+ string resultNFalse = Decode(barcodeImage, CustomerInformationInterpretingType.NTable, false);
+ // Decode with NTable interpreting type, flag set to true
+ string resultNTrue = Decode(barcodeImage, CustomerInformationInterpretingType.NTable, true);
- // Reset stream for next read
- ms.Position = 0;
+ // Verify that the flag influences decoding only when interpreting type is CTable
+ bool cTableEffect = resultCFalse != resultCTrue; // should differ
+ bool nTableEffect = resultNFalse == resultNTrue; // should be the same
- // ---------- Test 2: CTable with IgnoreEndingFillingPatternsForCTable = false ----------
- string decodedWithoutIgnore = DecodeBarcode(ms, CustomerInformationInterpretingType.CTable, false);
+ Console.WriteLine($"CTable flag effect (should differ): {(cTableEffect ? "PASS" : "FAIL")}");
+ Console.WriteLine($"NTable flag effect (should be same): {(nTableEffect ? "PASS" : "FAIL")}");
- // Reset stream for next read
- ms.Position = 0;
-
- // ---------- Test 3: NTable with IgnoreEndingFillingPatternsForCTable = true ----------
- string decodedNTable = DecodeBarcode(ms, CustomerInformationInterpretingType.NTable, true);
-
- // Evaluate expectations
- bool test1Pass = decodedWithIgnore != decodedWithoutIgnore && decodedWithIgnore.EndsWith("z");
- bool test2Pass = decodedWithoutIgnore.EndsWith("333");
- bool test3Pass = decodedNTable == decodedWithoutIgnore; // property should have no effect for NTable
-
- // Output test results
- Console.WriteLine($"Test 1 (CTable + ignore): {(test1Pass ? "PASS" : "FAIL")} - Decoded: {decodedWithIgnore}");
- Console.WriteLine($"Test 2 (CTable + no ignore): {(test2Pass ? "PASS" : "FAIL")} - Decoded: {decodedWithoutIgnore}");
- Console.WriteLine($"Test 3 (NTable + ignore): {(test3Pass ? "PASS" : "FAIL")} - Decoded: {decodedNTable}");
+ // Optional: output decoded texts for manual inspection
+ Console.WriteLine($"CTable false: {resultCFalse ?? "null"}");
+ Console.WriteLine($"CTable true: {resultCTrue ?? "null"}");
+ Console.WriteLine($"NTable false: {resultNFalse ?? "null"}");
+ Console.WriteLine($"NTable true: {resultNTrue ?? "null"}");
}
}
}
- ///
- /// Decodes an AustraliaPost barcode from a stream using the specified interpreting type and ignore flag.
- ///
- /// Stream containing the barcode image.
- /// Customer information interpreting type (CTable or NTable).
- /// Whether to ignore ending filling patterns for CTable.
- /// The decoded code text, or an empty string if decoding fails.
- private static string DecodeBarcode(Stream imageStream, CustomerInformationInterpretingType interpretingType, bool ignoreEndingFillingPatterns)
+ // Helper method to decode a barcode image with specified settings
+ static string Decode(Bitmap image, CustomerInformationInterpretingType interpretingType, bool ignoreEnding)
{
- using (var reader = new BarCodeReader(imageStream, DecodeType.AustraliaPost))
+ using (BarCodeReader reader = new BarCodeReader(image, DecodeType.AustraliaPost))
{
// Set the interpreting type (CTable or NTable)
reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = interpretingType;
+ // Set whether to ignore ending filling patterns for CTable
+ reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = ignoreEnding;
- // Set the flag under test
- reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = ignoreEndingFillingPatterns;
-
- // Read barcodes and return the first result's CodeText
- foreach (var result in reader.ReadBarCodes())
+ BarCodeResult[] results = reader.ReadBarCodes();
+ if (results.Length > 0)
{
- return result.CodeText ?? string.Empty;
+ return results[0].CodeText;
}
+ return null;
}
-
- // Return empty string if no barcode was read
- return string.Empty;
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-unit-test-verifying-barcodereader-removes-fnc-symbols-when-stripfnc-is-false.cs b/special-barcode-recognition-settings/write-unit-test-verifying-barcodereader-removes-fnc-symbols-when-stripfnc-is-false.cs
index 7ebbd83..6c2ab5e 100644
--- a/special-barcode-recognition-settings/write-unit-test-verifying-barcodereader-removes-fnc-symbols-when-stripfnc-is-false.cs
+++ b/special-barcode-recognition-settings/write-unit-test-verifying-barcodereader-removes-fnc-symbols-when-stripfnc-is-false.cs
@@ -1,97 +1,75 @@
-// Title: Demonstrate StripFNC behavior in GS1 Code128 barcode reading
-// Description: Shows how BarCodeReader handles FNC characters when StripFNC is false versus true, using a GS1 Code128 sample.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader and BarcodeSettings to control FNC character stripping. Developers working with GS1 symbologies often need to preserve or remove FNC1 separators depending on downstream processing. The snippet demonstrates typical API usage for reading raw and stripped barcode data, useful for unit testing and integration scenarios.
+// Title: BarCodeReader StripFNC behavior verification example
+// Description: Demonstrates how to use Aspose.BarCode to read a GS1 Code128 barcode and verify the StripFNC setting retains or removes FNC symbols.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader and BarcodeGenerator for GS1 symbologies. It shows how to configure BarcodeSettings.StripFNC to control the handling of Function (FNC) characters, a common requirement when processing GS1 data streams. Developers often need to toggle this setting to preserve AI delimiters or produce clean numeric strings.
// Prompt: Write a unit test verifying BarCodeReader removes FNC symbols when StripFNC is false.
-// Tags: gs1code128, stripfnc, barcoderecognition, aspose.barcode, unit-test, fnc1
+// Tags: barcode, gs1code128, stripfnc, fnc-symbols, barcode-recognition, aspose.barcode, unit-test
using System;
+using System.IO;
using System.Linq;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Example program that reads a GS1 Code128 barcode and demonstrates the effect of the StripFNC setting.
+/// Contains the entry point and verification logic for testing the StripFNC behavior of BarCodeReader.
///
class Program
{
///
- /// Generates a barcode image in memory and reads it twice: once with StripFNC disabled (default) and once with it enabled,
- /// printing verification results to the console.
+ /// Application entry point. Executes the StripFNC verification routine.
///
static void Main()
{
- // Sample GS1 Code128 data containing multiple Application Identifier (AI) groups.
- string sourceCodeText = "(02)04006664241007(37)1(400)7019590754";
+ // Run the verification test
+ VerifyStripFncBehavior();
+ }
+
+ static void VerifyStripFncBehavior()
+ {
+ // GS1 Code128 barcode with FNC (parentheses represent AI delimiters)
+ const string originalCodeText = "(02)04006664241007(37)1(400)7019590754";
- // Create a barcode generator for GS1 Code128 and produce the image in memory.
- using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, sourceCodeText))
- using (Bitmap barcodeImage = generator.GenerateBarCodeImage())
+ // Generate the barcode image in memory
+ using (var ms = new MemoryStream())
{
- // ------------------------------------------------------------
- // Test case 1: StripFNC = false (default behavior)
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128))
+ using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, originalCodeText))
{
- // Explicitly ensure that FNC characters are NOT stripped.
- reader.BarcodeSettings.StripFNC = false;
-
- // Read the first barcode result from the image.
- BarCodeResult result = reader.ReadBarCodes().FirstOrDefault();
-
- // Verify that a result was obtained.
- if (result == null)
- {
- Console.WriteLine("Failed to read barcode with StripFNC = false.");
- return;
- }
+ generator.Save(ms, BarCodeImageFormat.Png);
+ }
- // Expected raw text includes FNC1 separators (ASCII 29, represented as \x1D).
- string expectedRaw = "\x1D04006664241007\x1D1\x1D7019590754";
+ // Ensure the stream is ready for reading
+ ms.Position = 0;
- // Compare the actual CodeText with the expected raw string.
- bool rawMatches = result.CodeText == expectedRaw;
- Console.WriteLine($"StripFNC = false => CodeText matches expected: {rawMatches}");
+ // Test 1: StripFNC = false (should retain the original text)
+ using (var reader = new BarCodeReader(ms, DecodeType.GS1Code128))
+ {
+ reader.BarcodeSettings.StripFNC = false;
+ var result = reader.ReadBarCodes().FirstOrDefault();
+ string readText = result?.CodeText ?? string.Empty;
- // Output detailed mismatch information if the comparison fails.
- if (!rawMatches)
- {
- Console.WriteLine($"Actual: [{result.CodeText}]");
- Console.WriteLine($"Expected: [{expectedRaw}]");
- }
+ bool pass = readText == originalCodeText;
+ Console.WriteLine(pass
+ ? "PASS: StripFNC = false retains FNC symbols."
+ : $"FAIL: StripFNC = false altered code text. Expected '{originalCodeText}', got '{readText}'.");
}
- // ------------------------------------------------------------
- // Test case 2: StripFNC = true
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128))
+ // Reset stream position for the second read
+ ms.Position = 0;
+
+ // Test 2: StripFNC = true (should remove the parentheses)
+ using (var reader = new BarCodeReader(ms, DecodeType.GS1Code128))
{
- // Enable stripping of FNC characters.
reader.BarcodeSettings.StripFNC = true;
+ var result = reader.ReadBarCodes().FirstOrDefault();
+ string readText = result?.CodeText ?? string.Empty;
- // Read the first barcode result from the image.
- BarCodeResult result = reader.ReadBarCodes().FirstOrDefault();
-
- // Verify that a result was obtained.
- if (result == null)
- {
- Console.WriteLine("Failed to read barcode with StripFNC = true.");
- return;
- }
-
- // Expected text after stripping FNC1 separators: concatenated data without delimiters.
- string expectedStripped = "0400666424100717019590754";
-
- // Compare the actual CodeText with the expected stripped string.
- bool strippedMatches = result.CodeText == expectedStripped;
- Console.WriteLine($"StripFNC = true => CodeText matches expected: {strippedMatches}");
-
- // Output detailed mismatch information if the comparison fails.
- if (!strippedMatches)
- {
- Console.WriteLine($"Actual: [{result.CodeText}]");
- Console.WriteLine($"Expected: [{expectedStripped}]");
- }
+ // Expected text without parentheses
+ string expectedStripped = originalCodeText.Replace("(", string.Empty).Replace(")", string.Empty);
+ bool pass = readText == expectedStripped;
+ Console.WriteLine(pass
+ ? "PASS: StripFNC = true correctly strips FNC symbols."
+ : $"FAIL: StripFNC = true did not strip correctly. Expected '{expectedStripped}', got '{readText}'.");
}
}
}
diff --git a/special-barcode-recognition-settings/write-unit-test-verifying-barcodereader-retains-fnc-symbols-when-stripfnc-is-true.cs b/special-barcode-recognition-settings/write-unit-test-verifying-barcodereader-retains-fnc-symbols-when-stripfnc-is-true.cs
index 090fd59..3584766 100644
--- a/special-barcode-recognition-settings/write-unit-test-verifying-barcodereader-retains-fnc-symbols-when-stripfnc-is-true.cs
+++ b/special-barcode-recognition-settings/write-unit-test-verifying-barcodereader-retains-fnc-symbols-when-stripfnc-is-true.cs
@@ -1,98 +1,108 @@
-// Title: Verify BarCodeReader retains FNC symbols when StripFNC is true
-// Description: Demonstrates a unit‑test‑style verification that the BarCodeReader keeps the FNC1 character when StripFNC is disabled and removes it when enabled.
-// Category-Description: This example belongs to the Aspose.BarCode barcode reading category, focusing on GS1‑128 symbology and the StripFNC setting. It showcases the use of BarcodeGenerator, BarCodeReader, and related settings to control FNC character handling—common tasks for developers integrating barcode validation or data extraction.
+// Title: Verify StripFNC behavior for QR codes with FNC1 symbols
+// Description: Demonstrates generating a QR code containing FNC1 characters, then reading it with and without stripping FNC symbols to confirm the StripFNC setting works.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing the use of BarcodeGenerator, QrExtCodetextBuilder, and BarCodeReader. It illustrates typical scenarios where developers need to preserve or remove function characters (FNC) in QR codes, such as GS1 data handling, and how to validate the StripFNC property during decoding.
// Prompt: Write a unit test verifying BarCodeReader retains FNC symbols when StripFNC is true.
-// Tags: barcode symbology, gs1-128, stripfnc, unit test, aspose.barcode, generation, recognition
+// Tags: qr, fnc1, stripfnc, barcode generation, barcode recognition, aspose.barcode, unit test
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Contains the example that validates the StripFNC behavior of for GS1‑128 barcodes.
+/// Demonstrates generating a QR code with FNC1 characters and verifying the StripFNC setting of BarCodeReader.
///
class Program
{
///
- /// Generates a GS1‑128 barcode, reads it twice (with StripFNC disabled and enabled),
- /// and verifies that the FNC1 character is retained or removed as expected.
+ /// Entry point that creates a QR barcode, reads it with different StripFNC settings, and validates the results.
///
static void Main()
{
- // Sample GS1‑128 code text containing Application Identifier (AI) sections.
- const string sampleCodeText = "(02)04006664241007(37)1(400)7019590754";
+ // Prepare a temporary folder and file path for the barcode image
+ string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeTest");
+ Directory.CreateDirectory(tempFolder);
+ string barcodePath = Path.Combine(tempFolder, "qr_fnc.png");
- // Generate the barcode image into a memory stream to avoid file I/O.
- using (var imageStream = new MemoryStream())
- {
- // Create a generator for GS1‑128 and save the image as PNG.
- using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, sampleCodeText))
- {
- generator.Save(imageStream, BarCodeImageFormat.Png);
- }
-
- // Reset the stream position so it can be read from the beginning.
- imageStream.Position = 0;
+ // Build QR code text containing FNC1 characters using the builder
+ QrExtCodetextBuilder builder = new QrExtCodetextBuilder();
+ builder.AddFNC1FirstPosition(); // FNC1 at first position
+ builder.AddPlainCodetext("DATA"); // regular data
+ builder.AddFNC1SecondPosition("12"); // FNC1 with value "12"
+ builder.AddPlainCodetext("MORE"); // more data
+ string extendedText = builder.GetExtendedCodetext();
- // Test with StripFNC disabled (the FNC1 character should be retained).
- bool stripFncDisabledResult = TestStripFnc(imageStream, false, out string decodedWithoutStrip);
- // Reset stream position for the next read.
- imageStream.Position = 0;
-
- // Test with StripFNC enabled (the FNC1 character should be removed).
- bool stripFncEnabledResult = TestStripFnc(imageStream, true, out string decodedWithStrip);
- // Reset stream position for any further use.
- imageStream.Position = 0;
+ // Generate QR barcode with Extended mode (supports FNC1)
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR))
+ {
+ generator.CodeText = extendedText;
+ generator.Parameters.Barcode.QR.EncodeMode = QREncodeMode.Extended;
+ generator.Save(barcodePath, BarCodeImageFormat.Png);
+ }
- int passed = 0, failed = 0;
+ // Verify that the barcode file was created
+ if (!File.Exists(barcodePath))
+ {
+ Console.WriteLine("FAILED: Barcode image was not created.");
+ return;
+ }
- // The FNC1 character is represented by ASCII 29 (Group Separator).
- const char fnc1Char = '\u001D';
+ // Read barcode without stripping FNC characters (StripFNC = false)
+ string codeTextWithoutStrip;
+ using (BarCodeReader reader = new BarCodeReader(barcodePath, DecodeType.QR))
+ {
+ reader.BarcodeSettings.StripFNC = false;
+ BarCodeResult[] results = reader.ReadBarCodes();
+ if (results.Length == 0)
+ {
+ Console.WriteLine("FAILED: No barcode detected (StripFNC = false).");
+ return;
+ }
+ codeTextWithoutStrip = results[0].CodeText;
+ }
- // Verify that the result without stripping contains the FNC1 character.
- if (decodedWithoutStrip != null && decodedWithoutStrip.IndexOf(fnc1Char) >= 0)
- passed++;
- else
- failed++;
+ // Read barcode with stripping FNC characters (StripFNC = true)
+ string codeTextWithStrip;
+ using (BarCodeReader reader = new BarCodeReader(barcodePath, DecodeType.QR))
+ {
+ reader.BarcodeSettings.StripFNC = true;
+ BarCodeResult[] results = reader.ReadBarCodes();
+ if (results.Length == 0)
+ {
+ Console.WriteLine("FAILED: No barcode detected (StripFNC = true).");
+ return;
+ }
+ codeTextWithStrip = results[0].CodeText;
+ }
- // Verify that the result with stripping does NOT contain the FNC1 character.
- if (decodedWithStrip != null && decodedWithStrip.IndexOf(fnc1Char) < 0)
- passed++;
- else
- failed++;
+ // Simple verification: the texts should differ and the stripped version should be shorter
+ bool testPassed = !string.Equals(codeTextWithoutStrip, codeTextWithStrip) &&
+ codeTextWithStrip.Length < codeTextWithoutStrip.Length;
- // Output the test summary and the decoded strings.
- Console.WriteLine($"Test results: {passed} passed, {failed} failed.");
- Console.WriteLine($"Decoded without StripFNC: \"{decodedWithoutStrip}\"");
- Console.WriteLine($"Decoded with StripFNC: \"{decodedWithStrip}\"");
+ if (testPassed)
+ {
+ Console.WriteLine("PASSED: StripFNC works as expected.");
+ Console.WriteLine($"Original CodeText: {codeTextWithoutStrip}");
+ Console.WriteLine($"Stripped CodeText: {codeTextWithStrip}");
}
- }
-
- ///
- /// Reads a barcode from the provided stream using the specified StripFNC setting.
- ///
- /// Stream containing the barcode image.
- /// If true, the reader will remove FNC characters from the result.
- /// Outputs the decoded barcode text when reading succeeds.
- /// True if a barcode was successfully read; otherwise, false.
- static bool TestStripFnc(Stream imageStream, bool stripFnc, out string codeText)
- {
- codeText = null;
- // Initialize the reader for GS1‑128 symbology.
- using (var reader = new BarCodeReader(imageStream, DecodeType.GS1Code128))
+ else
{
- // Apply the StripFNC setting.
- reader.BarcodeSettings.StripFNC = stripFnc;
+ Console.WriteLine("FAILED: StripFNC did not modify the CodeText as expected.");
+ Console.WriteLine($"Original CodeText: {codeTextWithoutStrip}");
+ Console.WriteLine($"Stripped CodeText: {codeTextWithStrip}");
+ }
- // Iterate over detected barcodes (there should be only one in this example).
- foreach (var result in reader.ReadBarCodes())
- {
- codeText = result.CodeText;
- return true;
- }
+ // Clean up temporary files (optional)
+ try
+ {
+ File.Delete(barcodePath);
+ Directory.Delete(tempFolder, true);
+ }
+ catch
+ {
+ // Ignored - cleanup is best‑effort
}
- return false;
}
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-unit-test-verifying-custom-customerinformationdecoder-receives-raw-barcode-bytes-before-interpretation.cs b/special-barcode-recognition-settings/write-unit-test-verifying-custom-customerinformationdecoder-receives-raw-barcode-bytes-before-interpretation.cs
index 03665f0..aa25b24 100644
--- a/special-barcode-recognition-settings/write-unit-test-verifying-custom-customerinformationdecoder-receives-raw-barcode-bytes-before-interpretation.cs
+++ b/special-barcode-recognition-settings/write-unit-test-verifying-custom-customerinformationdecoder-receives-raw-barcode-bytes-before-interpretation.cs
@@ -1,8 +1,8 @@
-// Title: Verify custom CustomerInformationDecoder receives raw barcode bytes
-// Description: Demonstrates how to attach a custom CustomerInformationDecoder to an Australia Post barcode reader and confirm it receives the raw data before interpretation.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on custom decoding of Australia Post customer information. It showcases the use of BarcodeGenerator, BarCodeReader, and the AustraliaPostCustomerInformationDecoder API to customize data handling, a common need when integrating barcode data with legacy systems or performing raw data validation. Developers can adapt this pattern for other symbologies and custom decoders.
+// Title: Unit test for custom CustomerInformationDecoder in Australia Post barcode
+// Description: Demonstrates how to generate an Australia Post barcode, apply a custom CustomerInformationDecoder, and verify that the decoder receives the raw customer information field.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator, BarCodeReader, and the AustraliaPostCustomerInformationDecoder API classes. Developers often need to customize decoding of specific barcode fields, such as the customer information segment in Australia Post barcodes, to access raw data before standard interpretation. The pattern shown here is common for unit testing custom decoders in automated pipelines.
// Prompt: Write a unit test verifying custom CustomerInformationDecoder receives raw barcode bytes before interpretation.
-// Tags: australia post, customer information, decoder, custom decoder, barcode generation, barcode recognition, aspnet.barcode
+// Tags: australia post, custom decoder, barcode generation, barcode recognition, unit test, aspose.barcode
using System;
using System.IO;
@@ -12,81 +12,83 @@
using Aspose.Drawing;
///
-/// Custom decoder that captures the raw data passed from the barcode reader.
-/// Inherits from to integrate with the Australia Post decoding pipeline.
-///
-class MyDecoder : AustraliaPostCustomerInformationDecoder
-{
- ///
- /// Gets the raw data received by the decoder.
- ///
- public string ReceivedData { get; private set; }
-
- ///
- /// Stores the incoming data and returns it unchanged for testing purposes.
- ///
- /// Raw data string supplied by the barcode reader.
- /// The same data string that was received.
- public string Decode(string data)
- {
- ReceivedData = data;
- // Return the raw data unchanged for this test
- return data;
- }
-}
-
-///
-/// Entry point for the example that generates an Australia Post barcode,
-/// reads it with a custom decoder, and verifies the decoder receives the raw bytes.
+/// Contains the entry point that demonstrates a unit‑test‑style verification of a custom
+/// AustraliaPostCustomerInformationDecoder. The program generates a barcode, reads it back,
+/// and checks that the decoder receives the raw customer information field.
///
class Program
{
///
- /// Generates a barcode, reads it using a custom ,
- /// and checks that the decoder was invoked with the expected raw data.
+ /// Generates an Australia Post barcode, applies a custom decoder, and validates that the decoder
+ /// was invoked with the raw data. Results are written to the console.
///
static void Main()
{
- // Generate an Australia Post barcode with sample data and store it in a memory stream
- using (var imageStream = new MemoryStream())
+ // Instantiate the custom decoder that will capture the raw customer information field.
+ var decoder = new TestCustomerInformationDecoder();
+
+ // Create a barcode generator for the Australia Post symbology with sample data.
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678ABCde"))
{
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678ABCde"))
+ // Save the generated barcode image to a memory stream in PNG format.
+ using (var ms = new MemoryStream())
{
- // Use CTable interpreting type for customer information
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable;
- // Save the generated barcode image to the stream in PNG format
- generator.Save(imageStream, BarCodeImageFormat.Png);
- }
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading.
- // Reset stream position to the beginning for reading
- imageStream.Position = 0;
+ // Initialize a barcode reader for the generated image and configure it to use the custom decoder.
+ using (var reader = new BarCodeReader(ms, DecodeType.AustraliaPost))
+ {
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder = decoder;
- // Prepare the custom decoder instance
- var customDecoder = new MyDecoder();
+ // Perform barcode recognition.
+ var results = reader.ReadBarCodes();
- // Create a barcode reader configured for Australia Post symbology
- using (var reader = new BarCodeReader(imageStream, DecodeType.AustraliaPost))
- {
- // Assign the custom decoder to the AustraliaPost settings
- reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder = customDecoder;
+ // Determine whether at least one barcode was detected.
+ bool barcodeFound = results != null && results.Length > 0;
- // Perform recognition and output detected code texts
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected CodeText: {result.CodeText}");
- }
- }
+ // Verify that the custom decoder received non‑empty raw data.
+ bool decoderInvoked = !string.IsNullOrEmpty(decoder.ReceivedRawData);
- // Verify that the decoder received the raw barcode bytes
- if (!string.IsNullOrEmpty(customDecoder.ReceivedData))
- {
- Console.WriteLine("PASS: Custom decoder received raw barcode data.");
- Console.WriteLine($"Raw data passed to decoder: {customDecoder.ReceivedData}");
- }
- else
- {
- Console.WriteLine("FAIL: Custom decoder did not receive raw barcode data.");
+ // Output test outcome.
+ if (barcodeFound && decoderInvoked)
+ {
+ Console.WriteLine("PASS: Barcode recognized and custom decoder received raw data.");
+ Console.WriteLine($"Decoder raw data: {decoder.ReceivedRawData}");
+ }
+ else
+ {
+ Console.WriteLine("FAIL: Test conditions not met.");
+ Console.WriteLine($"Barcode found: {barcodeFound}");
+ Console.WriteLine($"Decoder invoked: {decoderInvoked}");
+ }
+ }
}
}
}
+}
+
+///
+/// Custom implementation of AustraliaPostCustomerInformationDecoder used for testing.
+/// It records the raw customer information field passed during decoding.
+///
+class TestCustomerInformationDecoder : AustraliaPostCustomerInformationDecoder
+{
+ ///
+ /// Gets the raw customer information data received from the barcode reader.
+ ///
+ public string ReceivedRawData { get; private set; }
+
+ ///
+ /// Called by the barcode reader with the raw customer information field.
+ /// Stores the raw data and returns a placeholder decoded string.
+ ///
+ /// The raw customer information field extracted from the barcode.
+ /// A placeholder decoded string.
+ public string Decode(string customerInformationField)
+ {
+ ReceivedRawData = customerInformationField;
+ // For testing purposes, return a simple placeholder.
+ return "DecodedInfo";
+ }
}
\ No newline at end of file
diff --git a/special-barcode-recognition-settings/write-validation-routine-ensuring-processorsettingsmaxadditionalallowedthreads-does-not-exceed-system-limits.cs b/special-barcode-recognition-settings/write-validation-routine-ensuring-processorsettingsmaxadditionalallowedthreads-does-not-exceed-system-limits.cs
index a50d9bd..2365ae1 100644
--- a/special-barcode-recognition-settings/write-validation-routine-ensuring-processorsettingsmaxadditionalallowedthreads-does-not-exceed-system-limits.cs
+++ b/special-barcode-recognition-settings/write-validation-routine-ensuring-processorsettingsmaxadditionalallowedthreads-does-not-exceed-system-limits.cs
@@ -1,55 +1,83 @@
-// Title: Validate ProcessorSettings.MaxAdditionalAllowedThreads against system limits
-// Description: Demonstrates how to ensure the MaxAdditionalAllowedThreads setting does not exceed the machine's logical processor count, adjusting it if necessary.
-// Category-Description: This example belongs to the Aspose.BarCode threading configuration category, illustrating the use of BarCodeReader.ProcessorSettings to control parallel processing. Developers often need to limit additional threads to avoid oversubscription of CPU resources, especially in high‑throughput scanning scenarios. The snippet shows retrieving system processor count, defining safe bounds, and applying validated values.
+// Title: Validate MaxAdditionalAllowedThreads Setting for Aspose.BarCode
+// Description: Demonstrates how to validate and safely set the MaxAdditionalAllowedThreads property of Aspose.BarCode's ProcessorSettings, ensuring it stays within system limits.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating how to work with processor settings to control multithreading. It showcases the BarCodeReader class and its ProcessorSettings, a common requirement when optimizing barcode recognition performance on multi‑core systems. Developers often need to validate thread counts to avoid exceeding hardware capabilities while maximizing throughput.
// Prompt: Write a validation routine ensuring ProcessorSettings.MaxAdditionalAllowedThreads does not exceed system limits.
-// Tags: barcode, threading, validation, processorsettings, aspose.barcode
+// Tags: barcode, validation, configuration, barcodereader, processorsettings
using System;
+using Aspose.BarCode;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode.Common;
///
-/// Provides an example of validating and setting the maximum number of additional threads
-/// allowed for Aspose.BarCode's based on system limits.
+/// Provides a console example that validates and applies a thread count limit
+/// to .
///
class Program
{
///
- /// Entry point of the example. Retrieves the logical processor count, validates a desired
- /// thread count against a safe upper bound, and applies the validated value to the processor settings.
+ /// Entry point of the example. Demonstrates validation with both an exceeding
+ /// and a valid thread count, handling any validation errors gracefully.
///
static void Main()
{
- // Retrieve the number of logical processors available on the current machine.
- int processorCount = Environment.ProcessorCount;
+ // Calculate sample values: one that exceeds the safe limit, one that is within the limit.
+ int exceedingValue = Environment.ProcessorCount * 3; // Intentionally too high.
+ int validValue = Environment.ProcessorCount * 2; // Within the safe range.
- // Example desired value for additional threads (could be sourced from configuration or arguments).
- // Here we intentionally set it to three times the processor count to demonstrate the validation.
- int desiredAdditionalThreads = processorCount * 3;
+ // Attempt to set the exceeding value and capture validation failure.
+ Console.WriteLine("Attempting to set exceeding value:");
+ try
+ {
+ ValidateMaxAdditionalAllowedThreads(exceedingValue);
+ }
+ catch (ArgumentOutOfRangeException ex)
+ {
+ Console.WriteLine($"Validation failed: {ex.Message}");
+ }
- // Define a safe upper bound for additional threads (e.g., twice the core count).
- int maxAllowed = processorCount * 2;
+ Console.WriteLine();
- // Ensure the requested thread count is not negative.
- if (desiredAdditionalThreads < 0)
+ // Attempt to set a valid value and confirm successful application.
+ Console.WriteLine("Attempting to set valid value:");
+ try
{
- throw new ArgumentOutOfRangeException(
- nameof(desiredAdditionalThreads),
- "MaxAdditionalAllowedThreads cannot be negative.");
+ ValidateMaxAdditionalAllowedThreads(validValue);
+ }
+ catch (ArgumentOutOfRangeException ex)
+ {
+ Console.WriteLine($"Validation failed: {ex.Message}");
}
+ }
- // If the requested value exceeds the safe limit, adjust it down to the maximum allowed.
- if (desiredAdditionalThreads > maxAllowed)
+ ///
+ /// Validates that the requested number of additional threads does not exceed a safe system limit.
+ /// The safe limit is defined as twice the number of logical processors.
+ ///
+ /// The number of additional threads to set.
+ static void ValidateMaxAdditionalAllowedThreads(int requestedThreads)
+ {
+ // Define a safe maximum based on the current environment.
+ int safeMaximum = Environment.ProcessorCount * 2;
+
+ // Guard against negative thread counts.
+ if (requestedThreads < 0)
{
- Console.WriteLine(
- $"Requested MaxAdditionalAllowedThreads ({desiredAdditionalThreads}) exceeds system limit ({maxAllowed}). Adjusting to limit.");
- desiredAdditionalThreads = maxAllowed;
+ throw new ArgumentOutOfRangeException(
+ nameof(requestedThreads),
+ "Thread count cannot be negative.");
}
- // Apply the validated (and possibly adjusted) thread count to the Aspose.BarCode processor settings.
- BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = desiredAdditionalThreads;
+ // Guard against values that exceed the calculated safe maximum.
+ if (requestedThreads > safeMaximum)
+ {
+ throw new ArgumentOutOfRangeException(
+ nameof(requestedThreads),
+ $"Requested threads ({requestedThreads}) exceed the safe maximum ({safeMaximum}).");
+ }
- // Output the final setting for verification.
- Console.WriteLine(
- $"ProcessorSettings.MaxAdditionalAllowedThreads is set to {BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads}.");
+ // Apply the validated value to Aspose.BarCode processor settings.
+ BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = requestedThreads;
+ Console.WriteLine($"ProcessorSettings.MaxAdditionalAllowedThreads successfully set to {requestedThreads}.");
}
}
\ No newline at end of file