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 187e7f5..91908ba 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,50 +1,74 @@ +// 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. +// 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 + using System; using System.IO; using System.Threading; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Demonstrates generating a barcode, storing it in memory, and reading it back using Aspose.BarCode. +/// Demonstrates adjusting .NET ThreadPool settings and using Aspose.BarCode to generate and read a Code128 barcode. /// class Program { /// - /// Entry point of the application. - /// Configures thread pool, creates a barcode image in memory, and reads it back. + /// Entry point of the example. Configures ThreadPool limits, creates a barcode image, reads it, and cleans up. /// static void Main() { - // Configure the thread pool to have a minimum of 2 worker and I/O threads, - // and a maximum of 8 worker and I/O threads. - ThreadPool.SetMinThreads(2, 2); - ThreadPool.SetMaxThreads(8, 8); + // -------------------------------------------------------------------- + // 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 - // Use a memory stream to hold the generated barcode image. - using (var ms = new MemoryStream()) + // ------------------------------------------------- + // Generate a sample barcode image using Code128 symbology + // ------------------------------------------------- + string imagePath = "sample_barcode.png"; + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Create a barcode generator for Code128 with the data "123456". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) - { - // Save the generated barcode as a PNG image into the memory stream. - generator.Save(ms, BarCodeImageFormat.Png); - } + generator.Save(imagePath, BarCodeImageFormat.Png); + } - // Reset the stream position to the beginning before reading. - ms.Position = 0; + // ------------------------------------------------- + // Verify that the barcode image was successfully created + // ------------------------------------------------- + if (!File.Exists(imagePath)) + { + Console.WriteLine("Failed to create barcode image."); + return; + } - // Initialize a barcode reader that can decode all supported barcode types, - // using the memory stream that contains the PNG image. - using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes)) + // ------------------------------------------------- + // Read the barcode from the generated image using BarCodeReader + // ------------------------------------------------- + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + { + foreach (var result in reader.ReadBarCodes()) { - // Iterate through all detected barcodes and output their type and text. - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}"); - } + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Detected Text: {result.CodeText}"); } } + + // ------------------------------------------------- + // Clean up the sample image file (optional) + // ------------------------------------------------- + try + { + File.Delete(imagePath); + } + catch + { + // Ignore any cleanup errors + } } } \ 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 74dfe6f..488ebbe 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,54 +1,51 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Demonstrates generating a Code128 barcode, reading it back, and cleaning up the temporary file. +/// Demonstrates configuring Aspose.BarCode to use all CPU cores for barcode recognition and reading a Code128 barcode. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode image, reads it, displays the results, and deletes the temporary file. + /// Entry point that generates a sample barcode if missing, enables multi‑core processing, and reads the barcode information. /// static void Main() { - // Define a temporary file path for the generated barcode image. - string tempImagePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png"); - - // Generate a simple Code128 barcode and save it to the temporary file. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) - { - generator.Save(tempImagePath, BarCodeImageFormat.Png); - } - - // Configure the barcode reader to utilize all CPU cores for faster recognition. + // Enable utilization of all CPU cores for barcode recognition BarCodeReader.ProcessorSettings.UseAllCores = true; - // Read the barcode from the generated image file. - using (var reader = new BarCodeReader(tempImagePath, DecodeType.AllSupportedTypes)) + // Path to the barcode image file + string imagePath = "barcode.png"; + + // Generate a sample Code128 barcode image if it does not already exist + if (!File.Exists(imagePath)) { - // Iterate through all detected barcodes and output their type and text. - foreach (var result in reader.ReadBarCodes()) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789")) { - Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Detected Text: {result.CodeText}"); + generator.Save(imagePath, BarCodeImageFormat.Png); } } - // Clean up the temporary image file if it still exists. - if (File.Exists(tempImagePath)) + // Initialize the reader to decode all supported barcode types from the image + using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - try - { - File.Delete(tempImagePath); - } - catch + // Iterate through all detected barcodes and output their details + foreach (var result in reader.ReadBarCodes()) { - // If deletion fails, ignore – the OS will eventually remove the file. + 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}"); } } } 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 e9c0047..7501249 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,103 +1,88 @@ +// 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. +// 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 + using System; using System.Collections.Generic; +using System.ComponentModel; using System.IO; -using System.Threading.Tasks; +using System.Threading; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates generating barcode images, treating them as video frames, -/// and processing each frame to recognize barcodes using Aspose.BarCode. +/// Example program that generates barcode images, simulates video frames, +/// and reads them in a background worker using Aspose.BarCode APIs. /// class Program { /// - /// Entry point of the application. - /// Configures processor settings, generates sample frames, and processes them asynchronously. + /// Entry point. Generates sample frames, configures processor settings, + /// and processes frames asynchronously. /// static void Main() { - // Use all available CPU cores for barcode processing (optimal performance) - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount; - - // Generate a small collection of barcode images that simulate video frames - List frameStreams = GenerateSampleFrames(5); - - // Run the frame processing on a background task (simulating a background worker) - Task processingTask = Task.Run(() => ProcessFrames(frameStreams)); - - // Wait for the background task to complete before exiting the program - processingTask.Wait(); - } - - /// - /// Generates the specified number of barcode images and returns them as memory streams. - /// - /// Number of barcode frames to generate. - /// List of memory streams containing PNG barcode images. - private static List GenerateSampleFrames(int count) - { - var frames = new List(); - - for (int i = 0; i < count; i++) + // Generate a few barcode images to simulate video frames + var frames = new List(); + for (int i = 0; i < 3; i++) { - // Create a unique code text for each frame (e.g., FRAME01, FRAME02, ...) - string codeText = $"FRAME{i + 1:D2}"; - - // Initialize a barcode generator for Code128 with the specified text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Create a barcode generator for Code128 with unique text + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i + 1}")) { - // Set a consistent image size for all generated barcodes - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - - // Save the generated barcode image to a memory stream in PNG format - var ms = new MemoryStream(); - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for subsequent reading - - // Add the memory stream to the collection of frames - frames.Add(ms); + // 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()); + } + } } } - return frames; - } + // Synchronization primitive to wait for background work completion + var doneEvent = new ManualResetEventSlim(false); - /// - /// Processes each barcode frame, reads any barcodes present, and writes the results to the console. - /// - /// List of memory streams representing barcode frames. - private static void ProcessFrames(List frameStreams) - { - int frameIndex = 0; - - // Iterate over each frame stream - foreach (var stream in frameStreams) + // BackgroundWorker that processes the simulated video frames + var worker = new BackgroundWorker(); + worker.DoWork += (sender, args) => { - frameIndex++; + // Configure processor settings for optimal core usage + BarCodeReader.ProcessorSettings.UseAllCores = false; + BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Math.Max(1, Environment.ProcessorCount / 2); - // Load the image from the memory stream - using (var bitmap = new Bitmap(stream)) + // Iterate over each simulated frame + foreach (var frameData in frames) { - // Initialize a barcode reader that supports all barcode types - using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) + // 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)) { - // Apply a high-performance quality preset for faster processing + // Apply a high‑performance quality preset reader.QualitySettings = QualitySettings.HighPerformance; - // Read all barcodes found in the current frame + // Read and output all detected barcodes foreach (var result in reader.ReadBarCodes()) { - // Output the detected barcode type and its text value - Console.WriteLine($"Frame {frameIndex}: Detected {result.CodeTypeName} - Text: {result.CodeText}"); + Console.WriteLine($"Detected: {result.CodeTypeName} - {result.CodeText}"); } } } + }; + // Signal completion when background work finishes + worker.RunWorkerCompleted += (s, e) => doneEvent.Set(); - // Release the memory stream resources after processing the frame - stream.Dispose(); - } + // Start processing and wait until it finishes + worker.RunWorkerAsync(); + doneEvent.Wait(); } } \ 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 dc2417c..a8f07bd 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,91 +1,92 @@ +// 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. +// 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 + using System; using System.IO; +using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generation and reading of GS1 Code128 barcodes with FNC1 characters using Aspose.BarCode. +/// Demonstrates batch processing of barcode images while keeping FNC symbols (StripFNC = false). /// class Program { /// - /// Entry point of the application. - /// Generates sample barcode images, saves them to a folder, and then reads them back, - /// displaying barcode type and text (including FNC characters) to the console. + /// Entry point. Generates sample images if needed and reads all PNG files in the InputImages folder, + /// printing detected barcode information without stripping FNC characters. /// static void Main() { - // -------------------------------------------------------------------- - // Prepare output folder for barcode images - // -------------------------------------------------------------------- - string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - if (!Directory.Exists(folderPath)) - { - // Create the folder if it does not exist - Directory.CreateDirectory(folderPath); - } + // Define the folder that will contain input images. + string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "InputImages"); - // -------------------------------------------------------------------- - // Define sample barcode texts containing GS1 Application Identifiers - // -------------------------------------------------------------------- - string[] sampleTexts = new string[] + // Ensure the input folder exists. + if (!Directory.Exists(inputFolder)) { - "(01)12345678901231(10)ABC", // GTIN and batch number - "(01)98765432109876(21)XYZ123", // GTIN and serial number - "(01)55555555555555(17)210101" // GTIN and expiration date - }; + Directory.CreateDirectory(inputFolder); + } - // -------------------------------------------------------------------- - // Generate barcode images for each sample text - // -------------------------------------------------------------------- - for (int i = 0; i < sampleTexts.Length; i++) + // 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) { - // Build file name for the current barcode image - string filePath = Path.Combine(folderPath, $"sample{i + 1}.png"); + List sampleTexts = new List + { + "(01)12345678901231", // GTIN + "(01)98765432109876(10)ABCD", // GTIN with lot number + "(01)55555555555555(21)XYZ" // GTIN with serial number + }; - // Create a barcode generator configured for GS1 Code128 - using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, sampleTexts[i])) + int index = 1; + foreach (string text in sampleTexts) { - // Save the generated barcode as a PNG file - generator.Save(filePath); + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.GS1Code128, text)) + { + string filePath = Path.Combine(inputFolder, $"Sample{index}.png"); + generator.Save(filePath, BarCodeImageFormat.Png); + } + index++; } } - // -------------------------------------------------------------------- - // Retrieve all generated PNG images from the folder - // -------------------------------------------------------------------- - string[] imageFiles = Directory.GetFiles(folderPath, "*.png"); - if (imageFiles.Length == 0) - { - Console.WriteLine("No barcode images found to process."); - return; - } + // Retrieve all PNG images from the input folder. + string[] imageFiles = Directory.GetFiles(inputFolder, "*.png"); - // -------------------------------------------------------------------- - // Read each barcode image and output its details - // -------------------------------------------------------------------- + // Process each image file. foreach (string imagePath in imageFiles) { if (!File.Exists(imagePath)) { - // Skip missing files (should not happen, but guard against it) Console.WriteLine($"File not found: {imagePath}"); continue; } - // Initialize a barcode reader for all supported types - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Initialize the barcode reader for all supported symbologies. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - // Preserve FNC characters in the decoded text + // Disable stripping of FNC characters to keep them in the result. reader.BarcodeSettings.StripFNC = false; - // Iterate through all detected barcodes 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 barcode detected in {Path.GetFileName(imagePath)}"); + } + else { - Console.WriteLine($"File: {Path.GetFileName(imagePath)}"); - Console.WriteLine($" Type: {result.CodeTypeName}"); - Console.WriteLine($" CodeText (with FNC): {result.CodeText}"); + // Output details for each detected barcode. + foreach (BarCodeResult result in results) + { + Console.WriteLine($"File: {Path.GetFileName(imagePath)} | 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 cc5e67d..ae49ab7 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,88 +1,90 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Demonstrates generating GS1 Code128 barcodes, saving them as images, -/// and reading them back while stripping FNC characters. +/// 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. /// class Program { /// - /// Entry point of the application. - /// Generates sample barcode images, reads them, and outputs original and stripped code texts. + /// 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. /// static void Main() { - // Determine a temporary directory to store generated barcode images. - string outputDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodes"); - if (!Directory.Exists(outputDir)) - { - // Create the directory if it does not already exist. - Directory.CreateDirectory(outputDir); - } + // Folder containing barcode images + string imagesFolder = "Images"; - // Sample code texts that include GS1 Application Identifiers (AIs) and potential FNC characters. - string[] sampleCodeTexts = new string[] + // Verify that the folder exists before proceeding + if (!Directory.Exists(imagesFolder)) { - "(01)12345678901231(21)ABC123", // Typical GS1 format without explicit FNC. - "(02)04006664241007(37)1(400)7019590754", // Contains groups that resemble FNC characters. - "(10)123456(17)210101(21)XYZ", // Multiple AI groups. - }; + Console.WriteLine($"Folder not found: {imagesFolder}"); + return; + } - // Array to hold the file paths of the generated barcode images. - string[] imagePaths = new string[sampleCodeTexts.Length]; + // 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 - // Generate a barcode image for each sample text. - for (int i = 0; i < sampleCodeTexts.Length; i++) + // Process each file until the maximum count is reached + foreach (string filePath in imageFiles) { - // Construct a unique file name for each barcode image. - string filePath = Path.Combine(outputDir, $"barcode_{i}.png"); + if (processed >= maxFiles) break; - // Create a BarcodeGenerator for GS1 Code128 using the current sample text. - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.GS1Code128, sampleCodeTexts[i])) + // Ensure the file still exists (it could have been removed externally) + if (!File.Exists(filePath)) { - // Save the generated barcode as a PNG image. - generator.Save(filePath); + Console.WriteLine($"File not found: {filePath}"); + continue; } - // Store the generated image path for later processing. - imagePaths[i] = filePath; - } - - // Iterate over each generated image to read and process the barcode. - foreach (string imagePath in imagePaths) - { - // Verify that the image file exists before attempting to read it. - if (!File.Exists(imagePath)) + // Accept only common image formats + string extension = Path.GetExtension(filePath).ToLowerInvariant(); + if (extension != ".png" && extension != ".jpg" && extension != ".jpeg" && extension != ".bmp") { - Console.WriteLine($"File not found: {imagePath}"); + Console.WriteLine($"Unsupported file type: {filePath}"); continue; } - // Initialize a BarCodeReader to decode all supported barcode types from the image. - using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Initialize the barcode reader for the current image + using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) { - // Enable automatic stripping of FNC characters from the decoded text. + // Enable stripping of FNC symbols from decoded text reader.BarcodeSettings.StripFNC = true; - // Read all barcodes present in the image. - foreach (var result in reader.ReadBarCodes()) + // Perform the recognition + BarCodeResult[] results = reader.ReadBarCodes(); + + // Output the results + if (results.Length == 0) { - // Output the image name and the decoded texts. - Console.WriteLine($"Image: {Path.GetFileName(imagePath)}"); - Console.WriteLine($"Original CodeText: {result.CodeText}"); - // Since StripFNC is true, the CodeText already has FNC characters removed. - Console.WriteLine($"Stripped CodeText: {result.CodeText}"); - Console.WriteLine(); + Console.WriteLine($"No barcodes detected in: {Path.GetFileName(filePath)}"); + } + else + { + Console.WriteLine($"Barcodes in {Path.GetFileName(filePath)} (FNC stripped):"); + foreach (BarCodeResult result in results) + { + Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}"); + } } } + + processed++; } - // Optional cleanup: delete the generated barcode images. - // foreach (var path in imagePaths) { File.Delete(path); } + 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 26dfe0c..c7234f6 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,66 +1,66 @@ +// 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. +// Prompt: Create a multithreaded barcode scanner that processes image files in parallel using default ProcessorSettings. +// Tags: code128, scanning, console, barcodegenerator, barcodereader, parallel, aspose.barcode + using System; using System.IO; +using System.Collections.Generic; using System.Threading.Tasks; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.BarCode; /// -/// Sample program demonstrating barcode generation and reading using Aspose.BarCode. +/// Demonstrates parallel barcode generation and recognition using Aspose.BarCode. /// class Program { /// - /// Entry point. Generates sample barcodes, reads them in parallel, and cleans up temporary files. + /// Entry point of the example. Generates sample barcode images and scans them concurrently. /// static void Main() { - // Create a temporary folder for sample barcode images - string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodesSample"); - Directory.CreateDirectory(tempFolder); + // Define the directory that will hold the sample barcode images. + string imagesDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(imagesDir); - // Generate sample barcode images (CODE001 to CODE005) + // Build a list of file paths for the sample images. + List imageFiles = new List(); for (int i = 1; i <= 5; i++) { - string codeText = $"CODE{i:D3}"; - string imagePath = Path.Combine(tempFolder, $"barcode{i}.png"); + string filePath = Path.Combine(imagesDir, $"barcode{i}.png"); + imageFiles.Add(filePath); - // Use BarcodeGenerator to create a Code128 barcode and save it as PNG - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Create a barcode image if it does not already exist. + if (!File.Exists(filePath)) { - generator.Save(imagePath); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}")) + { + generator.Save(filePath, BarCodeImageFormat.Png); + } } } - // Configure the barcode reader to use all available processor cores (default behavior) - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount; - - // Retrieve all generated PNG files from the temporary folder - string[] imageFiles = Directory.GetFiles(tempFolder, "*.png"); - - // Process each image in parallel to read barcodes - Parallel.ForEach(imageFiles, filePath => + // Scan all images in parallel using the default ProcessorSettings. + Parallel.ForEach(imageFiles, file => { - // Initialize a reader that supports all barcode types - using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + // Verify that the file exists before attempting to read it. + if (!File.Exists(file)) { - // Iterate through all detected barcodes in the image + Console.WriteLine($"File not found: {file}"); + return; + } + + // Initialize the reader for all supported barcode types. + using (var reader = new BarCodeReader(file, DecodeType.AllSupportedTypes)) + { + // Iterate through all detected barcodes in the image. foreach (var result in reader.ReadBarCodes()) { - // Output file name, barcode type, and decoded text to the console - Console.WriteLine($"File: {Path.GetFileName(filePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); + Console.WriteLine($"{Path.GetFileName(file)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); } } }); - - // Cleanup temporary files (optional). Errors are ignored to avoid crashing the program. - try - { - Directory.Delete(tempFolder, true); - } - catch - { - // Ignored - } } } \ No newline at end of file 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 d7d513d..570f147 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,56 +1,84 @@ +// 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. +// 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 + using System; using System.IO; -using Aspose.Drawing; using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates reading Australia Post barcodes from a set of PNG files using Aspose.BarCode. +/// Sample program that generates and reads a batch of PNG barcodes using Australia Post CTable interpretation. /// class Program { /// - /// Entry point of the application. Processes each PNG file, reads barcodes, and prints results. + /// Entry point. Generates sample Australia Post barcodes, saves them as PNG, then reads them applying CTable interpretation. /// static void Main() { - // Define the list of PNG files to be processed. - string[] pngFiles = new string[] + // Prepare a temporary folder for sample barcode images + string folder = Path.Combine(Path.GetTempPath(), "AustraliaPostBarcodes"); + Directory.CreateDirectory(folder); + + // Sample Australia Post code texts (must satisfy CTable rules) + string[] sampleCodes = new string[] { - "barcode1.png", - "barcode2.png", - "barcode3.png" + "5912345678AB", + "5912345678CD", + "5912345678EF" }; - // Iterate over each file path in the array. - foreach (string filePath in pngFiles) + // Generate PNG files for the sample codes + foreach (string code in sampleCodes) { - // Verify that the file exists before attempting to process it. - if (!File.Exists(filePath)) + string filePath = Path.Combine(folder, $"{code}.png"); + using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, code)) { - Console.WriteLine($"File not found: {filePath}"); - continue; // Skip to the next file if the current one is missing. + // Apply CTable interpreting type for generation + generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable; + generator.Save(filePath, BarCodeImageFormat.Png); } + } - // Load the image from the file into a Bitmap object. - using (Bitmap bitmap = new Bitmap(filePath)) + // 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++) + { + string file = pngFiles[i]; + if (!File.Exists(file)) { - // Create a BarCodeReader configured to decode Australia Post barcodes. - using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost)) + Console.WriteLine($"File not found: {file}"); + continue; + } + + using (var reader = new BarCodeReader(file, DecodeType.AustraliaPost)) + { + // 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()) { - // Set the customer information interpreting type to CTable. - reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; - - // Read all barcodes found in the image. - foreach (var result in reader.ReadBarCodes()) - { - // Output the file name and barcode details to the console. - Console.WriteLine($"File: {filePath}"); - Console.WriteLine($"Barcode Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text: {result.CodeText}"); - } + 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}"); } } } + + // 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 cb72415..66fa8f5 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,74 +1,73 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Demonstrates generation and recognition of Australia Post barcodes using NTable interpreting type. +/// Sample program that reads up to five TIFF images from a folder and decodes +/// Australia Post barcodes using the NTable customer information interpreting type. /// class Program { /// - /// Entry point of the application. Generates sample TIFF files with Australia Post barcodes, - /// then reads and decodes them applying the NTable interpreting type. + /// Entry point of the application. /// static void Main() { - // ------------------------------------------------------------ - // Prepare an array of TIFF file names to be created in the current directory. - // ------------------------------------------------------------ - string[] tiffFiles = new string[5]; - for (int i = 0; i < tiffFiles.Length; i++) - { - tiffFiles[i] = $"AustraliaPost_{i + 1}.tif"; - } + // Define the folder that contains the TIFF images. + string folderPath = "tiff_images"; - // ------------------------------------------------------------ - // Generate sample Australia Post barcodes and save each as a TIFF file. - // ------------------------------------------------------------ - for (int i = 0; i < tiffFiles.Length; i++) + // Verify that the folder exists before proceeding. + if (!Directory.Exists(folderPath)) { - // Create a simple numeric code text for the barcode. - string codeText = $"5912345678{i}"; - - // Initialize the barcode generator with Australia Post encoding. - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText)) - { - // Set the interpreting type to NTable for generation. - generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.NTable; - - // Save the generated barcode image as a TIFF file. - generator.Save(tiffFiles[i], BarCodeImageFormat.Tiff); - } + Console.WriteLine($"Folder not found: {folderPath}"); + return; } - // ------------------------------------------------------------ - // Read each generated TIFF file and decode the barcode using NTable interpreting type. - // ------------------------------------------------------------ - foreach (var filePath in tiffFiles) + // 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); + + // Iterate over each selected TIFF file. + for (int i = 0; i < filesToProcess; i++) { - // Verify that the file exists before attempting to read it. - if (!File.Exists(filePath)) + string file = tiffFiles[i]; + + // Ensure the file still exists (it could have been removed externally). + if (!File.Exists(file)) { - Console.WriteLine($"File not found: {filePath}"); + Console.WriteLine($"File not found: {file}"); continue; } - // Initialize the barcode reader for Australia Post type. - using (var reader = new BarCodeReader(filePath, DecodeType.AustraliaPost)) + // Load the TIFF image into a bitmap object. + using (Bitmap bitmap = new Bitmap(file)) { - // Apply NTable interpreting type for recognition. - reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.NTable; - - // Iterate through all detected barcodes in the image. - foreach (var result in reader.ReadBarCodes()) + // Create a barcode reader configured for Australia Post symbology. + using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost)) { - Console.WriteLine($"File: {Path.GetFileName(filePath)}"); - Console.WriteLine($" Detected Type: {result.CodeTypeName}"); - Console.WriteLine($" Code Text: {result.CodeText}"); + // Set the customer information interpreting type to NTable. + reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.NTable; + + // Read all barcodes found in the image. + foreach (var result in reader.ReadBarCodes()) + { + // 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(); + } } } } 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 b3afd08..3b15475 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,69 +1,73 @@ +// 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. +// 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 + using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Demonstrates generating a Code128 barcode, toggling the StripFNC setting, -/// and decoding the barcode with and without stripping FNC characters. +/// Generates a GS1‑128 barcode, then reads it twice: once preserving FNC characters +/// and once stripping them, illustrating the impact of the StripFNC setting. /// class Program { /// - /// Entry point of the console application. - /// Generates a barcode, decodes it twice (once with StripFNC disabled, - /// once with it enabled), and writes the results to the console. + /// Entry point of the example. Creates a barcode image in memory, then decodes it + /// with different StripFNC configurations. /// static void Main() { - // Create a barcode generator for Code128 with the data "123456". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Sample GS1‑128 barcode text containing FNC characters + const string barcodeText = "(02)04006664241007(37)1(400)7019590754"; + + // Generate the barcode image into a memory stream (PNG format) + using (var imageStream = new MemoryStream()) { - // Store the generated barcode image in a memory stream. - using (var ms = new MemoryStream()) + using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, barcodeText)) { - // Save the barcode as a PNG image into the memory stream. - generator.Save(ms, BarCodeImageFormat.Png); - // Reset stream position to the beginning for reading. - ms.Position = 0; + // Save the generated barcode as PNG to the stream + generator.Save(imageStream, BarCodeImageFormat.Png); + } - // ------------------------------------------------------------ - // First decoding pass: StripFNC disabled (default behavior) - // ------------------------------------------------------------ - using (var bitmap = new Bitmap(ms)) - using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) - { - // Ensure FNC characters are not stripped during decoding. - reader.BarcodeSettings.StripFNC = false; + // Reset stream position so it can be read from the beginning + imageStream.Position = 0; - // Iterate through all detected barcodes and output their details. - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"StripFNC=False -> Type: {result.CodeTypeName}, Text: {result.CodeText}"); - } - } - - // Reset the stream position again for the second decoding pass. - ms.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; - // ------------------------------------------------------------ - // Second decoding pass: StripFNC enabled - // ------------------------------------------------------------ - using (var bitmap = new Bitmap(ms)) - using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) + // Load the image from the stream into a bitmap object + using (var bitmap = new Bitmap(imageStream)) { - // Enable stripping of FNC characters during decoding. - reader.BarcodeSettings.StripFNC = true; - - // Iterate through all detected barcodes and output their details. - foreach (var result in reader.ReadBarCodes()) + // Initialize a reader for Code128 (covers GS1‑128) + using (var reader = new BarCodeReader(bitmap, DecodeType.Code128)) { - Console.WriteLine($"StripFNC=True -> Type: {result.CodeTypeName}, Text: {result.CodeText}"); + // Apply the StripFNC setting (true = remove FNC characters) + 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}"); + } } } } + + // Decode and display results without stripping FNC characters + ReadAndDisplay(false); + + // Decode and display results with FNC characters stripped + ReadAndDisplay(true); } } } \ 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 182d667..1f38c3c 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,117 +1,100 @@ +// 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. +// 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 + using System; using System.IO; -using System.Collections.Generic; using System.Threading.Tasks; -using Aspose.BarCode; -using Aspose.BarCode.BarCodeRecognition; using Aspose.Pdf; using Aspose.Pdf.Facades; +using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates how to read barcodes from PDF files using Aspose.BarCode and Aspose.Pdf. +/// 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. /// class Program { /// - /// Entry point of the application. - /// Processes a list of PDF files (provided via command‑line arguments or a default list), - /// renders each page to an image, and extracts any barcodes found on the pages. + /// 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. /// - /// Optional PDF file paths passed as command‑line arguments. + /// Command‑line arguments; first argument can specify the input folder. static void Main(string[] args) { - // ---------------------------------------------------------------------- - // Prepare the list of PDF files to process. - // ---------------------------------------------------------------------- - // Default sample files – replace with your own paths or pass as command‑line arguments. - List pdfFiles = new List - { - "sample1.pdf", - "sample2.pdf", - "sample3.pdf" - }; + // 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"); - // If arguments are provided, treat them as PDF paths (fallback to the sample list if none). - if (args.Length > 0) + // Verify that the input folder exists. + if (!Directory.Exists(inputFolder)) { - pdfFiles = new List(args); + Console.WriteLine($"Input folder does not exist: {inputFolder}"); + return; } - // Limit processing to a safe number of files for the runner (max 3). - int maxFiles = Math.Min(3, pdfFiles.Count); - pdfFiles = pdfFiles.GetRange(0, maxFiles); - - // ---------------------------------------------------------------------- - // Configure barcode reader to utilize all available processor cores. - // ---------------------------------------------------------------------- - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount; - - // ---------------------------------------------------------------------- - // Process each PDF file in parallel. - // ---------------------------------------------------------------------- - Parallel.ForEach(pdfFiles, pdfPath => + // Retrieve all PDF files in the folder (limit to three files for safe execution in evaluation mode). + string[] pdfFiles = Directory.GetFiles(inputFolder, "*.pdf"); + if (pdfFiles.Length == 0) { - // Verify that the file exists before attempting to process it. - if (!File.Exists(pdfPath)) - { - Console.WriteLine($"File not found: {pdfPath}"); - return; - } + Console.WriteLine("No PDF files found."); + return; + } - try + int maxFiles = Math.Min(pdfFiles.Length, 3); + var filesToProcess = pdfFiles[..maxFiles]; + + // 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 => { - // Load the PDF document. - using (var pdfDoc = new Document(pdfPath)) + try { - // Create a converter for rendering PDF pages to images. - using (var pdfConverter = new PdfConverter(pdfDoc)) + // Load the PDF document. + using var pdfDocument = new Document(pdfPath); + + // Initialize a converter to render PDF pages to images. + var converter = new PdfConverter(pdfDocument) { - // Enable barcode optimization during rendering. - pdfConverter.RenderingOptions.BarcodeOptimization = true; + // Enable barcode optimization to improve recognition speed. + RenderingOptions = { BarcodeOptimization = true } + }; - // Process each page sequentially (page rendering is not thread‑safe per document). - for (int pageNumber = 1; pageNumber <= pdfDoc.Pages.Count; pageNumber++) - { - // Set the page range to a single page for conversion. - pdfConverter.StartPage = pageNumber; - pdfConverter.EndPage = pageNumber; + // Limit processing to the first four pages (evaluation mode restriction). + int pageCount = Math.Min(pdfDocument.Pages.Count, 4); - // Perform the conversion for the current page. - pdfConverter.DoConvert(); + for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++) + { + // 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()) - { - pdfConverter.GetNextImage(imageStream); - imageStream.Position = 0; // Reset stream position for reading. + // Retrieve the rendered image into a memory stream. + using var imageStream = new MemoryStream(); + converter.GetNextImage(imageStream); + imageStream.Position = 0; - // Recognize barcodes from the rendered page image. - using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes)) - { - // Optional: use a higher quality preset for better detection. - reader.QualitySettings = QualitySettings.HighQuality; + // Create a barcode reader that attempts to decode all supported symbologies. + using var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes); - // Iterate over all detected barcodes. - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"PDF: {Path.GetFileName(pdfPath)} | Page: {pageNumber}"); - Console.WriteLine($" Type: {result.CodeTypeName}"); - Console.WriteLine($" Text: {result.CodeText}"); - Console.WriteLine($" Confidence: {result.Confidence}"); - Console.WriteLine($" ReadingQuality: {result.ReadingQuality}"); - Console.WriteLine(); - } - } - } + // Iterate through all detected barcodes and output their details. + foreach (var result in reader.ReadBarCodes()) + { + Console.WriteLine($"{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}"); - } - }); + 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 33a948d..5ca4c36 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,33 +1,35 @@ +// 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. +// 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 + using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.BarCodeRecognition; /// -/// Scans a directory for image files and reads any barcodes using Aspose.BarCode. +/// Entry point for the barcode batch decoding console application. /// class Program { /// - /// Entry point of the application. + /// Scans a directory for image files, decodes all supported barcodes with StripFNC disabled, and writes results to the console. /// - /// Optional command‑line arguments. The first argument, if present, specifies the directory to scan. + /// Optional first argument specifying the directory path; if omitted, the current directory is used. static void Main(string[] args) { - // Determine the directory to scan: use first argument or fallback to a sample folder. - string directoryPath = args.Length > 0 ? args[0] : "Barcodes"; + // 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(); // Verify that the directory exists before proceeding. if (!Directory.Exists(directoryPath)) { - Console.WriteLine($"Directory not found: {directoryPath}"); + Console.WriteLine($"Directory does not exist: {directoryPath}"); return; } - // Define the set of image file extensions that will be processed. - string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff" }; - - // Retrieve all files in the target directory. + // 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) { @@ -35,41 +37,43 @@ static void Main(string[] args) return; } - // Iterate over each file and attempt barcode detection on supported image types. + // Process each file individually. foreach (string filePath in files) { - // Skip files whose extensions are not in the supported list. - if (Array.IndexOf(extensions, Path.GetExtension(filePath).ToLowerInvariant()) < 0) + // Skip non‑existing files (should not happen) and filter out unsupported extensions. + if (!File.Exists(filePath)) continue; - // Double‑check that the file still exists (it may have been removed concurrently). - if (!File.Exists(filePath)) - { - Console.WriteLine($"File not found: {filePath}"); + string extension = Path.GetExtension(filePath).ToLowerInvariant(); + if (extension != ".png" && extension != ".jpg" && extension != ".jpeg" && extension != ".bmp" && extension != ".tif" && extension != ".tiff") continue; - } - // Create a barcode reader for the current image, configured to detect all supported types. - using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + // Use BarCodeReader to decode barcodes in the current image file. + using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) { - // Ensure that FNC characters are preserved in the decoded text. + // Ensure FNC characters are not stripped (set to false as required). reader.BarcodeSettings.StripFNC = false; - // Perform the barcode detection. + // Perform the recognition and obtain all results. BarCodeResult[] results = reader.ReadBarCodes(); - // If no barcodes were found, report and move to the next file. + // If no barcodes were detected, report and continue to the next file. if (results.Length == 0) { - Console.WriteLine($"No barcodes detected in: {Path.GetFileName(filePath)}"); + Console.WriteLine($"[File: {Path.GetFileName(filePath)}] No barcodes detected."); continue; } - // Output the detected barcodes for the current image. - Console.WriteLine($"Barcodes in {Path.GetFileName(filePath)}:"); - foreach (var result in results) + // 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) { - Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}"); + Console.WriteLine($" Type: {result.CodeTypeName}"); + Console.WriteLine($" CodeText: {result.CodeText}"); + Console.WriteLine($" Confidence: {result.Confidence}"); + Console.WriteLine($" ReadingQuality: {result.ReadingQuality}"); } } } 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 f8e5294..88701e0 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,75 +1,103 @@ +// 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. +// 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 + using System; using System.IO; -using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Demonstrates reading Australia Post barcodes from image files located on a network share. +/// 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. /// class Program { /// - /// Entry point of the application. Scans a network directory for image files, - /// limits processing to a maximum of five files, and reads Australia Post barcodes - /// from each image using Aspose.BarCode. + /// 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. /// static void Main() { - // Path to the network share containing barcode images - string networkSharePath = @"\\Server\Share\Barcodes"; + // Network share path containing barcode images. + string networkFolder = @"\\server\share\barcodes"; - // Verify that the directory exists before proceeding - if (!Directory.Exists(networkSharePath)) + // Verify the folder exists before proceeding. + if (!Directory.Exists(networkFolder)) { - Console.WriteLine($"Directory not found: {networkSharePath}"); + Console.WriteLine($"Folder not found: {networkFolder}"); return; } - // Retrieve all files from the share (any extension) – we'll filter later - string[] allFiles = Directory.GetFiles(networkSharePath, "*.*", SearchOption.TopDirectoryOnly); - var imageFiles = new List(); + // Define supported image extensions for barcode scanning. + string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff" }; + string[] files = Directory.GetFiles(networkFolder); - // Filter the list to include only common image formats - foreach (string file in allFiles) - { - string ext = Path.GetExtension(file).ToLowerInvariant(); - if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp" || ext == ".tif" || ext == ".tiff") - { - imageFiles.Add(file); - } - } + bool anyFileProcessed = false; - // Process up to a safe number of files (e.g., 5) to avoid excessive load - int maxFiles = Math.Min(5, imageFiles.Count); - for (int i = 0; i < maxFiles; i++) + // Process each file found in the network folder. + foreach (string filePath in files) { - string filePath = imageFiles[i]; - Console.WriteLine($"Processing file: {filePath}"); + // 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 before attempting to read it + // Ensure the file still exists (it could have been removed after enumeration). if (!File.Exists(filePath)) { - Console.WriteLine("File does not exist."); + Console.WriteLine($"File not found: {filePath}"); continue; } - // Load the image and create a barcode reader configured for Australia Post barcodes - using (var bitmap = new Bitmap(filePath)) - using (var reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost)) + try { - // Apply specific settings required for Australia Post barcode interpretation - reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = true; - reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; - - // Iterate through all detected barcodes and output their details - foreach (var result in reader.ReadBarCodes()) + // 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)) { - Console.WriteLine($"BarCode Type: {result.CodeType}"); - Console.WriteLine($"BarCode CodeText: {result.CodeText}"); + // 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; + + bool found = false; + + // 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}"); + + // 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}"); + } + + // If no barcodes were detected, inform the user. + if (!found) + { + Console.WriteLine($"File: {Path.GetFileName(filePath)} - No AustraliaPost barcode detected."); + } } } + catch (Exception ex) + { + // Report any errors that occur while processing the file. + Console.WriteLine($"Error processing file '{Path.GetFileName(filePath)}': {ex.Message}"); + } + } + + // If no supported image files were found, notify the user. + if (!anyFileProcessed) + { + Console.WriteLine("No image files found in the specified folder."); } } } \ 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 9142de9..2160339 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,104 +1,82 @@ +// 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. +// 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 + using System; +using System.IO; using System.Text.Json; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; -namespace AustraliaPostBarcodeJsonDemo +namespace AustraliaPostBarcodeUtility { /// - /// Custom decoder implementing the Aspose interface. - /// This example simply maps digits 0‑9 to letters A‑J. + /// Custom decoder implementing the Aspose interface for Australia Post customer information. /// - public class SimpleCustomerInfoDecoder : AustraliaPostCustomerInformationDecoder + public class CustomCustomerInfoDecoder : AustraliaPostCustomerInformationDecoder { - /// - /// Decodes the supplied data by converting numeric characters to corresponding letters. - /// Non‑numeric characters are left unchanged. - /// - /// The raw customer information string. - /// The decoded string. - public string Decode(string data) + // Simple example: just return the raw bar values as decoded text. + public string Decode(string barValues) { - // Return empty string if input is null or empty - if (string.IsNullOrEmpty(data)) - return string.Empty; - - // Allocate a character array for the result - char[] result = new char[data.Length]; - - // Iterate over each character and apply the simple mapping - for (int i = 0; i < data.Length; i++) - { - char ch = data[i]; - if (ch >= '0' && ch <= '9') - { - // Map 0->A, 1->B, ..., 9->J - result[i] = (char)('A' + (ch - '0')); - } - else - { - // Preserve non‑numeric characters - result[i] = ch; - } - } - - // Convert the character array back to a string - return new string(result); + // In a real scenario, translate bar values (0‑3) to meaningful data here. + return barValues; } } + /// + /// Example utility that generates an Australia Post barcode, reads it using a custom decoder, + /// and outputs the decoded customer information as JSON. + /// class Program { /// - /// Entry point of the demo application. - /// Generates an Australia Post barcode, reads it back, applies a custom decoder, - /// and outputs the results as formatted JSON. + /// Entry point of the example. Generates a barcode, reads it, decodes customer info, + /// and prints the JSON representation to the console. /// static void Main() { - // Sample Australia Post barcode text (includes customer information part) - const string barcodeText = "5912345678AB"; + // Sample Australia Post barcode text (routing + identifier + customer info). + const string barcodeText = "5912345678ABCde"; - // Create a barcode generator for the Australia Post symbology + // Create the barcode generator for Australia Post symbology. using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, barcodeText)) { - // Set the interpreting type to CTable for demonstration purposes - generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable; + // Use CTable interpreting type for customer information. + generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable; - // Generate the barcode image + // Generate the barcode image in memory. using (var image = generator.GenerateBarCodeImage()) { - // Initialize a reader configured for Australia Post barcodes + // Set up the reader with the custom decoder. using (var reader = new BarCodeReader(image, DecodeType.AustraliaPost)) { - // Assign the custom decoder and interpreting type to the reader settings - reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder = new SimpleCustomerInfoDecoder(); + // Configure reader to use CTable and the custom decoder. reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; + reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder = new CustomCustomerInfoDecoder(); - // Perform barcode recognition - var results = reader.ReadBarCodes(); - - // Process each recognized barcode - foreach (var result in results) + // Perform recognition and process each detected barcode. + foreach (var result in reader.ReadBarCodes()) { - // Decode the raw code text using the custom decoder (demo purpose) - string decodedInfo = ((SimpleCustomerInfoDecoder)reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder) - .Decode(result.CodeText); + // Full code text from the barcode (may be null). + string fullCode = result.CodeText ?? string.Empty; + + // Extract the customer information part (after first 10 characters). + string customerInfoRaw = fullCode.Length > 10 ? fullCode.Substring(10) : string.Empty; - // Build an anonymous object for JSON serialization - var jsonObject = new - { - CodeText = result.CodeText, - DecodedCustomerInformation = decodedInfo, - InterpretingType = reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType.ToString() - }; + // Decode using the custom decoder. + string decodedInfo = ((CustomCustomerInfoDecoder)reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder) + .Decode(customerInfoRaw); - // Serialize the object to indented JSON - string json = JsonSerializer.Serialize(jsonObject, new JsonSerializerOptions { WriteIndented = true }); + // Convert decoded information to formatted JSON. + string json = JsonSerializer.Serialize( + new { CustomerInfo = decodedInfo }, + new JsonSerializerOptions { WriteIndented = true }); - // Output the JSON to the console + // Output the JSON to the console. Console.WriteLine(json); } } 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 9c38fac..1566cfe 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,5 +1,10 @@ +// 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. +// 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 + using System; -using System.IO; using System.Xml.Linq; using Aspose.BarCode; using Aspose.BarCode.Generation; @@ -7,59 +12,54 @@ using Aspose.Drawing; /// -/// Demonstrates generation, reading, and XML export of an Australia Post barcode using Aspose.BarCode. +/// Demonstrates converting decoded Australia Post barcode data to XML using a selected interpreting type. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, reads it back, and writes the result to an XML file. + /// Entry point of the utility. Generates a barcode, reads it, and outputs XML. /// - static void Main() + /// Command‑line arguments (not used). + static void Main(string[] args) { - // Sample Australia Post barcode data - string barcodeData = "5912345678AB"; + // Sample Australia Post barcode data (postal code + customer information) + string codeText = "5912345678ABCde"; - // Choose the interpreting type for customer information (CTable, NTable, Other) + // Choose the interpreting type for the customer information field CustomerInformationInterpretingType interpretingType = CustomerInformationInterpretingType.CTable; - // Create a barcode generator for Australia Post format - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, barcodeData)) + // Create a barcode generator for Australia Post symbology + using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText)) { // Apply the selected interpreting type to the generator settings generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = interpretingType; - // Generate the barcode image in memory - using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) + // Generate the barcode image as a bitmap + using (Bitmap bitmap = generator.GenerateBarCodeImage()) { - // Initialize a reader to decode the generated barcode image - using (var reader = new BarCodeReader(barcodeImage, DecodeType.AustraliaPost)) + // Initialize a barcode reader for Australia Post decoding + using (var reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost)) { - // Ensure the reader uses the same interpreting type as the generator + // Apply the same interpreting type to the reader settings reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = interpretingType; - // Iterate over all decoded barcode results (should be one in this case) - foreach (var result in reader.ReadBarCodes()) + // When using CTable, optionally ignore ending filling patterns + if (interpretingType == CustomerInformationInterpretingType.CTable) { - // Build an XML document representing the barcode data and interpreting type - XDocument xmlDoc = new XDocument( - new XElement("AustraliaPostBarcode", - new XElement("CodeText", result.CodeText), - new XElement("InterpretingType", interpretingType.ToString()) - ) - ); - - // Output the XML document to the console - Console.WriteLine(xmlDoc); - - // Define the output file path for the XML - string xmlPath = "AustraliaPostBarcode.xml"; + reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = true; + } - // Save the XML document to disk - xmlDoc.Save(xmlPath); + // Iterate over detected barcodes (only one expected in this example) + foreach (var result in reader.ReadBarCodes()) + { + // 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)); - // Inform the user where the XML file was saved - Console.WriteLine($"XML saved to {Path.GetFullPath(xmlPath)}"); + // Write the XML to the console + Console.WriteLine(xml); } } } 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 405aefa..269561d 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,55 +1,49 @@ +// 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. +// Prompt: Disable multithreaded barcode reading by setting ProcessorSettings.UseAllCores false and UseOnlyThisCoresCount to 1. +// Tags: barcode, multithreading, processor settings, code128, generation, recognition, aspose.barcode + using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates generating a barcode image, verifying its creation, -/// configuring single‑core processing, and reading the barcode back. +/// Demonstrates disabling multithreaded barcode reading using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. + /// Entry point. Generates a sample Code128 barcode if missing, configures single‑threaded processing, and reads the barcode. /// static void Main() { - // ------------------------------------------------------------ - // 1. Generate a sample barcode image and save it to a temp file. - // ------------------------------------------------------------ - string imagePath = Path.Combine(Path.GetTempPath(), "sample.png"); - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) - { - // Save the generated barcode as a PNG file. - generator.Save(imagePath); - } + // Define the path for the sample barcode image. + string imagePath = "sample_barcode.png"; - // ------------------------------------------------------------ - // 2. Verify that the barcode image was successfully created. - // ------------------------------------------------------------ + // Generate a sample barcode if it does not already exist on disk. if (!File.Exists(imagePath)) { - Console.WriteLine("Failed to create barcode image."); - return; + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + { + // Save the generated barcode as a PNG file. + generator.Save(imagePath, BarCodeImageFormat.Png); + } } - // ------------------------------------------------------------ - // 3. Configure the barcode reader to use a single CPU core. - // ------------------------------------------------------------ - BarCodeReader.ProcessorSettings.UseAllCores = false; // Disable automatic multi‑core usage. - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 1; // Restrict processing to one core. + // Configure the processor to use a single core (disable multithreading). + BarCodeReader.ProcessorSettings.UseAllCores = false; + BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 1; - // ------------------------------------------------------------ - // 4. Read and display barcode information from the generated image. - // ------------------------------------------------------------ - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Initialize the reader with the image and specify the expected barcode type. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.Code128)) { + // Iterate through all detected barcodes and output their details. foreach (var result in reader.ReadBarCodes()) { - // Output the type and decoded text of each detected barcode. Console.WriteLine($"Barcode Type: {result.CodeTypeName}"); - Console.WriteLine($"Barcode Text: {result.CodeText}"); + Console.WriteLine($"Code 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 9dc77a0..eb97d28 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,53 @@ +// 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. +// 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 + using System; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generation and recognition of an Australia Post barcode using Aspose.BarCode. +/// Demonstrates generating an Australia Post barcode in CTable mode and decoding it while suppressing filler "z" symbols. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, saves it to a file, then reads it back and displays the results. + /// Entry point of the example. Generates a barcode, saves it, and reads it back with specific settings. /// static void Main() { - // Define the output file path for the generated barcode image. - string imagePath = "australia_post.png"; - - // ------------------------------------------------- - // Generate an Australia Post barcode with CTable interpreting type. - // ------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678AB")) + // 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 encoding table. + // Configure the generator to use the CTable interpreting type generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable; - // Save the generated barcode image to the specified file. - generator.Save(imagePath); - } + // Save the generated barcode image to a file + generator.Save("AustraliaPost.png"); - // ------------------------------------------------- - // Recognize the previously generated barcode. - // Enable ignoring ending filling patterns for CTable. - // ------------------------------------------------- - using (var reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost)) - { - // Set the decoding interpreting type to CTable. - reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; + // Generate the barcode image in memory for immediate decoding + using (Bitmap image = generator.GenerateBarCodeImage()) + { + // Initialize a barcode reader for the generated image, targeting Australia Post symbology + using (BarCodeReader reader = new BarCodeReader(image, DecodeType.AustraliaPost)) + { + // Set the reader to interpret customer information using CTable + reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; - // Enable the flag to ignore filler "z" symbols at the end of the barcode. - reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = true; + // Enable suppression of ending filler patterns ("z") in CTable mode + reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = true; - // Iterate through all detected barcodes and output their details. - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"BarCode Type: {result.CodeType}"); - Console.WriteLine($"BarCode CodeText: {result.CodeText}"); + // Iterate through all detected barcodes and output their details + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine("BarCode Type: " + result.CodeTypeName); + Console.WriteLine("BarCode CodeText: " + 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 a12948b..283f2f0 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,3 +1,9 @@ +// 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. +// Prompt: Implement a custom class inheriting CustomerInformationDecoder and assign it to AustraliaPostSettings.CustomDecoder. +// Tags: barcode symbology, australia post, custom decoder, generation, recognition, aspnet.barcode + using System; using Aspose.BarCode; using Aspose.BarCode.Generation; @@ -7,66 +13,63 @@ namespace AustraliaPostCustomDecoderDemo { /// - /// Simple implementation of the interface. - /// Returns the raw data prefixed with "Decoded:" for demonstration purposes. + /// Custom decoder implementing the interface. + /// Returns the raw customer information field prefixed with "Decoded:". /// - public class SimpleCustomerInfoDecoder : AustraliaPostCustomerInformationDecoder + public class MyCustomerInfoDecoder : AustraliaPostCustomerInformationDecoder { /// - /// Decodes the supplied data by prefixing it with "Decoded:". + /// Decodes the supplied customer information field. /// - /// The raw data to decode. - /// The decoded string. - public string Decode(string data) + /// Raw field data from the barcode. + /// Decoded string prefixed with "Decoded:". + public string Decode(string customerInformationField) { - return $"Decoded:{data}"; + // In a real scenario, decode the bar values (0,1,2,3) into meaningful text. + return "Decoded:" + customerInformationField; } } /// - /// Demonstrates generating an Australia Post barcode, reading it, and using a custom decoder. + /// Demonstrates generation of an Australia Post barcode and reading it with a custom decoder. /// class Program { /// - /// Entry point of the demo application. + /// Generates an Australia Post barcode, saves it to a file, then reads it using a custom decoder. /// static void Main() { - // Sample code text for an Australia Post barcode. - const string codeText = "5912345678AB"; + const string outputFile = "australia_post.png"; - // Create a barcode generator for the Australia Post format. - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText)) + // Generate an Australia Post barcode with CTable interpreting type. + using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678AB")) { - // Set the interpreting type (optional, using CTable as an example). + // Set the encoding table for the customer information field. generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable; - // Generate the barcode image as a Bitmap. - using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) + // Create the barcode image and save it as PNG. + using (var image = generator.GenerateBarCodeImage()) { - // Initialize a BarCodeReader to recognize the generated image. - using (var reader = new BarCodeReader(barcodeImage, DecodeType.AustraliaPost)) - { - // Assign the custom decoder to the Australia Post settings. - reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder = new SimpleCustomerInfoDecoder(); + image.Save(outputFile, Aspose.Drawing.Imaging.ImageFormat.Png); + } + } - // Optionally set the interpreting type on the reader side as well. - reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; + // 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(); - // Perform barcode recognition and iterate over all detected barcodes. - foreach (var result in reader.ReadBarCodes()) - { - // Output the detected barcode type and raw code text. - Console.WriteLine($"BarCode Type: {result.CodeType}"); - Console.WriteLine($"BarCode CodeText: {result.CodeText}"); + // Ensure the interpreting type matches the generator's setting. + reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; - // Demonstrate using the custom decoder directly on the raw code text. - var decodedInfo = ((SimpleCustomerInfoDecoder)reader.BarcodeSettings.AustraliaPost.CustomerInformationDecoder) - .Decode(result.CodeText); - Console.WriteLine($"Custom Decoder Output: {decodedInfo}"); - } - } + // 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. } } } 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 7326e5a..1d77b6a 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,73 +1,57 @@ +// 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. +// Prompt: Implement a diagnostic tool that reports current ThreadPool thread counts before and after barcode processing. +// Tags: code128, generation, recognition, png, threadpool, diagnostics + using System; using System.IO; using System.Threading; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.BarCode; /// -/// Demonstrates barcode generation, reading, and ThreadPool usage reporting. +/// Provides a diagnostic demonstration of ThreadPool usage during barcode generation and recognition. /// class Program { /// - /// Writes the current ThreadPool usage statistics to the console. - /// - /// A label indicating the point in execution (e.g., "Before processing"). - static void ReportThreadPool(string stage) - { - // Retrieve maximum thread counts for worker and I/O threads. - ThreadPool.GetMaxThreads(out int maxWorker, out int maxIO); - // Retrieve currently available thread counts. - ThreadPool.GetAvailableThreads(out int availWorker, out int availIO); - // Calculate used threads by subtracting available from maximum. - int usedWorker = maxWorker - availWorker; - int usedIO = maxIO - availIO; - - // Output the usage information. - Console.WriteLine($"{stage} - ThreadPool usage:"); - Console.WriteLine($" Worker threads: used {usedWorker} / max {maxWorker}"); - Console.WriteLine($" IO threads: used {usedIO} / max {maxIO}"); - } - - /// - /// Application entry point. Generates a barcode, reads it back, reports ThreadPool usage, - /// and cleans up temporary files. + /// Entry point of the application. Generates a Code128 barcode, reads it back, and reports ThreadPool thread counts before and after processing. /// static void Main() { - // Report ThreadPool status before any processing. - ReportThreadPool("Before processing"); + // 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}"); - // Define a temporary file path for the barcode image. - string tempFile = Path.Combine(Path.GetTempPath(), "sample_barcode.png"); + // Define a temporary file path for the generated barcode image + string tempFile = Path.Combine(Path.GetTempPath(), "barcode.png"); - // ------------------------------------------------- - // Generate a barcode image and save it to the file. - // ------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Generate a simple Code128 barcode and save it as a PNG image + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - generator.Save(tempFile); + generator.Save(tempFile, BarCodeImageFormat.Png); } - // ------------------------------------------------- - // Read the barcode from the generated image. - // ------------------------------------------------- - using (var reader = new BarCodeReader(tempFile, DecodeType.Code128)) + // Initialize a barcode reader to decode the previously generated image + using (BarCodeReader reader = new BarCodeReader(tempFile, DecodeType.Code128)) { - foreach (var result in reader.ReadBarCodes()) + // 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 code text: {result.CodeText}"); + Console.WriteLine($"Detected barcode text: {result.CodeText}"); } } - // Report ThreadPool status after processing. - ReportThreadPool("After processing"); + // 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 file if it exists. - // ------------------------------------------------- + // Clean up the temporary barcode image file if (File.Exists(tempFile)) { try @@ -76,7 +60,7 @@ static void Main() } catch { - // Ignore any cleanup errors to avoid crashing the program. + // Suppress any exceptions during cleanup to avoid interrupting the diagnostic flow } } } 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 5c83bf5..b966f85 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,85 +1,106 @@ +// 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. +// 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# + using System; -using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode; /// -/// Demonstrates generating a Code128 barcode containing an FNC1 character, -/// then reading it with StripFNC enabled to observe behavior. +/// Example program that generates a barcode, enables StripFNC during reading, +/// and validates whether the barcode type supports FNC stripping. /// class Program { /// - /// Entry point of the sample application. - /// Generates a barcode, reads it with StripFNC, and outputs results. + /// Entry point of the example. Generates a barcode, configures the reader, + /// checks for FNC support, and decodes the barcode while handling possible errors. /// static void Main() { - // Prepare a temporary file path for the barcode image - string imagePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png"); - - // Create a Code128 barcode that contains an FNC1 character (ASCII 29) - // This symbology does not support StripFNC, so we expect handling of the case. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "\u001D12345")) - { - // Save the generated barcode image to the temporary path - generator.Save(imagePath); - } + // 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"; - // Verify the image was created successfully - if (!File.Exists(imagePath)) + // -------------------------------------------------------------------- + // Generate and save the barcode image. + // -------------------------------------------------------------------- + using (var generator = new BarcodeGenerator(barcodeType, originalCodeText)) { - Console.WriteLine("Failed to create barcode image."); - return; + generator.Save("barcode.png"); } - // Attempt to read the barcode with StripFNC enabled - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + // -------------------------------------------------------------------- + // Prepare the barcode reader with StripFNC enabled. + // -------------------------------------------------------------------- + using (var reader = new BarCodeReader("barcode.png", DecodeType.Code128)) { - // Enable stripping of FNC characters during decoding + // Enable stripping of FNC characters during decoding. reader.BarcodeSettings.StripFNC = true; - try + // List of symbologies that support FNC stripping. + BaseEncodeType[] fncSupported = new[] { - // Read all barcodes from the image - var results = reader.ReadBarCodes(); + EncodeTypes.GS1Code128, + EncodeTypes.GS1QR, + EncodeTypes.GS1DataMatrix, + EncodeTypes.GS1Aztec, + EncodeTypes.GS1HanXin, + EncodeTypes.GS1CompositeBar, + EncodeTypes.GS1DotCode, + EncodeTypes.GS1MicroPdf417, + EncodeTypes.QR, + EncodeTypes.DataMatrix, + EncodeTypes.Aztec + }; - // Process each decoding result - foreach (var result in results) + // ---------------------------------------------------------------- + // 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) { - // Determine whether the decoded text still contains the FNC character (ASCII 29) - bool containsFnc = result.CodeText != null && result.CodeText.Contains("\u001D"); - - if (containsFnc) + if (barcodeType.Equals(supported)) { - // The barcode type does not support StripFNC; report a warning - Console.WriteLine($"[Warning] Barcode type '{result.CodeTypeName}' does not support StripFNC. FNC characters remain in the code text."); - } - else - { - // StripFNC succeeded; display the cleaned code text - Console.WriteLine($"Barcode type: {result.CodeTypeName}"); - Console.WriteLine($"CodeText (FNC stripped): {result.CodeText}"); + isSupported = true; + break; } } + + 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."); + } + } + + // ---------------------------------------------------------------- + // 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) { - // Handle any unexpected errors, such as unsupported operation for StripFNC - Console.WriteLine($"Error during barcode reading: {ex.Message}"); - Console.WriteLine("The selected barcode type may not support StripFNC."); + Console.WriteLine($"Unexpected exception: {ex.Message}"); } } - - // Clean up the temporary image file - try - { - File.Delete(imagePath); - } - catch - { - // Ignored – file may be in use or already deleted - } } } \ 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 7e40906..bed1b0d 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,82 +1,72 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates barcode generation and reading with fallback from multithreaded to single‑threaded processing. +/// 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. /// class Program { /// - /// Entry point of the application. Generates a sample barcode image if missing and attempts to read it. + /// Entry point of the example. Generates a barcode, reads it with multithreading, + /// and retries with a single thread on failure. /// static void Main() { - const string imagePath = "sample_barcode.png"; - - // Ensure a barcode image exists; generate one if it does not. - if (!File.Exists(imagePath)) - { - // Create a barcode generator for Code128 with sample data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) - { - // Save the generated barcode to the specified path. - generator.Save(imagePath); - Console.WriteLine($"Generated barcode image: {imagePath}"); - } - } - - // Read the barcode using multithreaded processing, with fallback to single‑threaded if needed. - ReadWithFallback(imagePath); - } - - static void ReadWithFallback(string imagePath) - { - // Verify that the image file exists before attempting to read. - if (!File.Exists(imagePath)) - { - Console.WriteLine($"Image file not found: {imagePath}"); - return; - } - - // Attempt to decode using all available processor cores. - try + // Generate a sample QR barcode and keep it in memory + using (var ms = new MemoryStream()) { - // Configure the reader to use all cores. - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount; + var generator = new BarcodeGenerator(EncodeTypes.QR, "Sample fallback barcode"); + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; // Reset stream position for reading - // Initialize the barcode reader for all supported decode types. - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Load the image into a bitmap for recognition + using (var bitmap = new Bitmap(ms)) { - // Iterate through all detected barcodes and output their type and text. - foreach (var result in reader.ReadBarCodes()) + // Enable multi‑threaded processing (use all available CPU cores) + BarCodeReader.ProcessorSettings.UseAllCores = true; + + try { - Console.WriteLine($"[Multi] Type: {result.CodeTypeName}, Text: {result.CodeText}"); + // 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 (OutOfMemoryException) - { - // If memory limits are hit, fall back to single‑threaded decoding. - Console.WriteLine("Memory limit exceeded during multithreaded decoding. Switching to single‑thread mode."); + 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..."); - // Restrict processing to a single core. - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 1; + // Configure processor to use only one core + BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 1; - // Re‑initialize the reader in single‑thread mode. - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) - { - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"[Single] Type: {result.CodeTypeName}, Text: {result.CodeText}"); + // 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}"); + } + } } } } - catch (Exception ex) - { - // Handle any other exceptions that may occur during decoding. - Console.WriteLine($"Decoding failed: {ex.Message}"); - } } } \ 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 5059ba1..8f0567d 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,79 +1,66 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generating a Code128 barcode, saving it to a file, -/// and then attempting to read it with different StripFNC settings. +/// Demonstrates barcode generation and recognition with a fallback StripFNC setting. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode image, verifies its existence, - /// and tries to decode it using Aspose.BarCode with fallback logic. + /// Entry point. Generates a Code128 barcode, attempts to decode it, and retries with StripFNC enabled if needed. /// static void Main() { - const string imagePath = "barcode.png"; - - // ------------------------------------------------------------ - // Generate a sample barcode image and save it to disk. - // ------------------------------------------------------------ - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) - { - generator.Save(imagePath); - } - - // Verify that the barcode image was successfully created. - if (!File.Exists(imagePath)) + // Generate a Code128 barcode image in memory. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123")) { - Console.WriteLine("Barcode image not found."); - return; - } - - bool decoded = false; // Tracks whether decoding succeeded. - - // ------------------------------------------------------------ - // First decoding attempt: use default StripFNC = false. - // ------------------------------------------------------------ - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) - { - reader.BarcodeSettings.StripFNC = false; // Explicitly set to false for clarity. - var results = reader.ReadBarCodes(); - - if (results.Length > 0) + using (var ms = new MemoryStream()) { - decoded = true; // Mark as successfully decoded. - foreach (var result in results) - { - Console.WriteLine($"Decoded (first attempt): {result.CodeText}"); - } - } - } - - // ------------------------------------------------------------ - // Fallback decoding attempt: enable StripFNC if first attempt failed. - // ------------------------------------------------------------ - if (!decoded) - { - using (var fallbackReader = new BarCodeReader(imagePath, DecodeType.Code128)) - { - fallbackReader.BarcodeSettings.StripFNC = true; // Enable StripFNC for fallback. - var fallbackResults = fallbackReader.ReadBarCodes(); + // Save the generated barcode to the memory stream as PNG. + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; // Reset stream position for reading. - if (fallbackResults.Length > 0) + // Load the image from the stream into a Bitmap for recognition. + using (var bitmap = new Bitmap(ms)) { - foreach (var result in fallbackResults) + // Create a reader that supports all barcode types. + using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) { - Console.WriteLine($"Decoded (fallback with StripFNC): {result.CodeText}"); + // First attempt: do not strip Function Code (FNC) characters. + reader.BarcodeSettings.StripFNC = false; + var results = reader.ReadBarCodes(); + + // 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(); + + 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."); + } + } } } - else - { - Console.WriteLine("Failed to decode barcode even after fallback."); - } } } } 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 5ea958f..799349f 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,61 +1,73 @@ +// 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. +// 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 + using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Demonstrates configuring multithreaded barcode reading, generating a sample barcode image, -/// and reading the barcode using Aspose.BarCode library. +/// Sample console application that demonstrates a feature flag for enabling or disabling +/// multithreaded barcode reading using Aspose.BarCode's . /// class Program { /// - /// Entry point of the application. - /// Configures processor settings, optionally generates a sample barcode image, - /// and reads the barcode from the image. + /// Application entry point. Accepts an optional command‑line argument ("true" or "false") + /// to control whether barcode reading should use all CPU cores. /// - /// Command‑line arguments; use "disable" to turn off multithreading. + /// Command‑line arguments; first argument toggles multithreading. static void Main(string[] args) { - // Determine whether multithreaded barcode reading should be enabled. + // Determine whether multithreading is enabled via a feature flag. + // Default is true; can be overridden by a command‑line argument. bool enableMultithreading = true; - if (args.Length > 0 && args[0].Equals("disable", StringComparison.OrdinalIgnoreCase)) + 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)) { - enableMultithreading = false; + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + { + generator.Save(imagePath, BarCodeImageFormat.Png); + } } - // Apply processor settings based on the feature flag. + // Configure processor settings based on the feature flag. + // These settings affect all BarCodeReader instances. BarCodeReader.ProcessorSettings.UseAllCores = enableMultithreading; if (!enableMultithreading) { - // Restrict processing to a single core when multithreading is disabled. + // When multithreading is disabled, restrict processing to a single core. + BarCodeReader.ProcessorSettings.UseAllCores = false; BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 1; } - Console.WriteLine($"Multithreaded barcode reading enabled: {enableMultithreading}"); - - // Path to the sample barcode image. - const string imagePath = "sample.png"; - - // Generate the sample image if it does not already exist. + // Verify the image file exists before attempting to read. if (!File.Exists(imagePath)) { - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) - { - // Save the generated barcode as a PNG file. - generator.Save(imagePath, BarCodeImageFormat.Png); - } + Console.WriteLine($"Image file not found: {imagePath}"); + return; } - // Read the barcode from the image using the configured processor settings. + // Read the barcode using BarCodeReader. using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { foreach (var result in reader.ReadBarCodes()) { - // Output the detected barcode type and its decoded text. - Console.WriteLine($"Detected Type: {result.CodeTypeName}, CodeText: {result.CodeText}"); + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Code Text: {result.CodeText}"); + Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); } } } 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 4de84cc..dac5e84 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,3 +1,9 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode; @@ -5,82 +11,53 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates generating a GS1 Code128 barcode with FNC characters, -/// then reading it back with different StripFNC settings. +/// Demonstrates generating a GS1 Code128 barcode image and decoding it with and without stripping FNC characters. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode image, reads it with StripFNC on/off, - /// outputs the results, and cleans up the temporary file. + /// Entry point of the example. Generates the barcode if needed and performs two decoding runs, logging the results. /// static void Main() { - // -------------------------------------------------------------------- - // Prepare a temporary file path for the barcode image - // -------------------------------------------------------------------- - string tempDir = Path.GetTempPath(); - string barcodePath = Path.Combine(tempDir, "sample_barcode.png"); + // Path for the sample barcode image + const string imagePath = "sample_gs1code128.png"; + + // Sample GS1 Code128 text containing FNC characters (represented by parentheses) + const string codeText = "(02)04006664241007(37)1(400)7019590754"; - // -------------------------------------------------------------------- - // Generate a GS1 Code128 barcode that contains FNC characters - // -------------------------------------------------------------------- - using (var generator = new BarcodeGenerator( - EncodeTypes.GS1Code128, - "(02)04006664241007(37)1(400)7019590754")) + // Generate the barcode image if it does not exist + if (!File.Exists(imagePath)) { - // Save the barcode image to the file system - generator.Save(barcodePath); + 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}"); + } } - - // -------------------------------------------------------------------- - // Verify that the barcode image was created successfully - // -------------------------------------------------------------------- - if (!File.Exists(barcodePath)) + else { - Console.WriteLine($"Failed to create barcode image at '{barcodePath}'."); - return; + Console.WriteLine($"Using existing barcode image: {imagePath}"); } - // -------------------------------------------------------------------- - // Perform two decoding runs: one with StripFNC disabled, one with it enabled - // -------------------------------------------------------------------- - bool[] stripFncOptions = new bool[] { false, true }; + // Perform two decoding runs: one without stripping FNC, one with stripping FNC + bool[] stripFncOptions = new[] { false, true }; + foreach (bool stripFnc in stripFncOptions) { - using (var reader = new BarCodeReader(barcodePath, DecodeType.AllSupportedTypes)) + using (var reader = new BarCodeReader(imagePath, DecodeType.GS1Code128)) { - // Configure whether FNC symbols should be stripped from the decoded text + // Configure whether FNC characters should be stripped from the decoded text reader.BarcodeSettings.StripFNC = stripFnc; // Read all barcodes from the image - BarCodeResult[] results = reader.ReadBarCodes(); - - // Log the outcome of each decoding operation - foreach (var result in results) + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"StripFNC: {stripFnc}, CodeText: {result.CodeText}"); - } - - // If no barcodes were found, indicate that as well - if (results.Length == 0) - { - Console.WriteLine($"StripFNC: {stripFnc}, no barcode detected."); + // Log the decoding operation, indicating the StripFNC setting and decoded data + Console.WriteLine($"StripFNC = {stripFnc} | Detected Type: {result.CodeTypeName} | CodeText: {result.CodeText}"); } } } - - // -------------------------------------------------------------------- - // Clean up the temporary image file - // -------------------------------------------------------------------- - try - { - File.Delete(barcodePath); - } - catch - { - // Ignored – file deletion failure is non‑critical for this demo - } } } \ No newline at end of file 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 cd8b602..a4baae7 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,127 +1,112 @@ +// 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. +// Prompt: Implement a wrapper class that encapsulates ProcessorSettings configuration for easy reuse across projects. +// Tags: barcode symbology, generation, png, aspose.barcode, aspose.drawing + using System; -using Aspose.BarCode.Generation; using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.Drawing; -namespace BarcodeProcessorDemo +/// +/// Encapsulates common barcode generation settings for reuse across projects. +/// +public class ProcessorSettings { - /// - /// Holds common barcode generation settings and provides helper methods to apply them. - /// - public class ProcessorSettings - { - // Symbology to use (e.g., EncodeTypes.Code128). - public BaseEncodeType Symbology { get; set; } = EncodeTypes.Code128; - - // Text to encode. - public string CodeText { get; set; } = "Sample123"; + // Symbology type (e.g., Code128, QR, etc.) + public BaseEncodeType EncodeType { get; set; } - // Optional bar height (in points). Applies to 1D barcodes when AutoSizeMode is None. - public float? BarHeight { get; set; } + // Text to encode into the barcode + public string CodeText { get; set; } - // Optional X-dimension (module width) in points. - public float? XDimension { get; set; } - - // Optional checksum enable/disable. - public EnableChecksum? ChecksumEnabled { get; set; } - - // Optional image width/height when using AutoSizeMode.Interpolation or Nearest. - public float? ImageWidth { get; set; } - public float? ImageHeight { get; set; } - - // Optional auto-size mode. - public AutoSizeMode? AutoSizeMode { get; set; } - - // Optional colors. - public Color? BarColor { get; set; } - public Color? BackColor { get; set; } - - /// - /// Applies the stored settings to an existing instance. - /// - /// The generator to configure. - /// Thrown when is null. - public void Apply(BarcodeGenerator generator) - { - if (generator == null) throw new ArgumentNullException(nameof(generator)); + // Module size (x-dimension) in points; default 2f + public float XDimension { get; set; } = 2f; - // Set the text to encode. - generator.CodeText = CodeText; + // Height of 1D bars when AutoSize is disabled; default 40f + public float BarHeight { get; set; } = 40f; - // Apply optional numeric settings if they have values. - if (BarHeight.HasValue) - generator.Parameters.Barcode.BarHeight.Point = BarHeight.Value; + // Determines whether the generator should auto‑size the image + public bool AutoSize { get; set; } = false; - if (XDimension.HasValue) - generator.Parameters.Barcode.XDimension.Point = XDimension.Value; + // Foreground (bar) color; default black + public Color BarColor { get; set; } = Color.Black; - if (ChecksumEnabled.HasValue) - generator.Parameters.Barcode.IsChecksumEnabled = ChecksumEnabled.Value; + // Background color; default white + public Color BackColor { get; set; } = Color.White; - if (ImageWidth.HasValue) - generator.Parameters.ImageWidth.Point = ImageWidth.Value; + // Uniform padding around the barcode in points; default 5f + public float Padding { get; set; } = 5f; - if (ImageHeight.HasValue) - generator.Parameters.ImageHeight.Point = ImageHeight.Value; + /// + /// Applies the stored settings to the specified instance. + /// + /// The barcode generator to configure. + public void Apply(BarcodeGenerator generator) + { + if (generator == null) throw new ArgumentNullException(nameof(generator)); - // Apply optional enum settings. - if (AutoSizeMode.HasValue) - generator.Parameters.AutoSizeMode = AutoSizeMode.Value; + // Set the text to encode (fallback to empty string if null) + generator.CodeText = CodeText ?? string.Empty; - // Apply optional color settings. - if (BarColor.HasValue) - generator.Parameters.Barcode.BarColor = BarColor.Value; + // Configure X‑dimension (module size) + generator.Parameters.Barcode.XDimension.Point = XDimension; - if (BackColor.HasValue) - generator.Parameters.BackColor = BackColor.Value; + // Handle auto‑size mode and bar height + if (AutoSize) + { + generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; } - - /// - /// Creates a new with the configured symbology and applies all settings. - /// - /// A configured instance. - public BarcodeGenerator CreateGenerator() + else { - // Initialise generator with the selected symbology and code text. - var generator = new BarcodeGenerator(Symbology, CodeText); - // Apply all optional settings. - Apply(generator); - return generator; + 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 +class Program +{ + /// + /// Entry point demonstrating the use of with Aspose.BarCode. + /// + static void Main() { - /// - /// Entry point of the demo application. Generates a QR code using predefined settings. - /// - static void Main() + // Create a reusable settings instance with desired configuration + var settings = new ProcessorSettings { - // Define reusable processor settings. - var settings = new ProcessorSettings - { - Symbology = EncodeTypes.QR, - CodeText = "https://example.com", - XDimension = 2f, - ImageWidth = 300f, - ImageHeight = 300f, - AutoSizeMode = AutoSizeMode.Interpolation, - BarColor = Color.DarkBlue, - BackColor = Color.White - }; - - // Generate barcode using the wrapper. - using (var generator = settings.CreateGenerator()) - { - // Define output file path. - string outputPath = "barcode.png"; - - // Save the generated barcode image. - generator.Save(outputPath); - - // Inform the user where the file was saved. - Console.WriteLine($"Barcode saved to {outputPath}"); - } + 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)) + { + // 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}"); } } } \ 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 e16a3ee..68b59c8 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,49 +1,66 @@ +// 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. +// Prompt: Instantiate AustraliaPostSettings and assign it to BarCodeReader.RecognitionSettings for custom Australia Post decoding. +// Tags: australia post, barcode decoding, custom decoder, aspose.barcode, recognitionsettings + using System; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; -/// -/// Demonstrates generation and recognition of an Australia Post barcode using Aspose.BarCode. -/// -class Program +namespace AsposeBarcodeAustraliaPostDemo { + // Custom decoder implementing the AustraliaPostCustomerInformationDecoder interface + public class MyAustraliaPostDecoder : AustraliaPostCustomerInformationDecoder + { + // Simple implementation that returns a fixed string for demonstration + public string Decode(string barValues) + { + // In a real scenario, decode the barValues according to custom logic + return "CustomDecodedInfo"; + } + } + /// - /// Entry point of the application. - /// Generates a barcode, then reads it back and prints the results. + /// Demonstrates custom decoding of Australia Post barcodes using Aspose.BarCode. /// - static void Main() + class Program { - // Sample Australia Post barcode text to encode. - string codeText = "5912345678AB"; - - // Create a barcode generator for Australia Post format with the specified text. - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText)) + /// + /// Entry point that generates a sample barcode, configures custom decoding, and outputs results. + /// + static void Main() { - // Optional: set the encoding table for generation (CTable in this case). - generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable; - - // Generate the barcode image as a Bitmap. - using (Bitmap image = generator.GenerateBarCodeImage()) + // Generate a sample Australia Post barcode image + using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678AB")) { - // Initialize a barcode reader for the generated image, specifying Australia Post decoding. - using (var reader = new BarCodeReader(image, DecodeType.AustraliaPost)) - { - // Access and customize Australia Post specific decoding settings. - var australiaPostSettings = reader.BarcodeSettings.AustraliaPost; - // Use NTable for interpreting customer information during decoding. - australiaPostSettings.CustomerInformationInterpretingType = CustomerInformationInterpretingType.NTable; - // Ignore ending filling patterns when using CTable encoding. - australiaPostSettings.IgnoreEndingFillingPatternsForCTable = true; + // Use CTable interpreting type for the customer information field + generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable; - // Perform barcode recognition and iterate over all detected results. - foreach (var result in reader.ReadBarCodes()) + // Create the barcode image + using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) + { + // Initialize a reader for the generated image, specifying Australia Post decode type + using (var reader = new BarCodeReader(barcodeImage, DecodeType.AustraliaPost)) { - // Output the type of barcode detected. - Console.WriteLine($"Detected Type: {result.CodeType}"); - // Output the decoded text of the barcode. - Console.WriteLine($"Code Text: {result.CodeText}"); + // Access the AustraliaPost decoding settings + AustraliaPostSettings auPostSettings = reader.BarcodeSettings.AustraliaPost; + + // Assign a custom decoder implementation + auPostSettings.CustomerInformationDecoder = new MyAustraliaPostDecoder(); + + // Ensure the interpreting type matches the generation settings + auPostSettings.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; + + // Perform barcode 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 + } } } } 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 f79a2de..ba4fccd 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,44 +1,48 @@ +// 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. +// 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 + using System; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generation and reading of an Australia Post barcode using the CTable interpreting type. +/// Program demonstrating generation and CTable decoding of an Australia Post barcode. /// class Program { /// - /// Entry point of the application. Generates a barcode, saves it to a memory stream, - /// then reads and decodes it using the same interpreting type. + /// Entry point. Generates a barcode, decodes it using CTable interpreting type, and writes results to console. /// static void Main() { - // Create a barcode generator for Australia Post format with sample data. - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678AB")) + // Sample Australia Post barcode text (postal code + customer info) + const string codeText = "5912345678AB"; + + // Initialize a barcode generator for Australia Post symbology + using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText)) { - // Configure the generator to use the CTable encoding table. - generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable; + // Configure the generator to use CTable encoding for the customer information segment + generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable; - // Prepare a memory stream to hold the generated barcode image. - using (var ms = new MemoryStream()) + // Generate the barcode image in memory + using (Bitmap image = generator.GenerateBarCodeImage()) { - // Save the generated barcode as a PNG image into the memory stream. - generator.Save(ms, BarCodeImageFormat.Png); - // Reset stream position to the beginning for reading. - ms.Position = 0; - - // Initialize a barcode reader to decode the image from the memory stream. - using (var reader = new BarCodeReader(ms, DecodeType.AustraliaPost)) + // Create a barcode reader for the generated image, specifying Australia Post decoding + using (var reader = new BarCodeReader(image, DecodeType.AustraliaPost)) { - // Set the reader to interpret customer information using the CTable type. + // Set the reader to interpret the customer information using CTable format reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; - // Iterate through all decoded barcodes and output their text. + // Iterate through all decoded barcode results foreach (var result in reader.ReadBarCodes()) { - 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-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 13be81c..9dab69c 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,52 +1,62 @@ +// 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 + using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Demonstrates generation and recognition of an Australia Post barcode using NTable encoding. +/// Example program that generates an Australia Post barcode using the NTable encoding +/// and then decodes it with the same NTable interpreting type. /// class Program { /// - /// Entry point of the application. - /// Generates an Australia Post barcode, saves it to a file, and then reads it back. + /// Entry point of the example. Generates a barcode image, verifies its creation, + /// and reads the barcode back using NTable decoding settings. /// static void Main() { - // Sample Australia Post barcode data (digits only for NTable decoding) - string codeText = "5912345678"; - string imagePath = "australiapost.png"; + // Sample Australia Post barcode text (FCC 59, DPID 8 digits, no customer info) + string codeText = "5980123456"; + + // Output image path + string imagePath = "AustraliaPost_NTable.png"; - // ------------------------------------------------- - // Generate the barcode image with NTable encoding - // ------------------------------------------------- + // Generate the barcode with NTable encoding table using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText)) { - // Set the encoding table to NTable for Australian Post barcodes - generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.NTable; + // Set the encoding table to NTable for generation + generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.NTable; - // Save the generated barcode image to the specified path + // Save the barcode image to the specified path generator.Save(imagePath); } - // ------------------------------------------------- - // Read the barcode and set decoding to NTable format - // ------------------------------------------------- + // Verify that the image file was created successfully + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); + return; + } + + // Read and decode the barcode, setting the decoding interpreting type to NTable using (var reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost)) { - // Configure the reader to interpret customer information using NTable + // Apply NTable interpreting type for decoding reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.NTable; - // Iterate through all detected barcodes in the image - foreach (var result in reader.ReadBarCodes()) + // Iterate through detected barcodes and output their details + foreach (BarCodeResult result in reader.ReadBarCodes()) { - // Output the type of barcode detected - Console.WriteLine($"Detected Type: {result.CodeType}"); - - // Output the decoded text of the barcode - Console.WriteLine($"CodeText: {result.CodeText}"); + Console.WriteLine($"Detected Barcode Type: {result.CodeType}"); + Console.WriteLine($"Decoded 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 eb802b3..f2eaeb7 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,3 +1,9 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode; @@ -6,52 +12,49 @@ using Aspose.Drawing; /// -/// Demonstrates generation and reading of an Australia Post barcode using Aspose.BarCode with -/// CustomerInformationInterpretingType set to Other. +/// Generates an Australia Post barcode with custom customer information interpretation +/// and then reads it back using the same custom settings. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, saves it to a file, verifies the file, and then reads the barcode back. + /// Entry point of the example. Generates a barcode, saves it as PNG, + /// verifies the file, and reads the barcode using the Other interpreting type. /// static void Main() { - // Define sample barcode text (valid length for "Other" interpreting type) and output image path. - string codeText = "59123456780123012301230123"; - string imagePath = "AustraliaPost.png"; + // Sample barcode text (customer information part can be empty for Other interpreting type) + const string codeText = "59123456780123012301230123"; + const string imagePath = "AustraliaPost.png"; - // ---------- Barcode Generation ---------- - // Create a BarcodeGenerator for Australia Post format with the specified text. + // Generate Australia Post barcode with CustomerInformationInterpretingType set to Other using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText)) { - // Configure the generator to interpret customer information as "Other". + // Configure the generator to treat the customer information segment as 'Other' (no built‑in interpretation) generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.Other; - // Save the generated barcode image to the specified file. - generator.Save(imagePath); + // Save the generated barcode image in PNG format + generator.Save(imagePath, BarCodeImageFormat.Png); } - // ---------- Verify Image Creation ---------- - // Ensure the barcode image file was successfully created. + // Verify that the image file was created successfully if (!File.Exists(imagePath)) { - Console.WriteLine("Failed to create barcode image."); + Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); return; } - // ---------- Barcode Reading ---------- - // Initialize a BarCodeReader for the saved image, specifying Australia Post decode type. + // Initialize a reader for Australia Post barcodes using (var reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost)) { - // Set the decoding interpreting type to match the generation setting. + // Apply the same 'Other' interpreting type for decoding the customer information segment reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.Other; - // Iterate through all detected barcodes and output their type and text. + // Iterate through all recognized barcodes (should be one in this case) foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine("BarCode Type: " + result.CodeType); - Console.WriteLine("BarCode CodeText: " + result.CodeText); + Console.WriteLine($"BarCode Type: {result.CodeType}"); + Console.WriteLine($"BarCode CodeText: {result.CodeText}"); } } } 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 988d31a..33fcc44 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,63 +1,64 @@ +// 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. +// Prompt: Set BarCodeReader.StripFNC to false to remove FNC symbols from decoded results. +// Tags: gs1, code128, stripfnc, barcode decoding, aspose.barcode, image generation, png + using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.BarCode; /// -/// Demonstrates generating a GS1 Code128 barcode with FNC1 characters, -/// saving it to a temporary PNG file, reading it back while preserving -/// FNC characters, and cleaning up the temporary file. +/// 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. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, reads it, displays results, and deletes the temporary image. + /// Entry point of the example. Executes barcode generation, recognition, and cleanup. /// static void Main() { - // Define path for a temporary PNG file to store the generated barcode image - string tempImagePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png"); + // Define the full path for the generated barcode image. + string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "sample_barcode.png"); - // Generate a GS1 Code128 barcode containing FNC1 characters + // Create a GS1 Code128 barcode that includes FNC1 characters (represented by parentheses). using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, "(01)12345678901231(10)ABC123")) { - // Save the generated barcode image to the temporary file - generator.Save(tempImagePath); + // Save the barcode image to a PNG file. + generator.Save(imagePath, BarCodeImageFormat.Png); } - // Verify that the barcode image file was successfully created - if (!File.Exists(tempImagePath)) + // Verify that the image file was successfully created. + if (!File.Exists(imagePath)) { - Console.WriteLine("Failed to create barcode image."); + Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); return; } - // Initialize a barcode reader for Code128 and configure it to retain FNC characters - using (var reader = new BarCodeReader(tempImagePath, DecodeType.Code128)) + // Initialize a barcode reader for Code128 and configure it to retain FNC characters. + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - // Ensure FNC characters are not stripped during decoding + // According to the task, set StripFNC to false (do not strip FNC characters). reader.BarcodeSettings.StripFNC = false; - // Read all barcodes found in the image + // Iterate through all detected barcodes in the image. foreach (var result in reader.ReadBarCodes()) { - // Output the detected barcode type Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - // Output the decoded text with FNC characters retained - Console.WriteLine($"CodeText (FNC retained): {result.CodeText}"); + Console.WriteLine($"Decoded Text: {result.CodeText}"); } } - // Attempt to delete the temporary image file; ignore any exceptions + // Optional cleanup: delete the generated image file. try { - File.Delete(tempImagePath); + File.Delete(imagePath); } catch { - // Suppress any errors that occur during cleanup + // 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 59445d7..4246ee6 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,80 +1,55 @@ +// 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. +// 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 + using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Demonstrates generating a Code128 barcode containing an FNC1 character, -/// then reading it with and without stripping FNC symbols. +/// 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. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode image, reads it under two different settings, - /// and cleans up the temporary file. + /// Entry point of the example. Generates a barcode, saves it to disk, + /// and reads it back while preserving FNC symbols. /// static void Main() { - // -------------------------------------------------------------------- - // Prepare a temporary file path for the barcode image. - // -------------------------------------------------------------------- - string tempDir = Path.GetTempPath(); - string barcodePath = Path.Combine(tempDir, "sample_code128.png"); - - // -------------------------------------------------------------------- - // Build the Code128 text that includes an FNC1 character (ASCII 241). - // -------------------------------------------------------------------- - string codeText = "ABC" + ((char)241).ToString() + "123"; + // Path where the barcode image will be saved + string imagePath = "sample_barcode.png"; - // -------------------------------------------------------------------- - // Generate the barcode image and save it as PNG. - // -------------------------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // 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")) { - generator.Save(barcodePath, BarCodeImageFormat.Png); + // Save the generated barcode as a PNG file + generator.Save(imagePath, BarCodeImageFormat.Png); } - // -------------------------------------------------------------------- - // Read the barcode without stripping FNC symbols (default behavior). - // -------------------------------------------------------------------- - using (var reader = new BarCodeReader(barcodePath, DecodeType.Code128)) + // Ensure the barcode image was successfully created before attempting to read it + if (!File.Exists(imagePath)) { - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine("Without StripFNC (default):"); - Console.WriteLine($" CodeText: {result.CodeText}"); - } + Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); + return; } - // -------------------------------------------------------------------- - // Read the barcode with StripFNC set to true to retain FNC symbols. - // -------------------------------------------------------------------- - using (var reader = new BarCodeReader(barcodePath, DecodeType.Code128)) + // Initialize a reader for Code128 barcodes and configure it to retain FNC symbols + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - // Enable retaining FNC symbols in the decoded result. + // Set StripFNC to true so function characters are NOT stripped from the decoded text reader.BarcodeSettings.StripFNC = true; + // Iterate through all detected barcodes in the image foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine("With StripFNC = true:"); - Console.WriteLine($" CodeText: {result.CodeText}"); - } - } - - // -------------------------------------------------------------------- - // Clean up the temporary image file. - // -------------------------------------------------------------------- - if (File.Exists(barcodePath)) - { - try - { - File.Delete(barcodePath); - } - catch - { - // Ignore any errors that occur during cleanup. + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Decoded Text: {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 b509095..cd787b1 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,51 +1,46 @@ +// 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. +// Prompt: Set ProcessorSettings.MaxAdditionalAllowedThreads to 2 to cap extra worker threads for controlled multithreading. +// Tags: code128, generation, recognition, threading, aspose.barcode, processorsettings + using System; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates generating a Code128 barcode, saving it to a file, -/// and then reading it back using Aspose.BarCode library. +/// Demonstrates setting a thread limit for the barcode processor, generating a Code128 barcode, +/// and then reading the generated barcode using Aspose.BarCode APIs. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode image, verifies its creation, - /// configures processing threads, and reads the barcode. + /// 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. /// static void Main() { - // Define the output file path for the generated barcode image. - string outputPath = "sample.png"; + // Limit the number of additional worker threads the barcode processor may spawn. + BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = 2; - // Generate a simple Code128 barcode with the specified text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) - { - // Save the generated barcode image to the defined path. - generator.Save(outputPath); - } + // Define the output file path for the generated barcode image. + const string imagePath = "sample.png"; - // Verify that the barcode image was successfully created. - if (!File.Exists(outputPath)) + // Generate a Code128 barcode with the value "123456" and save it as a PNG file. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - Console.WriteLine("Failed to create barcode image."); - return; + generator.Save(imagePath); } - // Limit the number of additional worker threads used for barcode processing. - BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = 2; - - // Initialize a barcode reader for the saved image, supporting all barcode types. - using (var reader = new BarCodeReader(outputPath, DecodeType.AllSupportedTypes)) + // 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 the image. + // Iterate through all detected barcodes (in this case, just one) and display details. foreach (var result in reader.ReadBarCodes()) { - // Output the type and text of each detected barcode. - Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text: {result.CodeText}"); + Console.WriteLine($"Barcode Type: {result.CodeTypeName}"); + Console.WriteLine($"Barcode Text: {result.CodeText}"); } } } 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 866c35c..ac37f0b 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,47 +1,61 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates generating a Code128 barcode, storing it in memory, -/// and then reading it back using Aspose.BarCode library. +/// Example program that restricts barcode recognition to a specific number of CPU cores +/// and demonstrates barcode generation and reading using Aspose.BarCode. /// class Program { /// /// Entry point of the application. - /// Generates a barcode, writes it to a memory stream, - /// configures the reader to use a limited number of CPU cores, - /// and then reads and displays the barcode data. + /// Configures core usage, ensures a sample barcode image exists, and reads barcodes from it. /// static void Main() { - // Create a memory stream to hold the generated barcode image. - using (var memoryStream = new MemoryStream()) + // Restrict barcode recognition to four CPU cores + BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 4; + + // Path to the barcode image file + string imagePath = "sample_barcode.png"; + + // Generate a sample barcode image if it does not already exist + if (!File.Exists(imagePath)) { - // Generate a Code128 barcode with the text "123456". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Save the barcode image to the memory stream in PNG format. - generator.Save(memoryStream, BarCodeImageFormat.Png); + // Save the generated barcode as a PNG file + generator.Save(imagePath, BarCodeImageFormat.Png); } + } - // Reset the stream position to the beginning for reading. - memoryStream.Position = 0; + // Verify that the image file is present before attempting recognition + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image file not found: {imagePath}"); + return; + } - // Limit barcode recognition processing to use only 4 CPU cores. - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 4; + // Perform barcode recognition using the configured core count + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + { + // Apply a high‑performance quality preset for faster processing + reader.QualitySettings = QualitySettings.HighPerformance; - // Initialize a barcode reader for Code128 type using the memory stream. - using (var reader = new BarCodeReader(memoryStream, DecodeType.Code128)) + // Iterate through all detected barcodes and output their details + foreach (var result in reader.ReadBarCodes()) { - // Iterate through all detected barcodes in the stream. - foreach (var result in reader.ReadBarCodes()) - { - // Output the decoded text of each barcode to the console. - Console.WriteLine("Detected CodeText: " + result.CodeText); - } + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Code Text: {result.CodeText}"); + Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); } } } 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 c80014c..dcbe639 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,99 @@ +// 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. +// 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 + using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; -using Aspose.Drawing.Imaging; +using Aspose.BarCode.Common; /// -/// Demonstrates barcode generation and decoding performance -/// with Aspose.BarCode using different processor core settings. +/// Provides a simple benchmark that compares barcode decoding speed when +/// is enabled versus disabled. /// class Program { /// - /// Entry point of the application. - /// Generates sample barcodes, then measures decoding time - /// with UseAllCores enabled and disabled. + /// Entry point of the benchmark application. + /// Generates sample Code128 barcodes, runs two decoding measurements, + /// and writes the elapsed times to the console. /// static void Main() { - const int sampleCount = 5; // safe sample size for the runner - - // Generate a collection of barcode images stored as byte arrays. - List barcodeImages = GenerateSampleBarcodes(sampleCount); + // -------------------------------------------------------------------- + // 1. Generate a collection of in‑memory barcode images (PNG format) + // -------------------------------------------------------------------- + List barcodeStreams = new List(); + for (int i = 0; i < 5; 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); + } + } - // Benchmark decoding with all processor cores enabled. + // --------------------------------------------------------------- + // 2. Measure decoding time with multi‑core processing enabled + // --------------------------------------------------------------- BarCodeReader.ProcessorSettings.UseAllCores = true; - TimeSpan timeAllCores = MeasureDecodingTime(barcodeImages); - Console.WriteLine($"Decoding with UseAllCores = true: {timeAllCores.TotalMilliseconds} ms"); + double timeAllCores = MeasureDecodingTime(barcodeStreams); - // Benchmark decoding with only a single core used. + // --------------------------------------------------------------- + // 3. Measure decoding time with single‑core processing + // --------------------------------------------------------------- BarCodeReader.ProcessorSettings.UseAllCores = false; - TimeSpan timeSingleCore = MeasureDecodingTime(barcodeImages); - Console.WriteLine($"Decoding with UseAllCores = false: {timeSingleCore.TotalMilliseconds} ms"); - } + double timeSingleCore = MeasureDecodingTime(barcodeStreams); - /// - /// Generates a list of barcode images (PNG) stored as byte arrays. - /// - /// Number of barcodes to generate. - /// List of byte arrays, each representing a PNG barcode image. - private static List GenerateSampleBarcodes(int count) - { - var images = new List(); + // --------------------------------------------------------------- + // 4. Output benchmark results + // --------------------------------------------------------------- + Console.WriteLine($"Decoding time with UseAllCores = true : {timeAllCores} ms"); + Console.WriteLine($"Decoding time with UseAllCores = false: {timeSingleCore} ms"); - // Create each barcode image and add its byte representation to the list. - for (int i = 0; i < count; i++) + // --------------------------------------------------------------- + // 5. Release all memory streams + // --------------------------------------------------------------- + foreach (MemoryStream ms in barcodeStreams) { - string codeText = $"Sample{i}"; - - // Initialize a barcode generator for Code128 with the specified text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) - { - // Save the generated barcode to a memory stream in PNG format. - using (var ms = new MemoryStream()) - { - generator.Save(ms, BarCodeImageFormat.Png); - images.Add(ms.ToArray()); // Store the image bytes. - } - } + ms.Dispose(); } - - return images; } /// - /// Measures the total time required to decode all provided barcode images. + /// Measures the total time required to decode a list of barcode image streams. /// - /// List of barcode image byte arrays to decode. - /// Elapsed time as a . - private static TimeSpan MeasureDecodingTime(List images) + /// The collection of barcode image streams to decode. + /// Total elapsed time in milliseconds. + private static double MeasureDecodingTime(List streams) { - var stopwatch = Stopwatch.StartNew(); + Stopwatch sw = Stopwatch.StartNew(); - // Iterate over each image and decode its barcode(s). - foreach (var imgData in images) + foreach (MemoryStream ms in streams) { - // Load the image bytes into a memory stream for the reader. - using (var ms = new MemoryStream(imgData)) + // Ensure the stream is positioned at the beginning before each read + ms.Position = 0; + + // Initialize a reader that supports all barcode types + using (BarCodeReader reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes)) { - // Initialize the barcode reader for all supported types. - using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes)) + // Iterate through all detected barcodes (results are ignored) + foreach (var result in reader.ReadBarCodes()) { - // ReadBarCodes returns an array of results; iterate to ensure processing. - foreach (var result in reader.ReadBarCodes()) - { - // Access result properties to simulate work; output can be omitted. - Console.WriteLine($"Decoded: {result.CodeText}"); - } + // No additional processing required; iteration forces decoding } } } - stopwatch.Stop(); - return stopwatch.Elapsed; + sw.Stop(); + return sw.Elapsed.TotalMilliseconds; } } \ 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 24b2687..99f1a8a 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,96 +1,87 @@ +// 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. +// 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 + 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.Drawing.Imaging; /// -/// Demonstrates benchmarking of barcode recognition using Aspose.BarCode. -/// Generates sample barcodes, measures recognition time in single‑ and multi‑threaded modes, -/// and outputs the results to the console. +/// Demonstrates benchmarking barcode recognition with different thread settings. /// class Program { /// - /// Application entry point. - /// Generates a set of barcode images, runs recognition benchmarks, and disposes resources. + /// Entry point. Generates sample barcodes, runs single‑ and multi‑thread benchmarks, and outputs elapsed times. /// static void Main() { - // Create a small collection of barcode images held in memory. - var barcodeStreams = GenerateSampleBarcodes(5); - - // Benchmark single‑threaded processing (no additional threads allowed). - BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = 0; - long singleThreadMs = MeasureRecognitionTime(barcodeStreams); - Console.WriteLine($"Single‑threaded recognition time: {singleThreadMs} ms"); + const int sampleCount = 5; + var barcodeStreams = new List(); - // Benchmark multi‑threaded processing (allow as many extra threads as there are processors). - BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = Environment.ProcessorCount; - long multiThreadMs = MeasureRecognitionTime(barcodeStreams); - Console.WriteLine($"Multi‑threaded recognition time: {multiThreadMs} ms"); - - // Release all memory streams. - foreach (var ms in barcodeStreams) + // Generate sample barcode images in memory + for (int i = 0; i < sampleCount; i++) { - ms.Dispose(); - } - } - - // Generates the specified number of Code128 barcode images and returns them as MemoryStreams. - private static List GenerateSampleBarcodes(int count) - { - var streams = new List(); - - for (int i = 0; i < count; i++) - { - var ms = new MemoryStream(); - - // Use a unique code text for each image (e.g., CODE0001, CODE0002, ...). - string codeText = $"CODE{i + 1:D4}"; - - // Create a barcode generator for Code128 and save the image directly into the stream. + 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); } - - // Reset the stream position so it can be read from the beginning. - ms.Position = 0; - streams.Add(ms); } - return streams; + // Benchmark with single‑thread (MaxAdditionalAllowedThreads = 0) + long singleThreadTicks = RunBenchmark(barcodeStreams, 0); + Console.WriteLine($"Single‑thread elapsed: {TimeSpan.FromTicks(singleThreadTicks).TotalMilliseconds} 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"); + + // Clean up streams + foreach (var ms in barcodeStreams) + { + ms.Dispose(); + } } - // Measures the total time (in milliseconds) required to recognize all barcodes in the provided streams. - private static long MeasureRecognitionTime(List streams) + /// + /// 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) { + // Configure processor settings + BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = maxAdditionalThreads; + var stopwatch = Stopwatch.StartNew(); - foreach (var ms in streams) + foreach (var stream in streams) { - // Create a new reader for each stream; it is disposed automatically after use. - using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes)) + // Ensure the stream is positioned at the beginning for each read + stream.Position = 0; + using (var reader = new BarCodeReader(stream, DecodeType.Code128)) { - // ReadBarCodes returns an array of detection results. - var results = reader.ReadBarCodes(); - - // Output each detected barcode to the console (prevents compiler optimizations from removing the call). - foreach (var result in results) + // Perform recognition + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Detected: {result.CodeTypeName} - {result.CodeText}"); + // Access result to ensure processing (no output needed) + var _ = result.CodeText; } } - - // Reset the stream position for the next iteration/read. - ms.Position = 0; } stopwatch.Stop(); - return stopwatch.ElapsedMilliseconds; + return stopwatch.ElapsedTicks; } } \ 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 2d92392..11e148e 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,51 +1,59 @@ +// 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. +// 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 + using System; -using System.Collections.Generic; -using System.Diagnostics; using System.IO; -using Aspose.BarCode; +using System.Diagnostics; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates generating barcode images, reading them, and measuring CPU usage. +/// Example program that generates a set of Code128 barcodes, reads them using +/// multi‑core processing, and records CPU usage statistics for the operation. /// class Program { /// - /// Entry point of the application. + /// Entry point. Generates temporary barcode images, enables multi‑core reading, + /// measures CPU and wall‑clock time, outputs results, and cleans up. /// static void Main() { // -------------------------------------------------------------------- - // Prepare a temporary directory for barcode images + // Prepare a temporary folder for barcode images // -------------------------------------------------------------------- - string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarCodeSample"); - if (!Directory.Exists(tempDir)) + string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodes"); + if (!Directory.Exists(tempFolder)) { - Directory.CreateDirectory(tempDir); + Directory.CreateDirectory(tempFolder); } // -------------------------------------------------------------------- - // Generate a small set of barcode images (5 items) + // Define sample data to encode and allocate array for image paths // -------------------------------------------------------------------- - List imagePaths = new List(); - for (int i = 0; i < 5; i++) - { - // Build the full file path for the current barcode image - string filePath = Path.Combine(tempDir, $"barcode_{i}.png"); + string[] sampleTexts = new string[] { "ABC123", "DEF456", "GHI789", "JKL012", "MNO345" }; + string[] imagePaths = new string[sampleTexts.Length]; - // Create a barcode generator for Code128 with a unique text value - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"CODE{i}")) + // -------------------------------------------------------------------- + // Generate barcode images using BarcodeGenerator + // -------------------------------------------------------------------- + for (int i = 0; i < sampleTexts.Length; i++) + { + string filePath = Path.Combine(tempFolder, $"barcode_{i}.png"); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, sampleTexts[i])) { - // Enable checksum calculation for the barcode - generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; - - // Save the generated barcode image to disk + // Simple visual settings + generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + generator.Parameters.ImageWidth.Point = 300f; + generator.Parameters.ImageHeight.Point = 100f; generator.Save(filePath); } - - // Store the path for later processing - imagePaths.Add(filePath); + imagePaths[i] = filePath; } // -------------------------------------------------------------------- @@ -54,50 +62,51 @@ static void Main() BarCodeReader.ProcessorSettings.UseAllCores = true; // -------------------------------------------------------------------- - // Record CPU usage before processing + // Record CPU usage and wall‑clock time before processing // -------------------------------------------------------------------- Process currentProcess = Process.GetCurrentProcess(); TimeSpan cpuStart = currentProcess.TotalProcessorTime; + Stopwatch wallClock = Stopwatch.StartNew(); // -------------------------------------------------------------------- - // Process each image and read barcodes + // Read each generated barcode image // -------------------------------------------------------------------- foreach (string path in imagePaths) { - // Verify that the file exists before attempting to read it if (!File.Exists(path)) { Console.WriteLine($"File not found: {path}"); continue; } - // Initialize a barcode reader for all supported types - using (var reader = new BarCodeReader(path, DecodeType.AllSupportedTypes)) + using (var reader = new BarCodeReader(path)) { // Iterate through all detected barcodes in the image foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine( - $"Image: {Path.GetFileName(path)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); + Console.WriteLine($"File: {Path.GetFileName(path)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); } } } // -------------------------------------------------------------------- - // Record CPU usage after processing + // Stop timing and calculate CPU usage statistics // -------------------------------------------------------------------- - currentProcess.Refresh(); + wallClock.Stop(); TimeSpan cpuEnd = currentProcess.TotalProcessorTime; + TimeSpan cpuUsed = cpuEnd - cpuStart; // -------------------------------------------------------------------- - // Compute and display CPU time consumed + // Output performance metrics // -------------------------------------------------------------------- - TimeSpan cpuUsed = cpuEnd - cpuStart; - Console.WriteLine( - $"CPU time used for processing {imagePaths.Count} images: {cpuUsed.TotalMilliseconds} ms"); + 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 files + // Clean up temporary barcode image files // -------------------------------------------------------------------- foreach (string path in imagePaths) { @@ -107,18 +116,13 @@ static void Main() } catch { - // Ignore any deletion errors (e.g., file in use) + // Ignore any deletion errors } } - // Attempt to delete the temporary directory - try - { - Directory.Delete(tempDir); - } - catch - { - // Ignore any deletion errors (e.g., directory not empty) - } + // -------------------------------------------------------------------- + // Reset processor settings (optional) + // -------------------------------------------------------------------- + BarCodeReader.ProcessorSettings.UseAllCores = false; } } \ 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 d1424f6..4f84af9 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,81 +1,66 @@ +// 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. +// Prompt: Write code that switches AustraliaPostSettings.CustomerInformationInterpretingType at runtime based on user selection. +// Tags: barcode symbology, australia post, runtime configuration, generation, recognition, aspose.barcode + using System; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; -using Aspose.Drawing.Imaging; +/// +/// Example program that switches AustraliaPostSettings.CustomerInformationInterpretingType at runtime, +/// generates an Australia Post barcode, and then reads it back using the same interpreting type. +/// class Program { - static void Main() + /// + /// Entry point. Accepts an optional command‑line argument specifying the desired CustomerInformationInterpretingType. + /// + /// Command‑line arguments; first argument should be a valid CustomerInformationInterpretingType value. + static void Main(string[] args) { - var samples = new (CustomerInformationInterpretingType Type, string CodeText, string FileName)[] + // 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)) + { + interpretingType = parsed; + } + else { - (CustomerInformationInterpretingType.CTable, "5912345678ABCde", "AustraliaPost_CTable.png"), - (CustomerInformationInterpretingType.NTable, "4512345678", "AustraliaPost_NTable.png"), - (CustomerInformationInterpretingType.Other, "6212", "AustraliaPost_Other.png") - }; + interpretingType = CustomerInformationInterpretingType.Other; + } - foreach (var sample in samples) + // 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)) { - if (!IsValidForInterpretingType(sample.Type, sample.CodeText)) - { - Console.WriteLine($"Skipping generation for {sample.Type}: invalid code text \"{sample.CodeText}\"."); - continue; - } + // Apply the runtime interpreting type to the generator settings. + generator.Parameters.Barcode.AustralianPost.EncodingTable = interpretingType; - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost)) - { - generator.Parameters.Barcode.AustralianPost.EncodingTable = sample.Type; - generator.CodeText = sample.CodeText; - generator.Save(sample.FileName, BarCodeImageFormat.Png); - Console.WriteLine($"Saved barcode image: {sample.FileName}"); - } + const string imagePath = "AustraliaPost.png"; + + // Save the generated barcode image to disk. + generator.Save(imagePath); + Console.WriteLine($"Barcode generated with CustomerInformationInterpretingType = {interpretingType}"); + Console.WriteLine($"Image saved to: {imagePath}"); - using (Bitmap image = (Bitmap)Image.FromFile(sample.FileName)) - using (BarCodeReader reader = new BarCodeReader(image, DecodeType.AustraliaPost)) + // Recognize the barcode and apply the same interpreting type for decoding. + using (var reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost)) { - reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = sample.Type; + // Configure the reader to use the same interpreting type as the generator. + reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = interpretingType; + + // Iterate through all detected barcodes (should be one) and output details. foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine($"Decoded [{sample.Type}] - Type: {result.CodeType}, CodeText: {result.CodeText}"); + Console.WriteLine($"Decoded Type: {result.CodeType}"); + Console.WriteLine($"Decoded Text: {result.CodeText}"); } } } } - - static bool IsValidForInterpretingType(CustomerInformationInterpretingType type, string text) - { - switch (type) - { - case CustomerInformationInterpretingType.CTable: - foreach (char c in text) - { - if (!(char.IsLetterOrDigit(c) || c == ' ' || c == '#')) - return false; - } - return true; - - case CustomerInformationInterpretingType.NTable: - foreach (char c in text) - { - if (!char.IsDigit(c)) - return false; - } - return true; - - case CustomerInformationInterpretingType.Other: - if (text.Length > 3) - return false; - foreach (char c in text) - { - if (c < '0' || c > '3') - return false; - } - return true; - - default: - return false; - } - } } \ No newline at end of file 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 4c0d6b0..0eec269 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,69 +1,89 @@ +// 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. +// Prompt: Write a configuration loader that reads ProcessorSettings values from a JSON file at application startup. +// Tags: processor settings, configuration, json, aspose.barcode, barcodereader + using System; using System.IO; using System.Text.Json; using Aspose.BarCode.BarCodeRecognition; /// -/// Represents the configuration settings for processor cores. +/// Represents the processor configuration that can be loaded from a JSON file. /// -class ProcessorSettingsConfig +class ProcessorConfig { - /// - /// Gets or sets the number of cores to be used by the processor. - /// - public int UseOnlyThisCoresCount { get; set; } + // 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 from a JSON file -/// and applies them to the Aspose.BarCode BarCodeReader. +/// Entry point of the application that loads processor settings and applies them to Aspose.BarCode. /// class Program { /// - /// Main method that orchestrates reading the configuration and applying it. + /// Application startup method. Loads configuration, applies settings, and reports the applied values. /// static void Main() { - // Path to the JSON configuration file const string configPath = "processorSettings.json"; - // Verify that the configuration file exists before attempting to read it - if (!File.Exists(configPath)) - { - Console.WriteLine($"Configuration file not found: {configPath}"); - return; - } + // Load configuration from JSON file (or use defaults if missing/invalid). + ProcessorConfig config = LoadConfig(configPath); - // Read the entire JSON content from the file - string json = File.ReadAllText(configPath); - ProcessorSettingsConfig? config; + // Apply the loaded settings to the Aspose.BarCode processor. + ApplyProcessorSettings(config); - // Attempt to deserialize the JSON into a ProcessorSettingsConfig instance - try - { - config = JsonSerializer.Deserialize(json); - } - catch (Exception ex) + // Output the effective processor settings. + Console.WriteLine( + $"ProcessorSettings applied: UseAllCores={BarCodeReader.ProcessorSettings.UseAllCores}, " + + $"UseOnlyThisCoresCount={BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}"); + } + + /// + /// Reads the processor configuration from the specified JSON file. + /// + /// Path to the JSON configuration file. + /// A instance populated with values from the file or defaults. + static ProcessorConfig LoadConfig(string path) + { + if (!File.Exists(path)) { - // Output any parsing errors and abort execution - Console.WriteLine($"Failed to parse configuration: {ex.Message}"); - return; + // Config file missing; fall back to default settings. + return new ProcessorConfig(); } - // Ensure that deserialization produced a non‑null object - if (config == null) + // Open the file for reading within a using block to ensure proper disposal. + using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { - Console.WriteLine("Configuration is empty or invalid."); - return; + try + { + // Deserialize JSON into ProcessorConfig; handle null result gracefully. + ProcessorConfig? cfg = JsonSerializer.Deserialize(stream); + return cfg ?? new ProcessorConfig(); + } + catch (JsonException ex) + { + // Invalid JSON format; log the error and use default settings. + Console.WriteLine($"Error parsing config: {ex.Message}"); + return new ProcessorConfig(); + } } + } - // Apply the deserialized settings to the Aspose.BarCode BarCodeReader processor - // ProcessorSettings is a static property of BarCodeReader that controls core usage + /// + /// 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; - - // Confirm successful loading and display the applied setting - Console.WriteLine("Processor settings loaded successfully."); - Console.WriteLine($"UseOnlyThisCoresCount = {BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}"); } } \ 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 a59430f..bd582f7 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,64 +1,99 @@ +// 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. +// 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 + using System; -using System.Collections.Generic; +using System.IO; using System.Threading; +using Aspose.BarCode; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; -namespace BarcodeThreadPoolHelper +/// +/// Sample program demonstrating barcode generation, reading, and ThreadPool configuration. +/// +class Program { /// - /// Demonstrates configuring the ThreadPool based on a list of barcode files - /// and simulating processing of each file. + /// Entry point. Generates sample barcodes if needed, configures ThreadPool, and reads each barcode. /// - class Program + static void Main() { - /// - /// Entry point of the application. - /// - static void Main() + // Directory to hold sample barcode images + const string barcodeDir = "Barcodes"; + + // Ensure the directory exists and contains a few sample files + if (!Directory.Exists(barcodeDir)) { - // Define a sample list of barcode file paths (replace with real paths as needed) - var barcodeFiles = new List - { - "barcode1.png", - "barcode2.png", - "barcode3.png" - }; + 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 the ThreadPool's minimum worker threads based on the number of files - ConfigureThreadPoolMinThreads(barcodeFiles.Count); + // Configure ThreadPool based on the number of files to process + ConfigureThreadPool(barcodeFiles.Length); - // Iterate over each file and simulate processing (real barcode logic would go here) - foreach (var file in barcodeFiles) + // Process each barcode file: read and output its type and text + foreach (string filePath in barcodeFiles) + { + using (var reader = new BarCodeReader(filePath)) { - // Output which file is being processed and on which thread - Console.WriteLine($"Processing {file} on thread {Thread.CurrentThread.ManagedThreadId}"); - // Placeholder for barcode generation/recognition logic + foreach (var result in reader.ReadBarCodes()) + { + Console.WriteLine($"File: {Path.GetFileName(filePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); + } } - - // Indicate that all files have been processed - Console.WriteLine("All barcode files processed."); } - /// - /// Sets the ThreadPool minimum worker threads to at least the number of barcode files. - /// - /// Number of barcode files to be processed. - static void ConfigureThreadPoolMinThreads(int barcodeFileCount) + // 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)); + + for (int i = 1; i <= count; i++) { - // Validate input to ensure a non‑negative file count - if (barcodeFileCount < 0) - throw new ArgumentOutOfRangeException(nameof(barcodeFileCount), "File count cannot be negative."); + 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); + } + } + } - // Retrieve the current minimum thread settings from the ThreadPool - ThreadPool.GetMinThreads(out int currentWorkerThreads, out int completionPortThreads); + // Adjusts the ThreadPool's minimum worker threads based on workload size. + private static void ConfigureThreadPool(int fileCount) + { + if (fileCount < 0) throw new ArgumentOutOfRangeException(nameof(fileCount)); - // Determine the desired number of worker threads (at least as many as files) - int desiredWorkerThreads = Math.Max(currentWorkerThreads, barcodeFileCount); + // Retrieve current minimum thread settings. + ThreadPool.GetMinThreads(out int currentWorkerMin, out int currentCompletionPortMin); - // Apply the new minimum settings; completion port threads remain unchanged - bool result = ThreadPool.SetMinThreads(desiredWorkerThreads, completionPortThreads); + // 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)); - // Report the outcome of the ThreadPool configuration - Console.WriteLine($"ThreadPool minimum worker threads set to {desiredWorkerThreads}: {(result ? "Success" : "Failed")}"); + // 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}."); } } } \ 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 2e82eaa..233b03f 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,118 +1,98 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generating QR codes with FNC1 symbols and reading them -/// with and without stripping the FNC characters using Aspose.BarCode. +/// 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. /// class Program { /// - /// Entry point of the application. - /// Generates QR barcodes, saves them to disk, and reads them back - /// demonstrating the effect of the StripFNC setting. + /// Entry point of the example. Generates a barcode image, then reads it twice: + /// once with the default StripFNC behavior and once with StripFNC enabled. /// static void Main() { // -------------------------------------------------------------------- - // Prepare output directory for generated barcode images + // Prepare output directory // -------------------------------------------------------------------- - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output"); if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } // -------------------------------------------------------------------- - // Define descriptions for the two barcode variants and allocate array - // to hold the file paths of the generated images + // Define barcode parameters // -------------------------------------------------------------------- - string[] descriptions = { "FNC1_FirstPosition", "FNC1_SecondPosition" }; - string[] filePaths = new string[descriptions.Length]; + string filePath = Path.Combine(outputDir, "gs1code128.png"); + // Sample GS1 Code128 data containing FNC1 (parentheses) delimiters + string codeText = "(02)04006664241007(37)1(400)7019590754"; // -------------------------------------------------------------------- - // Generate each QR barcode variant + // Generate barcode with embedded FNC characters (GS1 Code128) // -------------------------------------------------------------------- - for (int i = 0; i < descriptions.Length; i++) + using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, codeText)) { - // Build extended codetext using QrExtCodetextBuilder - var builder = new QrExtCodetextBuilder(); + // Basic appearance settings + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - if (i == 0) - { - // Variant 1: FNC1 placed in the first position, followed by plain data - builder.AddFNC1FirstPosition(); - builder.AddPlainCodetext("DATA123"); - } - else - { - // Variant 2: FNC1 placed in the second position with value "12" - builder.AddFNC1SecondPosition("12"); - builder.AddPlainCodetext("MOREDATA"); - } + // Size settings + generator.Parameters.AutoSizeMode = AutoSizeMode.None; + generator.Parameters.Barcode.BarHeight.Point = 50f; + generator.Parameters.Barcode.XDimension.Point = 2f; - // Retrieve the full extended codetext string - string extendedCode = builder.GetExtendedCodetext(); + // Disable filled bars to keep thin lines + generator.Parameters.Barcode.FilledBars = false; - // Define the output file path for the current barcode image - string filePath = Path.Combine(outputDir, $"{descriptions[i]}.png"); + // Prevent exceptions on automatic correction of the code text + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; - // Generate the QR barcode image using the extended codetext - using (var generator = new BarcodeGenerator(EncodeTypes.QR, extendedCode)) - { - // Set QR encoding mode to Extended to support FNC1 symbols - generator.Parameters.Barcode.QR.EncodeMode = QREncodeMode.Extended; - // Use low error correction level (Level L) - generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelL; - // Save the generated barcode as a PNG file - generator.Save(filePath, BarCodeImageFormat.Png); - } + // 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; - // Store the generated file path for later reading - filePaths[i] = filePath; - Console.WriteLine($"Generated barcode: {filePath}"); + // Save the generated barcode image as PNG + generator.Save(filePath, BarCodeImageFormat.Png); } + Console.WriteLine($"Barcode image saved to: {filePath}"); + // -------------------------------------------------------------------- - // Read each generated barcode twice: - // 1. Without stripping FNC characters (StripFNC = false) - // 2. With stripping FNC characters (StripFNC = true) + // Read barcode without stripping FNC characters (default behavior) // -------------------------------------------------------------------- - foreach (var path in filePaths) + using (var reader = new BarCodeReader(filePath, DecodeType.Code128)) { - if (!File.Exists(path)) + Console.WriteLine("\nReading without StripFNC (default):"); + foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine($"File not found: {path}"); - continue; - } - - Console.WriteLine($"\nReading barcode: {Path.GetFileName(path)}"); - - // ------------------------------------------------------------ - // Read barcode without stripping FNC characters - // ------------------------------------------------------------ - using (var reader = new BarCodeReader(path, DecodeType.QR)) - { - reader.BarcodeSettings.StripFNC = false; - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"StripFNC = false => CodeText: {result.CodeText}"); - } + Console.WriteLine($"CodeText: {result.CodeText}"); } + } - // ------------------------------------------------------------ - // Read barcode with stripping FNC characters - // ------------------------------------------------------------ - using (var reader = new BarCodeReader(path, DecodeType.QR)) + // -------------------------------------------------------------------- + // Read barcode with StripFNC enabled + // -------------------------------------------------------------------- + using (var reader = new BarCodeReader(filePath, DecodeType.Code128)) + { + // Enable stripping of FNC symbols during decoding + reader.BarcodeSettings.StripFNC = true; + Console.WriteLine("\nReading with StripFNC = true:"); + foreach (BarCodeResult result in reader.ReadBarCodes()) { - reader.BarcodeSettings.StripFNC = true; - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"StripFNC = true => CodeText: {result.CodeText}"); - } + Console.WriteLine($"CodeText: {result.CodeText}"); } } } 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 742f940..a30e828 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,66 +1,103 @@ +// 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. +// 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 + using System; -using System.Collections.Generic; using System.IO; +using System.Reflection; using System.Threading.Tasks; -using Aspose.BarCode; using Aspose.BarCode.BarCodeRecognition; /// -/// Entry point for the barcode processing application. +/// 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. /// class Program { /// - /// Main method that processes image files to read barcodes in parallel. + /// Entry point of the application. /// - /// Optional list of image file paths to process. - static void Main(string[] args) + static void Main() { - // Determine the list of image paths: use command‑line arguments if provided, - // otherwise fall back to a predefined set of sample images. - List imagePaths = args.Length > 0 - ? new List(args) - : new List - { - "image1.png", - "image2.png", - "image3.png", - "image4.png", - "image5.png" - }; + // 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" + }; - // Set the maximum degree of parallelism to the number of logical processors. + // Determine the maximum degree of parallelism. + // Default to the number of logical processors; override if ProcessorSettings provides a limit. int maxDegree = Environment.ProcessorCount; + + // Use reflection to safely access BarCodeReader.ProcessorSettings.MaxProcessorCount. + PropertyInfo procSettingsProp = typeof(BarCodeReader).GetProperty( + "ProcessorSettings", + BindingFlags.Static | BindingFlags.Public); + + if (procSettingsProp != null) + { + object procSettings = procSettingsProp.GetValue(null); + if (procSettings != null) + { + PropertyInfo maxProp = procSettings.GetType().GetProperty( + "MaxProcessorCount", + BindingFlags.Instance | BindingFlags.Public); + + if (maxProp != null && maxProp.PropertyType == typeof(int)) + { + maxDegree = (int)maxProp.GetValue(procSettings); + } + } + } + + // Configure ParallelOptions with the resolved degree of parallelism. var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = maxDegree }; - // Process each image file in parallel. + // Process each image path concurrently. Parallel.ForEach(imagePaths, parallelOptions, path => { - // Verify that the file exists before attempting to read it. + // Verify that the file exists before attempting to read. if (!File.Exists(path)) { Console.WriteLine($"File not found: {path}"); return; } - // Create a barcode reader for the current image, supporting all barcode types. - using (BarCodeReader reader = new BarCodeReader(path, DecodeType.AllSupportedTypes)) + try { - try + // Initialize BarCodeReader for the current image file. + using (var reader = new BarCodeReader(path)) { - // Iterate through all detected barcodes in the image. - foreach (BarCodeResult result in reader.ReadBarCodes()) + // 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) { - Console.WriteLine($"File: {path}"); - Console.WriteLine($" Barcode Type : {result.CodeTypeName}"); - Console.WriteLine($" Code Text : {result.CodeText}"); + Console.WriteLine($"No barcodes detected in: {path}"); + } + else + { + foreach (var result in results) + { + Console.WriteLine($"File: {path}"); + Console.WriteLine($" Type: {result.CodeTypeName}"); + Console.WriteLine($" CodeText: {result.CodeText}"); + } } } - catch (Exception ex) - { - // Log any errors that occur during barcode processing. - Console.WriteLine($"Error processing {path}: {ex.Message}"); - } + } + catch (Exception ex) + { + // Log any exceptions that occur during processing of the current file. + Console.WriteLine($"Error processing {path}: {ex.Message}"); } }); } 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 5b1e074..574793b 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,99 @@ +// 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. +// 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 + using System; using System.IO; -using System.Threading.Tasks; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generating Code128 barcodes, reading them in parallel, -/// and resetting processor settings using Aspose.BarCode. +/// Example program that generates barcode images, configures multithreaded barcode recognition, +/// and resets ProcessorSettings to their default values after processing. /// class Program { /// - /// Entry point of the application. - /// Generates temporary barcode images, reads them concurrently, - /// resets processing settings, and cleans up resources. + /// Entry point of the example. Executes barcode generation, multithreaded reading, and settings reset. /// static void Main() { - // -------------------------------------------------------------------- - // 1. Prepare a temporary directory for barcode images - // -------------------------------------------------------------------- - string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodes"); - Directory.CreateDirectory(tempDir); + // Prepare a temporary folder for barcode images + string outputDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodes"); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } - // -------------------------------------------------------------------- - // 2. Define sample code texts for barcode generation - // -------------------------------------------------------------------- - string[] codeTexts = new string[] { "ABC123", "DEF456", "GHI789", "JKL012", "MNO345" }; - string[] imagePaths = new string[codeTexts.Length]; + // Sample barcode texts to encode + string[] texts = { "ABC123", "XYZ789", "HELLO", "WORLD", "TEST5" }; + string[] imagePaths = new string[texts.Length]; - // -------------------------------------------------------------------- - // 3. Generate barcode images and store their file paths - // -------------------------------------------------------------------- - for (int i = 0; i < codeTexts.Length; i++) + // Generate barcode images using default settings + for (int i = 0; i < texts.Length; i++) { - string imagePath = Path.Combine(tempDir, $"barcode_{i}.png"); - - // Create a barcode generator for Code128 with the current text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeTexts[i])) + string filePath = Path.Combine(outputDir, $"barcode_{i}.png"); + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, texts[i])) { - // Save the generated barcode image using default settings - generator.Save(imagePath); + // Save the barcode as PNG + generator.Save(filePath, BarCodeImageFormat.Png); } - - // Keep the path for later processing - imagePaths[i] = imagePath; + imagePaths[i] = filePath; } - // -------------------------------------------------------------------- - // 4. Configure ProcessorSettings for multithreaded processing - // -------------------------------------------------------------------- - // Enable use of all available CPU cores for BarCodeReader operations - BarCodeReader.ProcessorSettings.UseAllCores = true; + // Configure ProcessorSettings for a controlled multithreaded job + BarCodeReader.ProcessorSettings.UseAllCores = false; + 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}"); - // -------------------------------------------------------------------- - // 5. Process barcodes in parallel - // -------------------------------------------------------------------- - Parallel.ForEach(imagePaths, imagePath => + // Perform barcode reading using the configured ProcessorSettings + foreach (string path in imagePaths) { - // Each parallel task reads its assigned barcode image - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + if (!File.Exists(path)) { - // Set a high‑performance quality preset (optional) - reader.QualitySettings = QualitySettings.HighPerformance; + Console.WriteLine($"File not found: {path}"); + continue; + } - // Iterate over all detected barcodes in the image - foreach (var result in reader.ReadBarCodes()) + using (BarCodeReader reader = new BarCodeReader(path, DecodeType.Code128)) + { + // Iterate through all detected barcodes in the image + foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine($"File: {Path.GetFileName(imagePath)} | Detected: {result.CodeText}"); + Console.WriteLine($"Detected barcode: Type={result.CodeTypeName}, Text={result.CodeText}"); } } - }); + } - // -------------------------------------------------------------------- - // 6. Reset ProcessorSettings to their default values - // -------------------------------------------------------------------- - // Default: UseAllCores = false, UseOnlyThisCoresCount = 0 (no specific core count) + // 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 default values."); + 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}"); - // -------------------------------------------------------------------- - // 7. Clean up temporary files (optional) - // -------------------------------------------------------------------- - foreach (var file in imagePaths) + // Cleanup generated files (optional) + foreach (string path in imagePaths) { - if (File.Exists(file)) + if (File.Exists(path)) { - File.Delete(file); + File.Delete(path); } } - - // Remove the temporary directory - Directory.Delete(tempDir, true); + if (Directory.Exists(outputDir)) + { + Directory.Delete(outputDir, true); + } } } \ 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 6d6869d..381b7f1 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,83 +1,72 @@ +// 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. +// Prompt: Write a test confirming ProcessorSettings.UseAllCores respects the system's hyper‑threading configuration. +// Tags: code128, generation, recognition, png, barcodegenerator, barcodereader, processorsettings + using System; -using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Demonstrates barcode generation and recognition while configuring processor settings. +/// Example program that creates a Code128 barcode, saves it as an image, +/// and demonstrates the effect of ProcessorSettings.UseAllCores on barcode reading performance. /// class Program { /// - /// Entry point of the application. - /// Generates a Code128 barcode, saves it to a temporary PNG file, - /// then reads it back using different processor settings. + /// 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. /// static void Main() { - // Define path for a temporary PNG file to store the generated barcode image. - string tempPath = Path.Combine(Path.GetTempPath(), "test_barcode.png"); + // Define the output path for the generated barcode image. + string imagePath = "barcode.png"; + + // Generate a simple Code128 barcode and save it to the specified file. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) + { + generator.Save(imagePath); + } - // Generate a simple Code128 barcode with checksum enabled and save it as PNG. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789")) + // Verify that the image file was successfully created. + if (!System.IO.File.Exists(imagePath)) { - // Enable checksum for Code128 (required by the API). - generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; - // Save the barcode image to the temporary file. - generator.Save(tempPath, BarCodeImageFormat.Png); + Console.WriteLine("Failed to create barcode image."); + return; } - // Retrieve and display the number of logical processors (including hyper‑threads). - int logicalProcessors = Environment.ProcessorCount; - Console.WriteLine($"Logical processors (including hyper‑threads): {logicalProcessors}"); + // Display the default ProcessorSettings.UseAllCores value. + Console.WriteLine($"Default UseAllCores: {BarCodeReader.ProcessorSettings.UseAllCores}"); - // ------------------------------------------------------------ - // Test barcode reading with UseAllCores = true - // ------------------------------------------------------------ + // Enable the use of all processor cores for barcode reading. BarCodeReader.ProcessorSettings.UseAllCores = true; - Console.WriteLine($"ProcessorSettings.UseAllCores set to: {BarCodeReader.ProcessorSettings.UseAllCores}"); + Console.WriteLine($"After setting UseAllCores = true: {BarCodeReader.ProcessorSettings.UseAllCores}"); // Read the barcode using all available cores. - using (var readerAll = new BarCodeReader(tempPath, DecodeType.Code128)) + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - foreach (var result in readerAll.ReadBarCodes()) + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine("[UseAllCores=true] Detected barcode: " + result.CodeText); + Console.WriteLine($"[AllCores] Detected CodeText: {result.CodeText}"); } } - // ------------------------------------------------------------ - // Test barcode reading with UseAllCores = false and limited cores - // ------------------------------------------------------------ + // Disable UseAllCores and limit the number of cores used for processing. BarCodeReader.ProcessorSettings.UseAllCores = false; - // Limit the number of cores to half of the logical processors, rounded up, but at least 1. - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Math.Max(1, logicalProcessors / 2); - Console.WriteLine($"ProcessorSettings.UseAllCores set to: {BarCodeReader.ProcessorSettings.UseAllCores}"); - Console.WriteLine($"ProcessorSettings.UseOnlyThisCoresCount set to: {BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount}"); + 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}"); - // Read the barcode using the limited core count. - using (var readerLimited = new BarCodeReader(tempPath, DecodeType.Code128)) + // Read the barcode again, this time using the limited core count. + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - foreach (var result in readerLimited.ReadBarCodes()) + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine("[UseAllCores=false] Detected barcode: " + result.CodeText); + Console.WriteLine($"[LimitedCores] Detected CodeText: {result.CodeText}"); } } - - // ------------------------------------------------------------ - // Clean up: delete the temporary barcode image file - // ------------------------------------------------------------ - try - { - if (File.Exists(tempPath)) - { - File.Delete(tempPath); - } - } - 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/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 6bb63d9..ca9f95a 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,44 +1,45 @@ +// 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. +// Prompt: Write a test confirming ProcessorSettings.UseOnlyThisCoresCount does not exceed the physical core count. +// Tags: barcode, processor-settings, core-count, performance, aspose.barcode, test + using System; using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode.Common; /// -/// Demonstrates how to configure Aspose.BarCode processor settings -/// to limit the number of CPU cores used for barcode recognition. +/// 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. /// class Program { /// - /// Entry point of the application. - /// Retrieves the physical core count, attempts to set a higher core usage, - /// and validates that the configured core count does not exceed the actual cores. + /// 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. /// - /// Command‑line arguments (not used). - static void Main(string[] args) + static void Main() { - // Get the number of physical processor cores available on the machine. - int physicalCores = Environment.ProcessorCount; + // Retrieve the number of logical processors reported by the runtime. + // In most environments this corresponds to the physical core count. + int physicalCoreCount = Environment.ProcessorCount; - // Disable automatic use of all cores; we will set a specific core count manually. + // Disable automatic core selection and explicitly set the core count. BarCodeReader.ProcessorSettings.UseAllCores = false; + BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = physicalCoreCount; // attempt to use all available cores - // Attempt to assign a core count greater than the actual number of physical cores. - // This should be clamped by the library to the maximum available cores. - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = physicalCores + 5; - - // Retrieve the value that was actually set after the library's internal validation. - int configuredCores = BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount; + // Read back the configured core count for validation. + int configuredCoreCount = BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount; - // Check whether the configured core count respects the physical core limit. - if (configuredCores <= physicalCores) + // Ensure the configured value does not exceed the actual core count. + if (configuredCoreCount > physicalCoreCount) { - // Success: the library correctly limited the core count. - Console.WriteLine($"PASS: UseOnlyThisCoresCount ({configuredCores}) does not exceed physical cores ({physicalCores})."); - } - else - { - // Failure: the configured core count is higher than the physical core count. - Console.WriteLine($"FAIL: UseOnlyThisCoresCount ({configuredCores}) exceeds physical cores ({physicalCores})."); + throw new InvalidOperationException( + $"Configured core count ({configuredCoreCount}) exceeds physical core count ({physicalCoreCount})."); } + + // 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})."); } } \ 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 b7a27e7..ecb0c40 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,84 +1,95 @@ +// 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. +// Prompt: Write a unit test confirming IgnoreEndingFillingPatternsForCTable only affects decoding when CustomerInformationInterpretingType is CTable. +// Tags: australiapost, barcode, decoding, ctable, ntable, ignoreendingfillingpatterns, aspose.barcode + using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Demonstrates generation and decoding of an Australia Post barcode -/// using different customer information interpreting types and flags. +/// Example program that generates an AustraliaPost barcode and validates the impact of +/// IgnoreEndingFillingPatternsForCTable on decoding for different CustomerInformationInterpretingType settings. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, decodes it with various settings, - /// and prints verification results to the console. + /// Entry point. Generates a barcode, decodes it under three scenarios and prints test results. /// static void Main() { - // Create a barcode generator for Australia Post format with a sample value. - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678AB")) + // Sample code text containing the ending filling pattern "333" + const string originalCodeText = "5912345678AB333"; + + // Generate an AustraliaPost barcode image in memory + using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, originalCodeText)) { - // Configure the generator to use the CTable interpreting type. + // Use CTable interpreting type for generation generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable; - // Generate the barcode image. - using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) + using (var ms = new MemoryStream()) { - // Decode the image using CTable with the flag set to true. - string resultCTableFlagTrue = Decode(barcodeImage, CustomerInformationInterpretingType.CTable, true); - // Decode the image using CTable with the flag set to false. - string resultCTableFlagFalse = Decode(barcodeImage, CustomerInformationInterpretingType.CTable, false); - // Decode the image using NTable (flag should have no effect). - string resultNTableFlagTrue = Decode(barcodeImage, CustomerInformationInterpretingType.NTable, true); + // Save the barcode as PNG into the memory stream + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; + + // ---------- Test 1: CTable with IgnoreEndingFillingPatternsForCTable = true ---------- + string decodedWithIgnore = DecodeBarcode(ms, CustomerInformationInterpretingType.CTable, true); + + // Reset stream for next read + ms.Position = 0; - // Output the raw decoding results. - Console.WriteLine($"CTable, Flag=True : {resultCTableFlagTrue}"); - Console.WriteLine($"CTable, Flag=False: {resultCTableFlagFalse}"); - Console.WriteLine($"NTable, Flag=True : {resultNTableFlagTrue}"); + // ---------- Test 2: CTable with IgnoreEndingFillingPatternsForCTable = false ---------- + string decodedWithoutIgnore = DecodeBarcode(ms, CustomerInformationInterpretingType.CTable, false); - // Verify that the flag influences CTable decoding. - bool flagAffectsCTable = !string.Equals(resultCTableFlagTrue, resultCTableFlagFalse, StringComparison.Ordinal); - // Verify that the flag is ignored for non‑CTable interpreting types. - bool flagIgnoredForNTable = string.Equals(resultCTableFlagFalse, resultNTableFlagTrue, StringComparison.Ordinal); + // Reset stream for next read + ms.Position = 0; - // Print verification outcomes. - Console.WriteLine(); - Console.WriteLine($"Flag affects CTable decoding: {(flagAffectsCTable ? "PASS" : "FAIL")}"); - Console.WriteLine($"Flag ignored for non-CTable interpreting type: {(flagIgnoredForNTable ? "PASS" : "FAIL")}"); + // ---------- 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}"); } } } /// - /// Decodes a barcode image using the specified interpreting type and flag. + /// Decodes an AustraliaPost barcode from a stream using the specified interpreting type and ignore flag. /// - /// The bitmap containing the barcode. - /// The customer information interpreting type to apply. - /// - /// When true, ending filling patterns are ignored for CTable decoding. - /// - /// The decoded text, or an empty string if decoding fails. - static string Decode(Bitmap image, CustomerInformationInterpretingType interpretingType, bool ignoreEndingFillingPatterns) + /// 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) { - // Initialize a barcode reader for Australia Post format. - using (var reader = new BarCodeReader(image, DecodeType.AustraliaPost)) + using (var reader = new BarCodeReader(imageStream, DecodeType.AustraliaPost)) { - // Apply the requested interpreting type. + // Set the interpreting type (CTable or NTable) reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = interpretingType; - // Set the flag that controls handling of ending filling patterns for CTable. + + // Set the flag under test reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = ignoreEndingFillingPatterns; - // Iterate over detected barcodes (expecting at most one). + // Read barcodes and return the first result's CodeText foreach (var result in reader.ReadBarCodes()) { - // Return the first decoded text, or an empty string if null. return result.CodeText ?? string.Empty; } } - // Return empty string if no barcode was read. + // 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 47ee0ab..7ebbd83 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,91 +1,97 @@ +// 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. +// Prompt: Write a unit test verifying BarCodeReader removes FNC symbols when StripFNC is false. +// Tags: gs1code128, stripfnc, barcoderecognition, aspose.barcode, unit-test, fnc1 + using System; -using System.IO; using System.Linq; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generation and recognition of a GS1 Code128 barcode, -/// showing the effect of the StripFNC setting on FNC1 characters. +/// Example program that reads a GS1 Code128 barcode and demonstrates the effect of the StripFNC setting. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, reads it twice with different StripFNC settings, - /// and outputs verification results to the console. + /// 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. /// static void Main() { - // Sample GS1 Code128 text containing Application Identifiers. - const string codeText = "(02)04006664241007(37)1(400)7019590754"; + // Sample GS1 Code128 data containing multiple Application Identifier (AI) groups. + string sourceCodeText = "(02)04006664241007(37)1(400)7019590754"; - // Create a memory stream to hold the generated barcode image. - using (var ms = new MemoryStream()) + // 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 using Aspose.BarCode. - using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, codeText)) + // ------------------------------------------------------------ + // Test case 1: StripFNC = false (default behavior) + // ------------------------------------------------------------ + using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128)) { - // Save the barcode as PNG (any format works for recognition). - generator.Save(ms, BarCodeImageFormat.Png); - } + // Explicitly ensure that FNC characters are NOT stripped. + reader.BarcodeSettings.StripFNC = false; - // Reset stream position to the beginning for reading. - ms.Position = 0; + // Read the first barcode result from the image. + BarCodeResult result = reader.ReadBarCodes().FirstOrDefault(); - // ---------- First read: StripFNC = false ---------- - // FNC characters should be retained in the decoded text. - string codeWithoutStrip; - using (var reader = new BarCodeReader(ms, DecodeType.GS1Code128)) - { - // Configure reader to keep FNC characters. - reader.BarcodeSettings.StripFNC = false; + // Verify that a result was obtained. + if (result == null) + { + Console.WriteLine("Failed to read barcode with StripFNC = false."); + return; + } - // Read the first barcode found (there should be only one). - var result = reader.ReadBarCodes().FirstOrDefault(); + // Expected raw text includes FNC1 separators (ASCII 29, represented as \x1D). + string expectedRaw = "\x1D04006664241007\x1D1\x1D7019590754"; - // Extract the decoded text, or use empty string if none. - codeWithoutStrip = result?.CodeText ?? string.Empty; - } + // Compare the actual CodeText with the expected raw string. + bool rawMatches = result.CodeText == expectedRaw; + Console.WriteLine($"StripFNC = false => CodeText matches expected: {rawMatches}"); - // Reset stream position again for the second read. - ms.Position = 0; + // Output detailed mismatch information if the comparison fails. + if (!rawMatches) + { + Console.WriteLine($"Actual: [{result.CodeText}]"); + Console.WriteLine($"Expected: [{expectedRaw}]"); + } + } - // ---------- Second read: StripFNC = true ---------- - // FNC characters should be removed from the decoded text. - string codeWithStrip; - using (var reader = new BarCodeReader(ms, DecodeType.GS1Code128)) + // ------------------------------------------------------------ + // Test case 2: StripFNC = true + // ------------------------------------------------------------ + using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128)) { - // Configure reader to strip FNC characters. + // Enable stripping of FNC characters. reader.BarcodeSettings.StripFNC = true; - // Read the first barcode found. - var result = reader.ReadBarCodes().FirstOrDefault(); - - // Extract the decoded text, or use empty string if none. - codeWithStrip = result?.CodeText ?? string.Empty; - } + // Read the first barcode result from the image. + BarCodeResult result = reader.ReadBarCodes().FirstOrDefault(); - // The FNC1 character is represented by char value 241 in Aspose.BarCode. - char fncChar = (char)241; + // Verify that a result was obtained. + if (result == null) + { + Console.WriteLine("Failed to read barcode with StripFNC = true."); + return; + } - // Determine whether the unstripped result contains the FNC1 character. - bool containsFnc = codeWithoutStrip.Contains(fncChar.ToString()); + // Expected text after stripping FNC1 separators: concatenated data without delimiters. + string expectedStripped = "0400666424100717019590754"; - // Output verification information to the console. - Console.WriteLine("CodeText with StripFNC = false: " + codeWithoutStrip); - Console.WriteLine("Contains FNC1 character: " + containsFnc); - Console.WriteLine("CodeText with StripFNC = true : " + codeWithStrip); - Console.WriteLine("CodeTexts are different: " + (codeWithoutStrip != codeWithStrip)); + // Compare the actual CodeText with the expected stripped string. + bool strippedMatches = result.CodeText == expectedStripped; + Console.WriteLine($"StripFNC = true => CodeText matches expected: {strippedMatches}"); - // Simple assertion to confirm expected behavior. - if (containsFnc && codeWithoutStrip != codeWithStrip) - { - Console.WriteLine("Test passed: FNC characters are retained when StripFNC is false and removed when true."); - } - else - { - Console.WriteLine("Test failed: Unexpected StripFNC behavior."); + // Output detailed mismatch information if the comparison fails. + if (!strippedMatches) + { + Console.WriteLine($"Actual: [{result.CodeText}]"); + Console.WriteLine($"Expected: [{expectedStripped}]"); + } } } } 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 aed5bb4..090fd59 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,84 +1,98 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Demonstrates generating a GS1 Code128 barcode with FNC characters, -/// then reading it with and without stripping those characters. +/// Contains the example that validates the StripFNC behavior of for GS1‑128 barcodes. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, reads it twice (once with StripFNC disabled, - /// once with StripFNC enabled) and prints the results. + /// 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. /// static void Main() { - // Sample GS1 Code128 text containing FNC characters. - // Parentheses denote Application Identifier (AI) sections. - const string codeText = "(02)04006664241007(37)1(400)7019590754"; + // Sample GS1‑128 code text containing Application Identifier (AI) sections. + const string sampleCodeText = "(02)04006664241007(37)1(400)7019590754"; - // Create a memory stream to hold the generated barcode image. - using (var ms = new MemoryStream()) + // Generate the barcode image into a memory stream to avoid file I/O. + using (var imageStream = new MemoryStream()) { - // Generate the barcode and save it as PNG into the memory stream. - using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, codeText)) + // Create a generator for GS1‑128 and save the image as PNG. + using (var generator = new BarcodeGenerator(EncodeTypes.GS1Code128, sampleCodeText)) { - generator.Save(ms, BarCodeImageFormat.Png); + generator.Save(imageStream, BarCodeImageFormat.Png); } - // Reset the stream position to the beginning before reading. - ms.Position = 0; + // Reset the stream position so it can be read from the beginning. + imageStream.Position = 0; - // ----------------------------------------------------------------- - // Read the barcode with StripFNC disabled (default behavior). - // This provides a baseline comparison where FNC characters are not stripped. - // ----------------------------------------------------------------- - using (var readerNoStrip = new BarCodeReader(ms, DecodeType.Code128)) - { - // No need to modify StripFNC; it defaults to false. - var resultsNoStrip = readerNoStrip.ReadBarCodes(); + // 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; - foreach (var result in resultsNoStrip) - { - Console.WriteLine($"StripFNC = false => CodeText: {result.CodeText}"); - } - } + // 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; - // Reset the stream again for the second read operation. - ms.Position = 0; + int passed = 0, failed = 0; - // ----------------------------------------------------------------- - // Read the same barcode with StripFNC enabled. - // This should retain the FNC symbols (parentheses) in the decoded text. - // ----------------------------------------------------------------- - using (var readerStrip = new BarCodeReader(ms, DecodeType.Code128)) - { - // Enable stripping of FNC characters. - readerStrip.BarcodeSettings.StripFNC = true; + // The FNC1 character is represented by ASCII 29 (Group Separator). + const char fnc1Char = '\u001D'; - var resultsStrip = readerStrip.ReadBarCodes(); + // Verify that the result without stripping contains the FNC1 character. + if (decodedWithoutStrip != null && decodedWithoutStrip.IndexOf(fnc1Char) >= 0) + passed++; + else + failed++; - foreach (var result in resultsStrip) - { - Console.WriteLine($"StripFNC = true => CodeText: {result.CodeText}"); + // Verify that the result with stripping does NOT contain the FNC1 character. + if (decodedWithStrip != null && decodedWithStrip.IndexOf(fnc1Char) < 0) + passed++; + else + failed++; + + // 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}\""); + } + } - // Verify that FNC symbols (parentheses) are still present when StripFNC is true. - bool containsFnc = result.CodeText.Contains("(") && result.CodeText.Contains(")"); - if (containsFnc) - { - Console.WriteLine("PASS: FNC symbols are retained when StripFNC is true."); - } - else - { - Console.WriteLine("FAIL: FNC symbols were stripped when StripFNC is true."); - } - } + /// + /// 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)) + { + // Apply the StripFNC setting. + reader.BarcodeSettings.StripFNC = stripFnc; + + // Iterate over detected barcodes (there should be only one in this example). + foreach (var result in reader.ReadBarCodes()) + { + codeText = result.CodeText; + return true; } } + 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 13e7e20..03665f0 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,3 +1,9 @@ +// 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. +// 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 + using System; using System.IO; using Aspose.BarCode; @@ -6,64 +12,81 @@ using Aspose.Drawing; /// -/// Demo program that generates a barcode, attempts to load a custom decoder via reflection, -/// and reads the barcode using Aspose.BarCode. +/// 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. /// class Program { /// - /// Entry point. Generates a barcode, tries to instantiate a custom CustomerInformationDecoder, - /// and reads the barcode. + /// Generates a barcode, reads it using a custom , + /// and checks that the decoder was invoked with the expected raw data. /// static void Main() { - // Generate a simple Code128 barcode image in memory. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Generate an Australia Post barcode with sample data and store it in a memory stream + using (var imageStream = new MemoryStream()) { - using (var ms = new MemoryStream()) + using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "5912345678ABCde")) { - // Save the generated barcode to the memory stream as PNG. - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for reading. - - // Attempt to locate the custom CustomerInformationDecoder type via reflection. - var decoderType = Type.GetType("Aspose.BarCode.BarCodeRecognition.CustomerInformationDecoder"); - if (decoderType == null) - { - Console.WriteLine("Custom CustomerInformationDecoder is not available in this Aspose.BarCode version."); - return; - } + // 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); + } - // If the type exists, create an instance (placeholder logic). - try - { - var decoderInstance = Activator.CreateInstance(decoderType); - Console.WriteLine($"Custom decoder instance created: {decoderInstance.GetType().FullName}"); + // Reset stream position to the beginning for reading + imageStream.Position = 0; - // Load the barcode image for recognition. - using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes)) - { - // Note: Actual assignment of the custom decoder depends on the API, - // which is not known. This placeholder demonstrates where such assignment would occur. - // Example (hypothetical): reader.CustomDecoder = decoderInstance; + // Prepare the custom decoder instance + var customDecoder = new MyDecoder(); - // Perform barcode recognition. - var results = reader.ReadBarCodes(); - foreach (var result in results) - { - Console.WriteLine($"Detected barcode: Type={result.CodeTypeName}, Text={result.CodeText}"); - } + // 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; - // Indicate completion; raw bytes verification requires a concrete decoder implementation. - Console.WriteLine("Test completed – raw barcode bytes handling cannot be verified without a concrete CustomerInformationDecoder implementation."); - } - } - catch (Exception ex) + // Perform recognition and output detected code texts + foreach (var result in reader.ReadBarCodes()) { - // Handle any errors that occur during decoder creation or usage. - Console.WriteLine($"Error while creating or using custom decoder: {ex.Message}"); + Console.WriteLine($"Detected CodeText: {result.CodeText}"); } } + + // 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."); + } } } } \ 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 22813f8..a50d9bd 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,66 +1,55 @@ +// 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. +// Prompt: Write a validation routine ensuring ProcessorSettings.MaxAdditionalAllowedThreads does not exceed system limits. +// Tags: barcode, threading, validation, processorsettings, aspose.barcode + using System; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates validation and configuration of the maximum number of additional threads -/// used by Aspose.BarCode's barcode processing engine. +/// Provides an example of validating and setting the maximum number of additional threads +/// allowed for Aspose.BarCode's based on system limits. /// class Program { /// - /// Validates and sets the maximum number of additional threads for barcode processing. + /// 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. /// - /// The desired number of additional threads. - /// - /// Thrown when is negative or exceeds the system limit. - /// - static void SetMaxAdditionalAllowedThreads(int requestedThreads) + static void Main() { - // Calculate a reasonable system limit (e.g., 4 times the logical processor count). - int systemLimit = Environment.ProcessorCount * 4; - - // Ensure the requested thread count is not negative. - if (requestedThreads < 0) - throw new ArgumentOutOfRangeException( - nameof(requestedThreads), - "Thread count cannot be negative."); + // Retrieve the number of logical processors available on the current machine. + int processorCount = Environment.ProcessorCount; - // Ensure the requested thread count does not exceed the calculated system limit. - if (requestedThreads > systemLimit) - throw new ArgumentOutOfRangeException( - nameof(requestedThreads), - $"Thread count exceeds system limit of {systemLimit} threads."); - - // Apply the validated value to the Aspose.BarCode processor settings. - BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = requestedThreads; + // 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; - // Inform the user of the successful configuration. - Console.WriteLine($"ProcessorSettings.MaxAdditionalAllowedThreads set to {requestedThreads}"); - } + // Define a safe upper bound for additional threads (e.g., twice the core count). + int maxAllowed = processorCount * 2; - /// - /// Entry point demonstrating thread count validation. - /// - static void Main() - { - // Attempt to set a valid thread count and handle any validation errors. - try - { - SetMaxAdditionalAllowedThreads(8); - } - catch (ArgumentOutOfRangeException ex) + // Ensure the requested thread count is not negative. + if (desiredAdditionalThreads < 0) { - Console.WriteLine($"Validation error: {ex.Message}"); + throw new ArgumentOutOfRangeException( + nameof(desiredAdditionalThreads), + "MaxAdditionalAllowedThreads cannot be negative."); } - // Attempt to set an invalid thread count (exceeds limit) and handle the error. - try - { - SetMaxAdditionalAllowedThreads(1000); - } - catch (ArgumentOutOfRangeException ex) + // If the requested value exceeds the safe limit, adjust it down to the maximum allowed. + if (desiredAdditionalThreads > maxAllowed) { - Console.WriteLine($"Validation error: {ex.Message}"); + Console.WriteLine( + $"Requested MaxAdditionalAllowedThreads ({desiredAdditionalThreads}) exceeds system limit ({maxAllowed}). Adjusting to limit."); + desiredAdditionalThreads = maxAllowed; } + + // Apply the validated (and possibly adjusted) thread count to the Aspose.BarCode processor settings. + BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads = desiredAdditionalThreads; + + // Output the final setting for verification. + Console.WriteLine( + $"ProcessorSettings.MaxAdditionalAllowedThreads is set to {BarCodeReader.ProcessorSettings.MaxAdditionalAllowedThreads}."); } } \ No newline at end of file