diff --git a/barcode-recognition-xml-serialization/compare-performance-of-exporttoxml-using-file-path-versus-stream-overload-for-large-barcode-image-batches.cs b/barcode-recognition-xml-serialization/compare-performance-of-exporttoxml-using-file-path-versus-stream-overload-for-large-barcode-image-batches.cs index c8f8f2a..a0b2192 100644 --- a/barcode-recognition-xml-serialization/compare-performance-of-exporttoxml-using-file-path-versus-stream-overload-for-large-barcode-image-batches.cs +++ b/barcode-recognition-xml-serialization/compare-performance-of-exporttoxml-using-file-path-versus-stream-overload-for-large-barcode-image-batches.cs @@ -1,99 +1,80 @@ -// Title: ExportToXml Performance Comparison: File Path vs Stream -// Description: Demonstrates measuring the execution time of Aspose.BarCode's ExportToXml method when writing to a file versus a memory stream for a batch of barcode images. +// Title: Compare ExportToXml performance: file path vs stream overload +// Description: Demonstrates measuring execution time of Aspose.BarCode ExportToXml using a file path and a stream for a batch of barcodes. +// Category-Description: This example belongs to the Aspose.BarCode generation and serialization category, showcasing how to serialize generated barcodes to XML using the ExportToXml API. It highlights key classes such as BarcodeGenerator, EncodeTypes, and the ExportToXml overloads, which developers commonly use when persisting barcode data for later processing or integration with other systems. // Prompt: Compare performance of ExportToXml using file path versus stream overload for large barcode image batches. -// Tags: code128, export, xml, performance, aspose.barcode, stream, file +// Tags: barcode, export, xml, performance, file-path, stream, aspose.barcode, code128, generation using System; -using System.Collections.Generic; using System.Diagnostics; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Provides a simple benchmark that compares the time required to export barcode data to XML -/// using the file‑path overload versus the stream overload of BarcodeGenerator.ExportToXml. +/// Demonstrates performance comparison between ExportToXml overloads (file path vs stream) for a batch of Code128 barcodes. /// class Program { /// - /// Entry point of the demo. Generates a small set of barcodes, exports each to XML - /// using both overloads, records the elapsed time, and prints a side‑by‑side comparison. + /// Entry point. Generates a set of barcodes, exports each to XML using both overloads, and reports elapsed time. /// static void Main() { - // Prepare a temporary directory for XML files - string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeExportDemo"); - if (!Directory.Exists(tempDir)) - { - Directory.CreateDirectory(tempDir); - } + const int batchSize = 5; // safe sample size for demonstration - // Sample barcode texts (small batch for safe execution) - List sampleTexts = new List - { - "ABC123456", - "9876543210", - "TestCode128", - "12345ABCDE", - "ZXCVBNM123" - }; + // Prepare output directory for generated XML files + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "ExportXmlDemo"); + Directory.CreateDirectory(outputDir); - // Store timing results for each overload - List fileTimes = new List(); - List streamTimes = new List(); - - // Iterate over each barcode text - for (int i = 0; i < sampleTexts.Count; i++) + // ------------------------------------------------------------ + // Measure performance of ExportToXml(string) overload + // ------------------------------------------------------------ + var swPath = Stopwatch.StartNew(); + for (int i = 1; i <= batchSize; i++) { - string codeText = sampleTexts[i]; - - // Create a BarcodeGenerator instance for the current text - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Create a barcode generator for Code128 with a unique value + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i:D4}")) { - // Export to XML file and measure time - string xmlFilePath = Path.Combine(tempDir, $"barcode_{i}.xml"); - Stopwatch swFile = Stopwatch.StartNew(); - bool fileResult = generator.ExportToXml(xmlFilePath); - swFile.Stop(); - fileTimes.Add(swFile.Elapsed); + // Define XML file path for this barcode + string xmlPath = Path.Combine(outputDir, $"barcode_path_{i}.xml"); - // Export to XML stream and measure time - using (MemoryStream ms = new MemoryStream()) + // Export barcode to XML file; check success + bool success = generator.ExportToXml(xmlPath); + if (!success) { - Stopwatch swStream = Stopwatch.StartNew(); - bool streamResult = generator.ExportToXml(ms); - swStream.Stop(); - streamTimes.Add(swStream.Elapsed); - } - - // Optional: verify export success (not required for timing) - if (!fileResult) - { - Console.WriteLine($"Export to file failed for index {i}."); + Console.WriteLine($"Export to file failed for item {i}"); } } } + swPath.Stop(); - // Output timing comparison - Console.WriteLine("Performance comparison of ExportToXml (file path vs stream):"); - for (int i = 0; i < sampleTexts.Count; i++) + // ------------------------------------------------------------ + // Measure performance of ExportToXml(Stream) overload + // ------------------------------------------------------------ + var swStream = Stopwatch.StartNew(); + for (int i = 1; i <= batchSize; i++) { - Console.WriteLine($"Item {i + 1}: File = {fileTimes[i].TotalMilliseconds} ms, Stream = {streamTimes[i].TotalMilliseconds} ms"); - } - - // Clean up temporary XML files - try - { - foreach (string file in Directory.GetFiles(tempDir, "*.xml")) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i:D4}")) { - File.Delete(file); + // Define XML file path for this barcode + string xmlPath = Path.Combine(outputDir, $"barcode_stream_{i}.xml"); + + // Open a file stream for writing the XML + using (var fileStream = new FileStream(xmlPath, FileMode.Create, FileAccess.Write)) + { + // Export barcode to the provided stream; check success + bool success = generator.ExportToXml(fileStream); + if (!success) + { + Console.WriteLine($"Export to stream failed for item {i}"); + } + } } - Directory.Delete(tempDir); - } - catch - { - // If cleanup fails, ignore – not critical for the demo } + swStream.Stop(); + + // Output timing results for both overloads + Console.WriteLine($"ExportToXml(string) total time for {batchSize} items: {swPath.ElapsedMilliseconds} ms"); + Console.WriteLine($"ExportToXml(Stream) total time for {batchSize} items: {swStream.ElapsedMilliseconds} ms"); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/create-batch-process-that-reads-multiple-images-extracts-barcodes-and-writes-each-state-to-separate-xml-files.cs b/barcode-recognition-xml-serialization/create-batch-process-that-reads-multiple-images-extracts-barcodes-and-writes-each-state-to-separate-xml-files.cs index 5de4370..9bf4a15 100644 --- a/barcode-recognition-xml-serialization/create-batch-process-that-reads-multiple-images-extracts-barcodes-and-writes-each-state-to-separate-xml-files.cs +++ b/barcode-recognition-xml-serialization/create-batch-process-that-reads-multiple-images-extracts-barcodes-and-writes-each-state-to-separate-xml-files.cs @@ -1,82 +1,108 @@ // Title: Batch barcode extraction to XML -// Description: Demonstrates reading multiple image files, extracting any barcodes found, and writing each barcode's details to a separate XML file. +// Description: Demonstrates reading multiple images, extracting all supported barcodes, and saving each result to an XML file per image. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, showing how to use BarCodeReader with DecodeType.AllSupportedTypes, XmlWriter, and BarcodeGenerator for sample data. Developers often need to process batches of images, extract barcode information, and store results in structured formats such as XML for downstream systems. // Prompt: Create a batch process that reads multiple images, extracts barcodes, and writes each state to separate XML files. -// Tags: barcode, batch, xml, aspose.barcode, barcodereader +// Tags: barcode recognition, batch processing, xml output, decodeall, aspose.barcode, csharp using System; using System.IO; using System.Xml; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Example program that processes a collection of image files, -/// extracts all detected barcodes, and writes each barcode's -/// type and text to an individual XML file. +/// Demonstrates batch processing of barcode images: generating sample barcodes, reading them, and writing results to XML files. /// class Program { /// - /// Entry point of the application. Iterates over a predefined list of image paths, - /// reads barcodes using Aspose.BarCode, and generates XML files for each barcode found. + /// Entry point. Generates sample barcodes, processes each image, extracts barcodes, and writes XML output. /// static void Main() { - // Define the list of image files to be processed. - // Adjust the file paths as needed for your environment. - string[] imageFiles = new string[] + // Define working folder for generated and processed files + string workFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(workFolder)) { - "image1.png", - "image2.png", - "image3.png", - "image4.png", - "image5.png" - }; + Directory.CreateDirectory(workFolder); + } + + // ----------------------------------------------------------------- + // Step 1: Generate a few sample barcode images (self‑contained demo) + // ----------------------------------------------------------------- + GenerateSampleBarcodes(workFolder); - // Process each image file in the list. + // ----------------------------------------------------------------- + // Step 2: Process each image, extract barcodes and write XML files + // ----------------------------------------------------------------- + string[] imageFiles = Directory.GetFiles(workFolder, "*.png"); foreach (string imagePath in imageFiles) { - // Verify that the file exists before attempting to read it. if (!File.Exists(imagePath)) { Console.WriteLine($"File not found: {imagePath}"); continue; } - // Initialize a barcode reader for the current image, - // configured to detect all supported barcode types. - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Prepare XML writer for the output file (same name, .xml extension) + string xmlPath = Path.ChangeExtension(imagePath, ".xml"); + using (XmlWriter writer = XmlWriter.Create(xmlPath, new XmlWriterSettings { Indent = true })) { - int barcodeIndex = 0; // Counter for naming XML files uniquely per image. + writer.WriteStartDocument(); + writer.WriteStartElement("Barcodes"); - // Iterate over all detected barcodes in the image. - foreach (var result in reader.ReadBarCodes()) + // Read all supported barcodes from the current image + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - // Construct the XML file name using the image name and barcode index. - string xmlFileName = $"{Path.GetFileNameWithoutExtension(imagePath)}_{barcodeIndex}.xml"; - - // Create an XML writer with indentation for readability. - using (var writer = XmlWriter.Create(xmlFileName, new XmlWriterSettings { Indent = true })) + foreach (var result in reader.ReadBarCodes()) { - writer.WriteStartDocument(); writer.WriteStartElement("BarCode"); + writer.WriteAttributeString("Type", result.CodeTypeName); + writer.WriteAttributeString("CodeText", result.CodeText ?? string.Empty); - // Write barcode type and text elements, handling possible null values. - writer.WriteElementString("Type", result.CodeTypeName ?? string.Empty); - writer.WriteElementString("CodeText", result.CodeText ?? string.Empty); + // Include region information if available + if (result.Region != null) + { + var rect = result.Region.Rectangle; + writer.WriteAttributeString("X", rect.X.ToString()); + writer.WriteAttributeString("Y", rect.Y.ToString()); + writer.WriteAttributeString("Width", rect.Width.ToString()); + writer.WriteAttributeString("Height", rect.Height.ToString()); + } - writer.WriteEndElement(); // - writer.WriteEndDocument(); + writer.WriteEndElement(); // BarCode } - - Console.WriteLine($"Processed barcode {barcodeIndex} from '{imagePath}' -> '{xmlFileName}'"); - barcodeIndex++; } - // If no barcodes were detected, inform the user. - if (barcodeIndex == 0) - { - Console.WriteLine($"No barcodes detected in '{imagePath}'."); - } + writer.WriteEndElement(); // Barcodes + writer.WriteEndDocument(); + } + + Console.WriteLine($"Processed '{Path.GetFileName(imagePath)}' -> '{Path.GetFileName(xmlPath)}'"); + } + + Console.WriteLine("Batch processing completed."); + } + + // Generates a small set of sample barcode images in the specified folder. + private static void GenerateSampleBarcodes(string folder) + { + // Sample data: (symbology, text, file name) + var samples = new (BaseEncodeType encode, string text, string file)[] + { + (EncodeTypes.Code128, "Sample123", "code128.png"), + (EncodeTypes.QR, "https://example.com", "qr.png"), + (EncodeTypes.DataMatrix, "DM12345", "datamatrix.png") + }; + + foreach (var (encode, text, file) in samples) + { + string path = Path.Combine(folder, file); + using (var generator = new BarcodeGenerator(encode, text)) + { + // Simple settings – default size and colors are fine for the demo + generator.Save(path, BarCodeImageFormat.Png); } } } diff --git a/barcode-recognition-xml-serialization/create-console-app-that-accepts-image-path-detects-barcodes-and-writes-state-to-xml-file.cs b/barcode-recognition-xml-serialization/create-console-app-that-accepts-image-path-detects-barcodes-and-writes-state-to-xml-file.cs index 1c26eb8..31feaaa 100644 --- a/barcode-recognition-xml-serialization/create-console-app-that-accepts-image-path-detects-barcodes-and-writes-state-to-xml-file.cs +++ b/barcode-recognition-xml-serialization/create-console-app-that-accepts-image-path-detects-barcodes-and-writes-state-to-xml-file.cs @@ -1,83 +1,83 @@ -// Title: Barcode Detection and XML Export -// Description: Detects all barcodes in an image file and writes their type and text to an XML document. +// Title: Detect barcodes in an image and export results to XML +// Description: Loads an image, detects any barcodes using Aspose.BarCode, and writes detection details to an XML file. +// Category-Description: Demonstrates barcode recognition with Aspose.BarCode in a console application. The example shows how to use BarcodeGenerator for fallback image creation, BarCodeReader for detecting all supported symbologies, and XmlWriter for persisting results. Ideal for developers needing quick barcode extraction and reporting in automation pipelines. // Prompt: Create a console app that accepts an image path, detects barcodes, and writes state to an XML file. -// Tags: barcode, detection, xml, console, aspose.barcoderecognition +// Tags: barcode detection, code128, xml output, aspose.barcode, console app using System; using System.IO; using System.Xml; +using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates how to read barcodes from an image and export the results to an XML file. +/// Console application that reads an image, detects barcodes, and writes detection results to an XML file. /// class Program { /// - /// Entry point of the console application. - /// Accepts an optional image path argument, detects barcodes, and writes the results to an XML file. + /// Entry point. Accepts an optional image path argument, generates a sample barcode if the file is missing, + /// reads all supported barcodes, and saves the results to an XML document. /// - /// Command‑line arguments; the first argument may be the image file path. + /// Command‑line arguments; the first argument is treated as the image file path. static void Main(string[] args) { - // Determine image path from command‑line or use a default sample. + // Determine image path (first argument or default) string imagePath = args.Length > 0 ? args[0] : "sample.png"; - // Verify that the image file exists before proceeding. + // If the image does not exist, generate a simple sample barcode if (!File.Exists(imagePath)) { - Console.WriteLine($"Image file not found: {imagePath}"); - return; + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + { + // Save the generated barcode as a PNG file + generator.Save(imagePath, BarCodeImageFormat.Png); + } } - // Prepare the output XML file path by changing the image extension to .xml. - string xmlPath = Path.ChangeExtension(imagePath, ".xml"); - - // Configure the XML writer to produce indented, human‑readable output. - XmlWriterSettings settings = new XmlWriterSettings - { - Indent = true, - IndentChars = " " - }; + // Prepare XML output path (same folder as the image) + string xmlPath = Path.Combine(Path.GetDirectoryName(imagePath) ?? "", "barcode_results.xml"); - // Open the XML writer within a using block to ensure proper disposal. - using (XmlWriter writer = XmlWriter.Create(xmlPath, settings)) + // Read barcodes from the image using all supported symbologies + using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - writer.WriteStartDocument(); - writer.WriteStartElement("Barcodes"); + var results = reader.ReadBarCodes(); - // Initialize the barcode reader to detect all supported barcode types. - using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Create an XML writer with indentation for readability + using (var writer = XmlWriter.Create(xmlPath, new XmlWriterSettings { Indent = true })) { - // Iterate through each detected barcode in the image. - foreach (var result in reader.ReadBarCodes()) + writer.WriteStartDocument(); + writer.WriteStartElement("Barcodes"); + + // Iterate over each detected barcode and write its details + foreach (var result in results) { writer.WriteStartElement("BarCode"); - // Write the barcode type name (e.g., QR, Code128). writer.WriteElementString("Type", result.CodeTypeName ?? string.Empty); - - // Write the decoded text/value of the barcode. writer.WriteElementString("CodeText", result.CodeText ?? string.Empty); + writer.WriteElementString("Confidence", result.Confidence.ToString()); + writer.WriteElementString("ReadingQuality", result.ReadingQuality.ToString()); - // Optional: write the region bounds of the barcode if needed. - // var rect = result.Region.Rectangle; - // writer.WriteStartElement("Region"); - // writer.WriteElementString("X", rect.X.ToString()); - // writer.WriteElementString("Y", rect.Y.ToString()); - // writer.WriteElementString("Width", rect.Width.ToString()); - // writer.WriteElementString("Height", rect.Height.ToString()); - // writer.WriteEndElement(); // Region + // Write the region (bounding rectangle) of the barcode + var rect = result.Region.Rectangle; + writer.WriteStartElement("Region"); + writer.WriteElementString("X", rect.X.ToString()); + writer.WriteElementString("Y", rect.Y.ToString()); + writer.WriteElementString("Width", rect.Width.ToString()); + writer.WriteElementString("Height", rect.Height.ToString()); + writer.WriteEndElement(); // Region writer.WriteEndElement(); // BarCode } - } - writer.WriteEndElement(); // Barcodes - writer.WriteEndDocument(); + writer.WriteEndElement(); // Barcodes + writer.WriteEndDocument(); + } } - // Inform the user that processing is complete and provide the XML file location. - Console.WriteLine($"Barcode detection completed. Results saved to: {xmlPath}"); + // Inform the user where the XML file was written + Console.WriteLine($"Barcode detection completed. Results saved to: {Path.GetFullPath(xmlPath)}"); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/create-demo-that-shows-checkpoint-restart-by-exporting-state-closing-reader-reopening-and-continuing-detection.cs b/barcode-recognition-xml-serialization/create-demo-that-shows-checkpoint-restart-by-exporting-state-closing-reader-reopening-and-continuing-detection.cs index a716301..b75d46f 100644 --- a/barcode-recognition-xml-serialization/create-demo-that-shows-checkpoint-restart-by-exporting-state-closing-reader-reopening-and-continuing-detection.cs +++ b/barcode-recognition-xml-serialization/create-demo-that-shows-checkpoint-restart-by-exporting-state-closing-reader-reopening-and-continuing-detection.cs @@ -1,77 +1,81 @@ -// Title: Barcode checkpoint/restart demo -// Description: Demonstrates exporting a reader's state to XML, closing the reader, reopening it, and continuing barcode detection. +// Title: Barcode checkpoint/restart demo using Aspose.BarCode +// Description: Demonstrates exporting a BarCodeReader state to XML, closing it, then importing and continuing detection on the same image. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating how to use BarCodeReader's checkpoint feature. It covers exporting reader settings with ExportToXml, importing with ImportFromXml, and resuming barcode detection. Developers working with large image batches or needing to pause/resume processing can use these APIs to manage state efficiently. // Prompt: Create a demo that shows checkpoint/restart by exporting state, closing the reader, reopening, and continuing detection. -// Tags: barcode, checkpoint, restart, export, import, aspose.barcoderecognition, aspose.barcodegeneration +// Tags: barcode, checkpoint, restart, export, import, aspose.barcode, coderecognition, code128, xml using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Demonstrates checkpoint/restart functionality for barcode detection using Aspose.BarCode. +/// Demonstrates checkpoint/restart functionality of Aspose.BarCode's BarCodeReader. /// class Program { /// - /// Entry point of the demo. Generates a barcode image if missing, reads it, exports the reader state, - /// simulates an application restart by importing the state, and continues detection. + /// Entry point. Generates a barcode, saves reader state, reloads it, and continues detection. /// static void Main() { // Paths for the barcode image and the checkpoint file - string imagePath = "sample.png"; + string barcodePath = "barcode.png"; string checkpointPath = "reader_state.xml"; - // Ensure a barcode image exists; create one if missing - if (!File.Exists(imagePath)) + // ------------------------------------------------- + // Step 1: Generate a sample barcode image (Code128) + // ------------------------------------------------- + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Generate a simple Code128 barcode and save it to disk - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Demo123")) - { - generator.Save(imagePath); - Console.WriteLine($"Generated barcode image: {imagePath}"); - } + // Save the generated barcode to a PNG file + generator.Save(barcodePath); } - // First detection pass – read the barcode and export reader state - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + // Verify that the barcode image was created successfully + if (!File.Exists(barcodePath)) { - // Perform detection and process the first result - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"First read – Type: {result.CodeTypeName}, Text: {result.CodeText}"); + Console.WriteLine("Failed to create barcode image."); + return; + } - // Export current reader settings to XML (checkpoint) - reader.ExportToXml(checkpointPath); - Console.WriteLine($"Reader state exported to: {checkpointPath}"); - break; // Demonstrate checkpoint after first result - } + // ------------------------------------------------- + // Step 2: Create a reader, set image, and export state + // ------------------------------------------------- + using (var reader = new BarCodeReader()) + { + // Restrict detection to Code128 symbology + reader.SetBarCodeReadType(DecodeType.Code128); + + // Load the barcode image into the reader + reader.SetBarCodeImage(barcodePath); + + // Export the reader's configuration (checkpoint) to an XML file + // Note: The image itself is not saved; it must be reloaded after import + reader.ExportToXml(checkpointPath); } - // Simulate application restart: import settings, set image again, continue detection - using (var reader = BarCodeReader.ImportFromXml(checkpointPath)) + // ------------------------------------------------- + // Step 3: Reopen the reader from the checkpoint and continue detection + // ------------------------------------------------- + if (!File.Exists(checkpointPath)) { - if (reader == null) - { - Console.WriteLine("Failed to import reader state."); - return; - } + Console.WriteLine("Checkpoint file not found."); + return; + } - // The imported reader does not retain the image; set it explicitly - if (!File.Exists(imagePath)) - { - Console.WriteLine($"Image file not found: {imagePath}"); - return; - } - reader.SetBarCodeImage(imagePath); + // Import the saved settings; this creates a new BarCodeReader instance + using (var resumedReader = BarCodeReader.ImportFromXml(checkpointPath)) + { + // Reassign the image because ImportFromXml restores only settings + resumedReader.SetBarCodeImage(barcodePath); - // Continue detection from the imported state - foreach (var result in reader.ReadBarCodes()) + // Perform barcode detection using the resumed reader + foreach (var result in resumedReader.ReadBarCodes()) { - Console.WriteLine($"Second read – Type: {result.CodeTypeName}, Text: {result.CodeText}"); + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); } } } diff --git a/barcode-recognition-xml-serialization/create-function-that-accepts-image-stream-performs-recognition-and-returns-xml-state-as-string.cs b/barcode-recognition-xml-serialization/create-function-that-accepts-image-stream-performs-recognition-and-returns-xml-state-as-string.cs index 929c6e3..1adde4c 100644 --- a/barcode-recognition-xml-serialization/create-function-that-accepts-image-stream-performs-recognition-and-returns-xml-state-as-string.cs +++ b/barcode-recognition-xml-serialization/create-function-that-accepts-image-stream-performs-recognition-and-returns-xml-state-as-string.cs @@ -1,10 +1,12 @@ -// Title: Barcode recognition with XML state export -// Description: Demonstrates how to read barcodes from an image stream using Aspose.BarCode and export the reader's internal state as XML. +// Title: Recognize Barcode from Image Stream and Export XML State +// Description: Demonstrates how to read a barcode from an in‑memory image stream using Aspose.BarCode and return the reader’s XML state as a string. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category. It shows the use of BarCodeReader with DecodeType.AllSupportedTypes to detect any supported symbology, and how to export the reader configuration and results to XML via ExportToXml. Developers working on barcode scanning, automated data capture, or integration testing often need to programmatically obtain detailed recognition information in XML for logging or further processing. // Prompt: Create a function that accepts an image stream, performs recognition, and returns the XML state as a string. -// Tags: barcode, recognition, xml, aspose.barcode, stream +// Tags: barcode symbology, recognition, xml, aspose.barcode, aspose.barcode.generation, aspose.barcode.recognition using System; using System.IO; +using System.Text; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; @@ -12,36 +14,39 @@ using Aspose.Drawing.Imaging; /// -/// Sample program that generates a barcode, recognizes it from a stream, -/// and outputs the reader's XML state. +/// Example program that generates a barcode, recognizes it from a memory stream, +/// and returns the recognition results as an XML string. /// class Program { /// - /// Recognizes barcodes from an image stream and returns the reader's XML state. + /// Recognizes barcodes from the provided image stream and returns the reader's XML state. /// - /// Stream containing the barcode image. - /// XML string representing the reader's configuration and results. - static string RecognizeAndExportXml(Stream imageStream) + /// A stream containing the barcode image. + /// XML string representing the reader configuration and detection results. + static string RecognizeBarcodeXml(Stream imageStream) { - if (imageStream == null) - throw new ArgumentNullException(nameof(imageStream)); + // Ensure the stream is positioned at the beginning before reading. + if (imageStream.CanSeek) + { + imageStream.Position = 0; + } - // Initialize the reader with all supported decode types. + // Initialize the reader to detect all supported barcode types. using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes)) { - // Perform the actual recognition. + // Perform the recognition process. reader.ReadBarCodes(); - // Export the reader's configuration/state to XML. + // Export the reader's configuration and results to an in‑memory XML stream. using (var xmlStream = new MemoryStream()) { reader.ExportToXml(xmlStream); - xmlStream.Position = 0; // Reset stream position for reading. + xmlStream.Position = 0; // Reset position for reading. - using (var sr = new StreamReader(xmlStream)) + // Read the XML content as a UTF‑8 string. + using (var sr = new StreamReader(xmlStream, Encoding.UTF8)) { - // Return the entire XML content as a string. return sr.ReadToEnd(); } } @@ -49,26 +54,26 @@ static string RecognizeAndExportXml(Stream imageStream) } /// - /// Entry point that generates a sample barcode, runs recognition, and prints the XML state. + /// Entry point of the example. Generates a Code128 barcode, recognizes it, + /// and writes the resulting XML to the console. /// static void Main() { - // Create a sample barcode image in memory. + // Create a barcode generator for Code128 with sample data. using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - using (var bitmap = generator.GenerateBarCodeImage()) + // Store the generated barcode image in a memory stream. + using (var imageStream = new MemoryStream()) { - using (var imageStream = new MemoryStream()) - { - // Save the bitmap to a PNG stream. - bitmap.Save(imageStream, ImageFormat.Png); - imageStream.Position = 0; // Reset stream position for reading. + // Save the barcode as a PNG image. + generator.Save(imageStream, BarCodeImageFormat.Png); + imageStream.Position = 0; // Reset stream before recognition. - // Recognize and obtain XML state. - string xml = RecognizeAndExportXml(imageStream); - Console.WriteLine("Reader XML State:"); - Console.WriteLine(xml); - } + // Recognize the barcode and obtain the XML representation. + string xmlResult = RecognizeBarcodeXml(imageStream); + + // Output the XML result to the console. + Console.WriteLine(xmlResult); } } } diff --git a/barcode-recognition-xml-serialization/create-performance-benchmark-that-measures-time-taken-to-exporttoxml-and-importfromxml-for-large-barcode-datasets.cs b/barcode-recognition-xml-serialization/create-performance-benchmark-that-measures-time-taken-to-exporttoxml-and-importfromxml-for-large-barcode-datasets.cs index 6be6487..cf9a3fe 100644 --- a/barcode-recognition-xml-serialization/create-performance-benchmark-that-measures-time-taken-to-exporttoxml-and-importfromxml-for-large-barcode-datasets.cs +++ b/barcode-recognition-xml-serialization/create-performance-benchmark-that-measures-time-taken-to-exporttoxml-and-importfromxml-for-large-barcode-datasets.cs @@ -1,118 +1,97 @@ // Title: Benchmark ExportToXml and ImportFromXml for large barcode datasets -// Description: Demonstrates measuring the time required to export and import barcode definitions to/from XML, useful for performance analysis of bulk barcode processing. +// Description: Demonstrates measuring performance of exporting and importing barcode definitions to/from XML using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode performance benchmarking category, showcasing how to use BarcodeGenerator for Code128 symbology, export barcode settings to XML, and re-import them. Developers often need to evaluate serialization overhead when handling large barcode collections, and this snippet provides a baseline measurement using ExportToXml and ImportFromXml APIs. // Prompt: Create a performance benchmark that measures time taken to ExportToXml and ImportFromXml for large barcode datasets. -// Tags: barcode symbology, performance, xml, export, import, aspose.barcode +// Tags: barcode, performance, benchmark, exporttoxml, importfromxml, code128, aspose.barcode, serialization using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates a performance benchmark for exporting and importing barcode definitions using Aspose.BarCode. +/// Program that benchmarks ExportToXml and ImportFromXml performance for a set of barcodes. /// class Program { /// - /// Entry point. Generates a set of barcodes, exports them to XML, measures export time, - /// then imports them back and measures import time. + /// Entry point. Generates sample barcodes, exports them to XML, re-imports them, and reports elapsed times. /// static void Main() { - // Number of barcodes to process (kept small for safe execution) - const int barcodeCount = 5; + const int sampleCount = 5; // Number of barcode samples to generate + var xmlFiles = new List(); // Stores paths of generated XML files + var exportStopwatch = new Stopwatch(); // Measures export duration + var importStopwatch = new Stopwatch(); // Measures import duration - // Prepare temporary folder for XML files - string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeBenchmark"); - Directory.CreateDirectory(tempFolder); - - // Arrays to hold file paths for later import - string[] xmlFiles = new string[barcodeCount]; - - // ------------------- Export to XML Benchmark ------------------- - // Start timing the export operation - Stopwatch exportStopwatch = Stopwatch.StartNew(); - - for (int i = 0; i < barcodeCount; i++) + // ------------------------------------------------- + // Generate barcode data and export each to an XML file + // ------------------------------------------------- + exportStopwatch.Start(); + for (int i = 0; i < sampleCount; i++) { // Create a unique code text for each barcode - string codeText = $"Sample{i + 1}"; - // Determine the XML file path for this barcode - string xmlPath = Path.Combine(tempFolder, $"barcode_{i + 1}.xml"); - xmlFiles[i] = xmlPath; + string codeText = $"CODE{i}{new string('X', i + 5)}"; - // Generate the barcode and export its definition to XML + // Determine temporary file path for the XML representation + string xmlPath = Path.Combine(Path.GetTempPath(), $"barcode_{i}.xml"); + xmlFiles.Add(xmlPath); + + // Initialize generator with Code128 symbology and the generated text using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Export properties to XML file + // Optional: adjust X-dimension for demonstration purposes + generator.Parameters.Barcode.XDimension.Point = 2f; + + // Export the barcode definition to XML; check success flag bool exported = generator.ExportToXml(xmlPath); if (!exported) { - Console.WriteLine($"Export failed for barcode {i + 1}"); + Console.WriteLine($"Failed to export XML for barcode {i}"); } } } - - // Stop timing and report export duration exportStopwatch.Stop(); - Console.WriteLine($"ExportToXml: Processed {barcodeCount} barcodes in {exportStopwatch.ElapsedMilliseconds} ms"); - - // ------------------- Import from XML Benchmark ------------------- - // Start timing the import operation - Stopwatch importStopwatch = Stopwatch.StartNew(); - for (int i = 0; i < barcodeCount; i++) + // ------------------------------------------------- + // Import each previously exported XML and verify content + // ------------------------------------------------- + importStopwatch.Start(); + foreach (string xmlPath in xmlFiles) { - string xmlPath = xmlFiles[i]; - // Verify the XML file exists before attempting import - if (!File.Exists(xmlPath)) - { - Console.WriteLine($"XML file missing for barcode {i + 1}"); - continue; - } - - // Import creates a new BarcodeGenerator instance from the XML definition - using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath)) + // Recreate the generator from the XML file + using (var generator = BarcodeGenerator.ImportFromXml(xmlPath)) { - // Optionally, verify that the imported code text matches expectation - // (not required for timing, but demonstrates usage) - // Console.WriteLine($"Imported CodeText: {importedGenerator.CodeText}"); + // Access properties to ensure the object is correctly initialized + Console.WriteLine($"Imported barcode type: {generator.BarcodeType.TypeName}, CodeText: {generator.CodeText}"); } } - - // Stop timing and report import duration importStopwatch.Stop(); - Console.WriteLine($"ImportFromXml: Processed {barcodeCount} barcodes in {importStopwatch.ElapsedMilliseconds} ms"); - // Cleanup temporary XML files - foreach (var file in xmlFiles) + // ------------------------------------------------- + // Output benchmark results + // ------------------------------------------------- + Console.WriteLine($"Export to XML time for {sampleCount} barcodes: {exportStopwatch.ElapsedMilliseconds} ms"); + Console.WriteLine($"Import from XML time for {sampleCount} barcodes: {importStopwatch.ElapsedMilliseconds} ms"); + + // ------------------------------------------------- + // Clean up temporary XML files + // ------------------------------------------------- + foreach (string xmlPath in xmlFiles) { try { - if (File.Exists(file)) + if (File.Exists(xmlPath)) { - File.Delete(file); + File.Delete(xmlPath); } } - catch + catch (Exception ex) { - // Ignore any cleanup errors + Console.WriteLine($"Could not delete file {xmlPath}: {ex.Message}"); } } - - // Remove the temporary folder - try - { - if (Directory.Exists(tempFolder)) - { - Directory.Delete(tempFolder, true); - } - } - catch - { - // Ignore any cleanup errors - } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/create-scheduled-job-that-periodically-exports-reader-state-to-xml-for-audit-logging-of-processed-barcodes.cs b/barcode-recognition-xml-serialization/create-scheduled-job-that-periodically-exports-reader-state-to-xml-for-audit-logging-of-processed-barcodes.cs index 384fe87..7fa72da 100644 --- a/barcode-recognition-xml-serialization/create-scheduled-job-that-periodically-exports-reader-state-to-xml-for-audit-logging-of-processed-barcodes.cs +++ b/barcode-recognition-xml-serialization/create-scheduled-job-that-periodically-exports-reader-state-to-xml-for-audit-logging-of-processed-barcodes.cs @@ -1,73 +1,87 @@ -// Title: Scheduled Export of Barcode Reader State to XML -// Description: Demonstrates generating barcodes, reading them, and exporting the reader state to XML for audit logging. +// Title: Scheduled barcode processing with XML audit export +// Description: Demonstrates generating Code128 barcodes, reading them, and exporting the reader state to XML for audit logging. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeReader for decoding them, and the ExportToXml method for persisting reader state. Developers often need such patterns for batch processing, scheduled jobs, and compliance auditing where a detailed record of barcode scans is required. // Prompt: Create a scheduled job that periodically exports reader state to XML for audit logging of processed barcodes. -// Tags: barcode symbology, generation, recognition, xml, audit logging, scheduled job +// Tags: code128, generation, recognition, xml, audit, export using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing.Imaging; +using Aspose.Drawing; /// -/// Example program that generates sample barcodes, reads them, and exports the reader state to XML. -/// Intended to be invoked by an external scheduler for periodic audit logging. +/// Example program that generates barcodes, reads them, and exports the reader state to XML for audit purposes. /// class Program { /// - /// Entry point of the console application. - /// Generates barcodes, reads them, and writes the reader state to XML files. + /// Entry point of the application. Generates sample barcodes, reads them, logs results, and exports reader state. /// static void Main() { - // Define sample barcodes with their symbology and corresponding code text. - var samples = new (BaseEncodeType EncodeType, string CodeText)[] - { - (EncodeTypes.Code128, "Sample123"), - (EncodeTypes.QR, "https://example.com"), - (EncodeTypes.DatabarStacked, "(01)01234567890123") - }; + // Prepare directory for generated barcode images + string imageDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(imageDir); + + // Initialize human‑readable audit log file + string auditLogPath = Path.Combine(Directory.GetCurrentDirectory(), "audit.log"); + File.WriteAllText(auditLogPath, $"Audit Log - Started at {DateTime.Now}{Environment.NewLine}"); - // Iterate over each sample barcode definition. - for (int i = 0; i < samples.Length; i++) + // Sample data to encode into barcodes + string[] sampleTexts = { "ABC123", "987XYZ", "Test001" }; + + // Process each sample text + foreach (string text in sampleTexts) { - var (encodeType, codeText) = samples[i]; + // Define paths for the barcode image and the corresponding XML export + string imagePath = Path.Combine(imageDir, $"{text}.png"); + string xmlPath = Path.Combine(imageDir, $"{text}_reader.xml"); - // Generate a barcode image and store it in a memory stream. - using (var generator = new BarcodeGenerator(encodeType, codeText)) - using (var imageStream = new MemoryStream()) + // ---------- Barcode Generation ---------- + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text)) { - // Save the generated barcode as a PNG image into the stream. - generator.Save(imageStream, BarCodeImageFormat.Png); - imageStream.Position = 0; // Reset stream position for subsequent reading. + // Optional: customize generation parameters + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.Barcode.BarHeight.Point = 40f; - // Initialize a barcode reader to decode all supported types from the image stream. - using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes)) - { - Console.WriteLine($"Reading barcode {i + 1}: {encodeType.TypeName}"); + // Save the generated barcode as a PNG image + generator.Save(imagePath, BarCodeImageFormat.Png); + } - // Enumerate and display each detected barcode result. - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($" Detected Type: {result.CodeTypeName}"); - Console.WriteLine($" CodeText: {result.CodeText}"); - } + // Verify that the image file was created successfully + if (!File.Exists(imagePath)) + { + File.AppendAllText(auditLogPath, $"Image not found: {imagePath}{Environment.NewLine}"); + continue; + } - // Export the internal reader state to an XML file for audit purposes. - string xmlPath = $"ReaderState_{i + 1}_{DateTime.Now:yyyyMMdd_HHmmss}.xml"; - bool exported = reader.ExportToXml(xmlPath); - Console.WriteLine(exported - ? $" Reader state exported to: {xmlPath}" - : $" Failed to export reader state for barcode {i + 1}"); + // ---------- Barcode Reading & Audit ---------- + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + { + // Read all barcodes present in the image + foreach (var result in reader.ReadBarCodes()) + { + // Log each detection result to the audit file + string logEntry = $"[{DateTime.Now}] Image: {Path.GetFileName(imagePath)}, " + + $"Type: {result.CodeType}, Text: {result.CodeText}"; + File.AppendAllText(auditLogPath, logEntry + Environment.NewLine); } - } - Console.WriteLine(); // Add a blank line as a visual separator between samples. + // Export the reader's internal state to XML for detailed audit logging + try + { + reader.ExportToXml(xmlPath); + File.AppendAllText(auditLogPath, $"Exported reader state to XML: {xmlPath}{Environment.NewLine}"); + } + catch (Exception ex) + { + File.AppendAllText(auditLogPath, $"Failed to export XML for {imagePath}: {ex.Message}{Environment.NewLine}"); + } + } } - // Note: This console application runs once and exits. - // To schedule periodic execution, configure an external scheduler (e.g., Windows Task Scheduler) to run this program at desired intervals. + // Finalize audit log + File.AppendAllText(auditLogPath, $"Audit Log - Completed at {DateTime.Now}{Environment.NewLine}"); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/create-unit-test-that-ensures-importfromxml-throws-exception-when-called-without-prior-setbarcodeimage-invocation.cs b/barcode-recognition-xml-serialization/create-unit-test-that-ensures-importfromxml-throws-exception-when-called-without-prior-setbarcodeimage-invocation.cs index 5b55273..916e686 100644 --- a/barcode-recognition-xml-serialization/create-unit-test-that-ensures-importfromxml-throws-exception-when-called-without-prior-setbarcodeimage-invocation.cs +++ b/barcode-recognition-xml-serialization/create-unit-test-that-ensures-importfromxml-throws-exception-when-called-without-prior-setbarcodeimage-invocation.cs @@ -1,71 +1,75 @@ -// Title: Unit test for ImportFromXml without prior SetBarCodeImage -// Description: Demonstrates a test that verifies ImportFromXml throws an exception when called before initializing a barcode image. +// Title: Unit test for ImportFromXml without SetBarCodeImage +// Description: Demonstrates a test that verifies ImportFromXml throws an exception when no barcode image has been set. +// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on XML import operations. It showcases the use of BarcodeGenerator.ImportFromXml and the requirement to call SetBarCodeImage before generating output. Developers working with barcode creation, configuration via XML, and error handling will find this pattern useful for building robust unit tests. // Prompt: Create a unit test that ensures ImportFromXml throws an exception when called without prior SetBarCodeImage invocation. -// Tags: barcode, importfromxml, exception, unit-test, aspose.barcode +// Tags: barcode, import, xml, generation, aspose.barcode using System; using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.BarCodeRecognition; +using Aspose.BarCode.Generation; /// -/// Contains the entry point demonstrating a unit‑test‑like verification that -/// throws when no barcode image has been set. +/// Contains a simple console‑based unit test that validates the behavior of +/// when no barcode image has been +/// configured via SetBarCodeImage. The test expects an exception to be thrown. /// class Program { /// - /// Executes the test: creates a temporary XML file, attempts to import barcode settings, - /// and validates that an exception is thrown because SetBarCodeImage was not called first. + /// Entry point of the test application. Creates a temporary XML file with minimal + /// content, attempts to import it, and asserts that an exception occurs because + /// the barcode image has not been set beforehand. /// static void Main() { - // Create a temporary XML file with minimal content. - string tempXmlPath = Path.GetTempFileName(); + // -------------------------------------------------------------------- + // Arrange: create a temporary XML file containing an empty BarcodeGenerator element. + // -------------------------------------------------------------------- + string tempXmlPath = Path.Combine(Path.GetTempPath(), "invalid_barcode.xml"); + File.WriteAllText(tempXmlPath, ""); + + bool exceptionThrown = false; try { - // Write a simple, empty element to the temp file. - File.WriteAllText(tempXmlPath, ""); - - bool exceptionThrown = false; - - try - { - // Attempt to import settings without setting a barcode image first. - // According to Aspose.BarCode behavior, this should raise an exception. - BarCodeReader reader = BarCodeReader.ImportFromXml(tempXmlPath); - - // If ImportFromXml returns without exception, dispose the reader if it was created. - if (reader != null) - { - reader.Dispose(); - } - } - catch (Exception ex) - { - // Expected path: an exception is thrown. - exceptionThrown = true; - Console.WriteLine($"Expected exception caught: {ex.GetType().Name} - {ex.Message}"); - } - - // Report the test outcome based on whether an exception was caught. - if (exceptionThrown) + // ---------------------------------------------------------------- + // Act: try to import the XML without having called SetBarCodeImage. + // According to the API contract, this should raise an exception. + // ---------------------------------------------------------------- + using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(tempXmlPath)) { - Console.WriteLine("Test passed: ImportFromXml threw an exception as expected."); - } - else - { - Console.WriteLine("Test failed: ImportFromXml did not throw an exception."); + // If ImportFromXml unexpectedly succeeds, attempt to save an image. + // This call will also fail because the required image data is missing. + generator.Save("should_not_be_created.png"); } } + catch (Exception ex) + { + // ---------------------------------------------------------------- + // Assert: an exception was caught as expected. + // Record the occurrence and output diagnostic information. + // ---------------------------------------------------------------- + exceptionThrown = true; + Console.WriteLine($"Expected exception caught: {ex.GetType().Name} - {ex.Message}"); + } finally { - // Clean up the temporary file. + // ---------------------------------------------------------------- + // Cleanup: delete the temporary XML file and any generated image file. + // ---------------------------------------------------------------- if (File.Exists(tempXmlPath)) - { File.Delete(tempXmlPath); - } + + if (File.Exists("should_not_be_created.png")) + File.Delete("should_not_be_created.png"); } + + // -------------------------------------------------------------------- + // Report the test result. + // -------------------------------------------------------------------- + if (exceptionThrown) + Console.WriteLine("Test passed: ImportFromXml threw an exception as expected."); + else + Console.WriteLine("Test failed: ImportFromXml did not throw an exception."); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/demonstrate-how-to-use-exporttoxml-stream-to-send-barcode-recognition-state-over-network-socket.cs b/barcode-recognition-xml-serialization/demonstrate-how-to-use-exporttoxml-stream-to-send-barcode-recognition-state-over-network-socket.cs index 4255558..c4fcae4 100644 --- a/barcode-recognition-xml-serialization/demonstrate-how-to-use-exporttoxml-stream-to-send-barcode-recognition-state-over-network-socket.cs +++ b/barcode-recognition-xml-serialization/demonstrate-how-to-use-exporttoxml-stream-to-send-barcode-recognition-state-over-network-socket.cs @@ -1,7 +1,8 @@ -// Title: Export barcode recognition state to XML over a network socket -// Description: Generates a barcode, recognizes it, exports the recognition state as XML, and transmits it via a TCP socket. +// Title: Export barcode recognition state to XML and transmit via TCP +// Description: Demonstrates generating a Code128 barcode, recognizing it, exporting the recognition state to XML, and sending that XML over a TCP socket. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to use BarcodeGenerator, BarCodeReader, and the ExportToXml(Stream) method. Typical use cases include transmitting barcode scan results between services or perserving recognition state. Developers often need to serialize recognition data for network communication or later analysis. // Prompt: Demonstrate how to use ExportToXml(Stream) to send barcode recognition state over a network socket. -// Tags: barcode, recognition, export, xml, network, socket, aspose +// Tags: code128, exporttoxml, xml, network, aspose.barcode, generation, recognition using System; using System.IO; @@ -10,74 +11,77 @@ using System.Threading.Tasks; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// /// Demonstrates generating a barcode, recognizing it, exporting the recognition state to XML, -/// and sending that XML over a TCP socket. +/// and transmitting that XML over a TCP socket using Aspose.BarCode APIs. /// class Program { /// - /// Entry point of the example. Executes the barcode generation, recognition, export, and network transmission. + /// Entry point of the example. Executes the barcode generation, recognition, XML export, + /// and network transmission steps. /// static void Main() { - // Generate a simple Code128 barcode image in memory. + // Step 1: Generate a simple Code128 barcode image in memory. using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345")) { - using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) + using (var barcodeStream = new MemoryStream()) { - // Create a reader for the generated image and perform recognition of all supported types. - using (var reader = new BarCodeReader(barcodeImage, DecodeType.AllSupportedTypes)) + // Save the barcode image to a memory stream (PNG format). + generator.Save(barcodeStream, BarCodeImageFormat.Png); + barcodeStream.Position = 0; // Reset stream position for reading. + + // Step 2: Create a BarCodeReader to recognize the barcode from the stream. + using (var reader = new BarCodeReader(barcodeStream, DecodeType.AllSupportedTypes)) { - // Output each detected barcode to the console. + // Perform recognition to populate internal state (optional). foreach (var result in reader.ReadBarCodes()) { Console.WriteLine($"Detected: {result.CodeTypeName} - {result.CodeText}"); } - // Export the recognition state to a memory stream in XML format. - using (var stateStream = new MemoryStream()) + // Step 3: Export the recognition state to an XML memory stream. + using (var xmlStateStream = new MemoryStream()) { - bool exported = reader.ExportToXml(stateStream); - Console.WriteLine($"Exported to XML: {exported}"); - - // Set up a TCP listener that will act as the server receiving the XML data. - using (var listener = new TcpListener(IPAddress.Loopback, 5000)) - { - listener.Start(); + reader.ExportToXml(xmlStateStream); + xmlStateStream.Position = 0; // Prepare stream for sending. - // Accept the incoming connection on a background task. - Task acceptTask = Task.Run(() => - { - using (TcpClient serverClient = listener.AcceptTcpClient()) - using (NetworkStream serverStream = serverClient.GetStream()) - using (var receivedStream = new MemoryStream()) - { - // Copy the incoming XML data into a memory stream. - serverStream.CopyTo(receivedStream); - Console.WriteLine($"Server received {receivedStream.Length} bytes of XML data."); - } - }); + // Step 4: Set up a TCP listener (server) on localhost. + const int port = 5000; + var listener = new TcpListener(IPAddress.Loopback, port); + listener.Start(); - // Connect as a client and send the XML data over the socket. + // Step 5: Start a client task that connects to the server. + var clientTask = Task.Run(() => + { using (var client = new TcpClient()) { - client.Connect(IPAddress.Loopback, 5000); - using (NetworkStream clientStream = client.GetStream()) + client.Connect(IPAddress.Loopback, port); + // Keep the connection open; no data is read in this demo. + using (var ns = client.GetStream()) { - // Reset the position of the state stream before sending. - stateStream.Position = 0; - stateStream.CopyTo(clientStream); - Console.WriteLine("Client sent XML data over the socket."); + // Placeholder for potential client-side read logic. } } + }); - // Wait for the server side to finish processing the received data. - acceptTask.Wait(); - listener.Stop(); + // Step 6: Accept the client connection on the server side. + using (var serverClient = listener.AcceptTcpClient()) + using (var networkStream = serverClient.GetStream()) + { + // Send the XML state over the network stream. + xmlStateStream.CopyTo(networkStream); + networkStream.Flush(); + Console.WriteLine("Barcode recognition state sent over network."); } + + // Clean up the listener. + listener.Stop(); + + // Ensure the client task completes before exiting. + clientTask.Wait(); } } } diff --git a/barcode-recognition-xml-serialization/deserialize-reader-state-from-xml-stream-then-reapply-same-barcode-image-for-analysis.cs b/barcode-recognition-xml-serialization/deserialize-reader-state-from-xml-stream-then-reapply-same-barcode-image-for-analysis.cs index 8abcddf..959cf59 100644 --- a/barcode-recognition-xml-serialization/deserialize-reader-state-from-xml-stream-then-reapply-same-barcode-image-for-analysis.cs +++ b/barcode-recognition-xml-serialization/deserialize-reader-state-from-xml-stream-then-reapply-same-barcode-image-for-analysis.cs @@ -1,7 +1,8 @@ -// Title: Deserialize and Reapply Barcode Image for Recognition -// Description: Demonstrates exporting a BarCodeReader's configuration to XML, then importing it into a new reader and applying the same barcode image for analysis. +// Title: Deserialize BarCodeReader state from XML and reuse the same image +// Description: Demonstrates exporting a BarCodeReader's state to an XML stream, importing it back, and reapplying the original barcode image for further analysis. +// Category-Description: This example belongs to the Aspose.BarCode serialization and deserialization category. It showcases the use of BarCodeReader.ExportToXml, BarCodeReader.ImportFromXml, and related classes such as BarcodeGenerator. Developers often need to persist reader configurations, share them across services, or reload them for repeated scans without reconfiguring the reader each time. // Prompt: Deserialize the reader state from an XML stream, then reapply the same barcode image for analysis. -// Tags: barcode, serialization, deserialization, xml, recognition, code128, aspose.barcode +// Tags: code128, serialization, png, barcodereader, barcodegenerator using System; using System.IO; @@ -11,50 +12,71 @@ using Aspose.Drawing; /// -/// Example program that shows how to export a BarCodeReader's state to XML, -/// import it into a new reader instance, and reuse the same barcode image for detection. +/// Example program that generates a Code128 barcode, exports the reader state to XML, +/// imports it back, and reuses the same image for barcode recognition. /// class Program { /// - /// Entry point. Generates a barcode, exports reader settings to XML, - /// imports them into a new reader, and reads the barcode again. + /// Entry point of the example. Performs barcode generation, state serialization, + /// deserialization, and recognition without requiring interactive console input. /// static void Main() { - // Generate a sample barcode image (Code128) - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Define the barcode text to encode. + const string codeText = "1234567890"; + + // Path for the temporary PNG image that will hold the generated barcode. + const string imagePath = "temp_barcode.png"; + + // Generate a Code128 barcode and save it as a PNG file. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + generator.Save(imagePath, BarCodeImageFormat.Png); + } + + // Load the generated PNG image into a bitmap for processing. + using (var bitmap = new Bitmap(imagePath)) { - using (var barcodeImage = generator.GenerateBarCodeImage()) + // Initialize a BarCodeReader and configure it to decode Code128 symbology. + using (var reader = new BarCodeReader()) { - // Create a reader for the generated image - using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128)) + reader.SetBarCodeReadType(DecodeType.Code128); + reader.SetBarCodeImage(bitmap); + + // Export the current reader configuration and state to an in‑memory XML stream. + using (var xmlStream = new MemoryStream()) { - // Export the reader's state to an XML stream - using (var exportStream = new MemoryStream()) + reader.ExportToXml(xmlStream); + xmlStream.Position = 0; // Reset stream position for subsequent reading. + + // Import the previously saved state into a new BarCodeReader instance. + var importedReader = BarCodeReader.ImportFromXml(xmlStream); + + // Reassign the same bitmap image to the imported reader for analysis. + importedReader.SetBarCodeImage(bitmap); + + // Execute barcode recognition and output results to the console. + foreach (var result in importedReader.ReadBarCodes()) { - reader.ExportToXml(exportStream); - exportStream.Position = 0; // Reset stream position for reading - - // Create a new reader instance without initial image - using (var newReader = new BarCodeReader()) - { - // Import the previously exported settings into the new reader - BarCodeReader.ImportFromXml(exportStream); - - // Apply the same barcode image to the new reader - newReader.SetBarCodeImage(barcodeImage); - - // Perform recognition using the imported settings - foreach (var result in newReader.ReadBarCodes()) - { - Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Detected Text: {result.CodeText}"); - } - } + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Detected Text: {result.CodeText}"); } } } } + + // Attempt to delete the temporary image file; ignore any errors that occur. + if (File.Exists(imagePath)) + { + try + { + File.Delete(imagePath); + } + catch + { + // Suppress cleanup exceptions. + } + } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/design-configuration-file-that-specifies-default-xml-export-directory-and-integrates-it-with-exporttoxml-calls.cs b/barcode-recognition-xml-serialization/design-configuration-file-that-specifies-default-xml-export-directory-and-integrates-it-with-exporttoxml-calls.cs index 6fb7b67..e3bdd2d 100644 --- a/barcode-recognition-xml-serialization/design-configuration-file-that-specifies-default-xml-export-directory-and-integrates-it-with-exporttoxml-calls.cs +++ b/barcode-recognition-xml-serialization/design-configuration-file-that-specifies-default-xml-export-directory-and-integrates-it-with-exporttoxml-calls.cs @@ -1,7 +1,8 @@ -// Title: Export Barcode Generator Settings to XML Using Configurable Directory -// Description: Demonstrates loading a JSON configuration to determine the export folder and then exporting barcode generator settings to an XML file. +// Title: Export barcode configuration to XML using Aspose.BarCode +// Description: Demonstrates loading a JSON configuration to set the default export directory and exporting a Code128 barcode generator's settings to an XML file. +// Category-Description: This example belongs to the Aspose.BarCode configuration export category, illustrating how to use the BarcodeGenerator class together with ExportToXml for persisting barcode settings. Developers often need to store generator parameters for later reuse or auditing, and this pattern shows reading configuration files, ensuring directories exist, and performing XML export—common tasks in automated barcode workflows. // Prompt: Design a configuration file that specifies the default XML export directory and integrates it with ExportToXml calls. -// Tags: barcode symbology, export, xml, configuration, aspnet, aspose.barcodes +// Tags: barcode symbology, export, xml, configuration, aspnet, aspose.barcode, code128, json using System; using System.IO; @@ -9,79 +10,92 @@ using Aspose.BarCode; using Aspose.BarCode.Generation; -namespace BarcodeExportConfigExample +namespace BarcodeExportExample { /// - /// Simple configuration class matching the JSON structure. - /// Contains the default directory where exported XML files are saved. + /// Represents application configuration loaded from a JSON file. /// public class AppConfig { + /// + /// Directory where XML exports will be saved. + /// public string ExportDirectory { get; set; } = "Export"; } + /// + /// Demonstrates loading configuration, ensuring export directory, generating a Code128 barcode, + /// and exporting its settings to XML. + /// class Program { /// /// Entry point of the example. - /// Loads configuration, ensures the export directory exists, generates a barcode, - /// and exports its settings to an XML file in the configured location. /// static void Main() { - // Load configuration from "config.json" if it exists; otherwise use defaults. - var config = LoadConfiguration("config.json"); + // Path to the JSON configuration file. + const string configPath = "config.json"; + AppConfig config; - // Ensure the export directory exists; create it if necessary. - if (!Directory.Exists(config.ExportDirectory)) + // Load existing configuration or create a default one. + if (File.Exists(configPath)) { - Directory.CreateDirectory(config.ExportDirectory); + try + { + string json = File.ReadAllText(configPath); + config = JsonSerializer.Deserialize(json) ?? new AppConfig(); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to read config file: {ex.Message}"); + config = new AppConfig(); + } } - - // Create a barcode generator for Code128 with sample text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + else { - // Optional: customize barcode appearance here if needed. - // e.g., generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; - - // Build the full path for the exported XML file. - string xmlPath = Path.Combine(config.ExportDirectory, "barcode_properties.xml"); - - // Export generator settings to XML file. - bool exported = generator.ExportToXml(xmlPath); - Console.WriteLine(exported - ? $"Barcode configuration exported successfully to: {xmlPath}" - : $"Failed to export barcode configuration to: {xmlPath}"); + // No config file – use defaults and persist them for future runs. + config = new AppConfig(); + try + { + string json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText(configPath, json); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to write default config file: {ex.Message}"); + } } - } - /// - /// Reads configuration from a JSON file; falls back to defaults on any error. - /// - /// Path to the JSON configuration file. - /// An instance with loaded or default values. - private static AppConfig LoadConfiguration(string filePath) - { - // If the config file does not exist, return a new instance with default values. - if (!File.Exists(filePath)) + // Ensure the export directory exists. + if (!Directory.Exists(config.ExportDirectory)) { - return new AppConfig(); + try + { + Directory.CreateDirectory(config.ExportDirectory); + } + catch (Exception ex) + { + Console.WriteLine($"Unable to create export directory '{config.ExportDirectory}': {ex.Message}"); + return; + } } - try + // Create a simple Code128 barcode generator. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Read the entire JSON content. - string json = File.ReadAllText(filePath); - var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; - // Deserialize JSON into AppConfig; if null, use defaults. - var config = JsonSerializer.Deserialize(json, options); - return config ?? new AppConfig(); - } - catch (Exception ex) - { - // Log any errors and revert to default configuration. - Console.WriteLine($"Error loading configuration: {ex.Message}"); - return new AppConfig(); + // Optional: customize appearance. + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.Barcode.BarHeight.Point = 40f; + + // Build the full path for the XML export file. + string xmlFilePath = Path.Combine(config.ExportDirectory, "barcode_export.xml"); + + // Export generator settings to XML. + bool exportSuccess = generator.ExportToXml(xmlFilePath); + Console.WriteLine(exportSuccess + ? $"Barcode configuration exported successfully to '{xmlFilePath}'." + : $"Failed to export barcode configuration to '{xmlFilePath}'."); } } } diff --git a/barcode-recognition-xml-serialization/design-logging-mechanism-that-records-file-path-used-in-setbarcodeimage-alongside-exported-xml-state.cs b/barcode-recognition-xml-serialization/design-logging-mechanism-that-records-file-path-used-in-setbarcodeimage-alongside-exported-xml-state.cs index df80b3f..7bf45e1 100644 --- a/barcode-recognition-xml-serialization/design-logging-mechanism-that-records-file-path-used-in-setbarcodeimage-alongside-exported-xml-state.cs +++ b/barcode-recognition-xml-serialization/design-logging-mechanism-that-records-file-path-used-in-setbarcodeimage-alongside-exported-xml-state.cs @@ -1,69 +1,97 @@ -// Title: Barcode generation, export to XML, and logging of image path -// Description: Demonstrates creating a Code128 barcode, saving it as an image, exporting the generator state to XML, and logging the image path used during barcode reading. +// Title: Barcode generation with XML export and logging of image path +// Description: Demonstrates creating a Code128 barcode, exporting its generator state to XML, and logging the image file path used in SetBarCodeImage. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to use BarcodeGenerator to create barcodes, export generator settings to XML, and employ BarCodeReader with SetBarCodeImage for image-based recognition. Developers often need to persist barcode configurations, debug image handling, and maintain logs of processing steps; this snippet illustrates those common tasks using key classes like BarcodeGenerator, BarCodeReader, and related parameters. // Prompt: Design a logging mechanism that records the file path used in SetBarCodeImage alongside the exported XML state. -// Tags: barcode symbology, generation, export, xml, logging, aspose.barcode, aspose.drawing +// Tags: barcode symbology, generation, recognition, xml export, logging, code128, aspose.barcode using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Example program that generates a barcode, exports its configuration to XML, -/// and logs the image path used when reading the barcode. +/// Demonstrates barcode generation, XML export, and logging of the image path used in SetBarCodeImage. /// class Program { /// - /// Entry point of the example. Performs barcode generation, XML export, - /// and reads the barcode while logging relevant information. + /// Entry point of the example. Generates a barcode, exports its state, and logs relevant information. /// static void Main() { - // Define file paths for the barcode image and the exported XML - string imagePath = "barcode.png"; - string xmlPath = "barcode.xml"; + // ------------------------------------------------------------ + // Prepare output folder + // ------------------------------------------------------------ + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "output"); + if (!Directory.Exists(outputFolder)) + { + Directory.CreateDirectory(outputFolder); + } + + // ------------------------------------------------------------ + // Define file paths for the barcode image, exported XML, and log file + // ------------------------------------------------------------ + string barcodePath = Path.Combine(outputFolder, "barcode.png"); + string xmlPath = Path.Combine(outputFolder, "generator.xml"); + string logPath = Path.Combine(outputFolder, "log.txt"); - // Generate a Code128 barcode, save the image, and export generator settings to XML + // ------------------------------------------------------------ + // Generate a simple Code128 barcode and save it as PNG + // ------------------------------------------------------------ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Save the generated barcode image to the specified path - generator.Save(imagePath); + // Example of setting a parameter (optional) + generator.Parameters.Barcode.XDimension.Point = 2f; - // Export the generator's current state (settings) to an XML file + // Save the barcode image to the specified path + generator.Save(barcodePath, BarCodeImageFormat.Png); + + // Export the generator's configuration/state to an XML file generator.ExportToXml(xmlPath); } - // Retrieve the exported XML content if the file was created successfully - string xmlContent = File.Exists(xmlPath) ? File.ReadAllText(xmlPath) : "XML file not found."; + // ------------------------------------------------------------ + // Read the exported XML content for later logging + // ------------------------------------------------------------ + string xmlContent = File.Exists(xmlPath) ? File.ReadAllText(xmlPath) : "XML export not found."; - // Initialize a BarCodeReader to read barcodes from the saved image - using (var reader = new BarCodeReader()) + // ------------------------------------------------------------ + // Load the barcode image and log the file path used in SetBarCodeImage + // ------------------------------------------------------------ + if (File.Exists(barcodePath)) { - // Verify that the barcode image file exists before attempting to load it - if (File.Exists(imagePath)) - { - // Log the file path that will be passed to SetBarCodeImage - Console.WriteLine($"Calling SetBarCodeImage with path: {imagePath}"); - reader.SetBarCodeImage(imagePath); - } - else + using (var bitmap = (Bitmap)Image.FromFile(barcodePath)) { - // Inform the user that the expected image file could not be found - Console.WriteLine($"Image file not found: {imagePath}"); - } + // Create a BarCodeReader instance (parameterless constructor is available) + using (var reader = new BarCodeReader()) + { + // Log the file path used in SetBarCodeImage + string logEntry = $"SetBarCodeImage called with path: {barcodePath}{Environment.NewLine}"; + File.AppendAllText(logPath, logEntry); - // Log the previously exported XML state for diagnostic purposes - Console.WriteLine("Exported XML state:"); - Console.WriteLine(xmlContent); + // Set the image for the reader (no actual read performed here) + reader.SetBarCodeImage(bitmap); - // Read and display any barcodes detected in the image - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"Detected barcode: Type={result.CodeTypeName}, Text={result.CodeText}"); + // Optionally perform a read (not required for logging) + // var results = reader.ReadBarCodes(); + } } } + else + { + // Log a warning if the barcode image could not be found + File.AppendAllText(logPath, $"Warning: Barcode image not found at {barcodePath}{Environment.NewLine}"); + } + + // ------------------------------------------------------------ + // Append the exported XML state to the log file + // ------------------------------------------------------------ + File.AppendAllText(logPath, $"Exported XML State:{Environment.NewLine}{xmlContent}{Environment.NewLine}"); + + // ------------------------------------------------------------ + // Indicate completion to the user + // ------------------------------------------------------------ + Console.WriteLine("Barcode generation, XML export, and logging completed."); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/design-unit-test-that-verifies-importfromxml-correctly-restores-results-after-exporting-to-temporary-xml-file.cs b/barcode-recognition-xml-serialization/design-unit-test-that-verifies-importfromxml-correctly-restores-results-after-exporting-to-temporary-xml-file.cs index 738d6cc..c53aa09 100644 --- a/barcode-recognition-xml-serialization/design-unit-test-that-verifies-importfromxml-correctly-restores-results-after-exporting-to-temporary-xml-file.cs +++ b/barcode-recognition-xml-serialization/design-unit-test-that-verifies-importfromxml-correctly-restores-results-after-exporting-to-temporary-xml-file.cs @@ -1,133 +1,101 @@ -// Title: ImportFromXml restores barcode generator settings -// Description: Demonstrates exporting a barcode generator's configuration to XML, importing it back, and verifying that the settings and generated barcode are identical. +// Title: Verify ImportFromXml restores barcode generator settings +// Description: Demonstrates exporting barcode generator settings to XML, importing them back, and confirming that the barcode can be read correctly. +// Category-Description: This example belongs to the Aspose.BarCode settings management category, illustrating how to use BarcodeGenerator.ExportToXml and BarcodeGenerator.ImportFromXml. It shows typical use cases such as persisting barcode configurations, sharing them across applications, and validating that imported settings produce the expected barcode output. Developers working with barcode generation and recognition often need to serialize settings for reuse or deployment, and this snippet provides a clear reference. // Prompt: Design a unit test that verifies ImportFromXml correctly restores results after exporting to a temporary XML file. -// Tags: barcode, import, export, xml, unit-test, aspose.barcode +// Tags: barcode symbology, export, import, xml, unit-test, settings, generation, recognition using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Example program that exports a barcode generator configuration to XML, -/// imports it back, and validates that the restored settings produce the same barcode. +/// Example program that exports barcode generator settings to XML, +/// imports them back, and validates that the restored settings generate +/// a readable barcode image. /// class Program { /// - /// Entry point of the example. Executes the export, import, and verification steps. + /// Entry point of the example. Performs the export, import, and validation steps. /// static void Main() { - // ------------------------------------------------------------ - // Prepare temporary file paths for XML configuration and barcode image - // ------------------------------------------------------------ - string xmlPath = Path.Combine(Path.GetTempPath(), "barcode_config.xml"); - string imagePath = Path.Combine(Path.GetTempPath(), "barcode_image.png"); + // Prepare temporary file paths for the XML settings and barcode image. + string xmlPath = Path.Combine(Path.GetTempPath(), "barcode_settings.xml"); + string imgPath = Path.Combine(Path.GetTempPath(), "barcode_image.png"); - // ------------------------------------------------------------ - // Create original barcode generator with custom visual settings - // ------------------------------------------------------------ - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) + // Create the original barcode generator with QR symbology and sample text. + using (var originalGenerator = new BarcodeGenerator(EncodeTypes.QR, "Test123")) { - // Set visual appearance - generator.Parameters.Barcode.BarColor = Color.Blue; - generator.Parameters.Barcode.XDimension.Point = 2f; - generator.Parameters.Barcode.Padding.Left.Point = 5f; - generator.Parameters.Barcode.Padding.Top.Point = 5f; - generator.Parameters.Barcode.Padding.Right.Point = 5f; - generator.Parameters.Barcode.Padding.Bottom.Point = 5f; - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; + // Set a custom XDimension to verify that the value is restored after import. + originalGenerator.Parameters.Barcode.XDimension.Point = 2f; - // Export the generator's configuration to an XML file - bool exportSuccess = generator.ExportToXml(xmlPath); + // Export the generator's configuration to an XML file. + bool exportSuccess = originalGenerator.ExportToXml(xmlPath); if (!exportSuccess) { Console.WriteLine("FAILED: ExportToXml returned false."); return; } - // Save the generated barcode image (used later for visual verification) - generator.Save(imagePath, BarCodeImageFormat.Png); + // Save a barcode image (used later for recognition). + originalGenerator.Save(imgPath); } - // ------------------------------------------------------------ - // Import the configuration from XML into a new generator instance - // ------------------------------------------------------------ - using (BarcodeGenerator imported = BarcodeGenerator.ImportFromXml(xmlPath)) + // Import the generator settings from the previously saved XML file. + BarcodeGenerator importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath); + if (importedGenerator == null) { - // Verify that key settings were correctly restored - bool settingsMatch = true; - settingsMatch &= imported.CodeText == "Test123"; - settingsMatch &= imported.Parameters.Barcode.BarColor.Equals(Color.Blue); - settingsMatch &= Math.Abs(imported.Parameters.Barcode.XDimension.Point - 2f) < 0.001f; - settingsMatch &= Math.Abs(imported.Parameters.Barcode.Padding.Left.Point - 5f) < 0.001f; - settingsMatch &= imported.Parameters.AutoSizeMode == AutoSizeMode.Interpolation; + Console.WriteLine("FAILED: ImportFromXml returned null."); + return; + } - if (!settingsMatch) - { - Console.WriteLine("FAILED: Imported settings do not match original."); - return; - } + // Generate a barcode image from the imported settings into a memory stream. + using (var imageStream = new MemoryStream()) + { + importedGenerator.Save(imageStream, BarCodeImageFormat.Png); + imageStream.Position = 0; // Reset stream position for reading. - // ------------------------------------------------------------ - // Generate a barcode image from the imported settings into memory - // ------------------------------------------------------------ - using (MemoryStream ms = new MemoryStream()) + // Initialize a barcode reader to verify the generated image. + using (var reader = new BarCodeReader()) { - imported.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for reading + // Provide the image stream to the reader. + reader.SetBarCodeImage(imageStream); + // Configure the reader to attempt decoding all supported types. + reader.BarCodeReadType = DecodeType.AllSupportedTypes; + + // Perform barcode recognition. + var results = reader.ReadBarCodes(); - // ------------------------------------------------------------ - // Decode the barcode from the generated image to verify content - // ------------------------------------------------------------ - using (BarCodeReader reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes)) + // Validate that a barcode was detected and that settings match expectations. + if (results == null || results.Length == 0) { - var results = reader.ReadBarCodes(); - if (results.Length == 0) - { - Console.WriteLine("FAILED: No barcode detected in the generated image."); - return; - } + Console.WriteLine("FAILED: No barcode detected."); + } + else + { + var result = results[0]; + bool codeTextMatch = string.Equals(result.CodeText, "Test123", StringComparison.Ordinal); + bool xDimensionMatch = Math.Abs(importedGenerator.Parameters.Barcode.XDimension.Point - 2f) < 0.001f; - // Ensure the decoded text matches the original code text - bool decodeMatch = true; - foreach (var result in results) + if (codeTextMatch && xDimensionMatch) { - if (string.IsNullOrEmpty(result.CodeText) || result.CodeText != "Test123") - { - decodeMatch = false; - break; - } + Console.WriteLine("PASSED: ImportFromXml restored settings correctly."); } - - if (!decodeMatch) + else { - Console.WriteLine("FAILED: Decoded CodeText does not match original."); - return; + Console.WriteLine("FAILED: Restored settings do not match original."); + Console.WriteLine($"Expected CodeText: Test123, Actual: {result.CodeText}"); + Console.WriteLine($"Expected XDimension: 2, Actual: {importedGenerator.Parameters.Barcode.XDimension.Point}"); } - - // All verification steps passed - Console.WriteLine("SUCCESS: ImportFromXml restored settings and barcode decoded correctly."); } } } - // ------------------------------------------------------------ - // Clean up temporary files (ignore any errors during cleanup) - // ------------------------------------------------------------ - try - { - if (File.Exists(xmlPath)) File.Delete(xmlPath); - if (File.Exists(imagePath)) File.Delete(imagePath); - } - catch - { - // Cleanup failures are non‑critical for the test outcome - } + // Clean up temporary files, ignoring any errors that may occur. + try { if (File.Exists(xmlPath)) File.Delete(xmlPath); } catch { } + try { if (File.Exists(imgPath)) File.Delete(imgPath); } catch { } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/develop-background-service-that-monitors-folder-imports-xml-states-and-processes-pending-barcode-images-automatically.cs b/barcode-recognition-xml-serialization/develop-background-service-that-monitors-folder-imports-xml-states-and-processes-pending-barcode-images-automatically.cs index 4f93508..2127641 100644 --- a/barcode-recognition-xml-serialization/develop-background-service-that-monitors-folder-imports-xml-states-and-processes-pending-barcode-images-automatically.cs +++ b/barcode-recognition-xml-serialization/develop-background-service-that-monitors-folder-imports-xml-states-and-processes-pending-barcode-images-automatically.cs @@ -1,85 +1,109 @@ -// Title: Automatic barcode generation from XML definitions -// Description: Demonstrates a console background service that watches a folder, imports barcode settings from XML files, generates PNG images, and archives processed XML. +// Title: Background Service for Automatic Barcode Generation and Recognition +// Description: Demonstrates monitoring a folder, importing barcode settings from XML, generating images, and reading pending barcode images. +// Category-Description: This example belongs to the Aspose.BarCode folder‑watching and batch processing category. It showcases key API classes such as BarcodeGenerator, BarCodeReader, and their XML import/export capabilities. Typical use cases include automated barcode creation pipelines, scheduled processing of incoming barcode specifications, and bulk recognition of generated images. Developers often need to integrate these operations into background services or CI workflows. // Prompt: Develop a background service that monitors a folder, imports XML states, and processes pending barcode images automatically. -// Tags: barcode, generation, xml, png, file-io, aspose.barcode +// Tags: barcode generation, barcode recognition, xml import, background service, aspose.barcode, code128, png using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Entry point for the barcode generation service. +/// Demonstrates a simple background‑style workflow that creates sample barcodes, +/// exports their configuration to XML, re‑imports the settings to generate processed images, +/// and finally reads all barcode images in the working folder. /// class Program { /// - /// Main method processes XML barcode definitions, generates images, and moves processed files. + /// Entry point of the example. Executes the workflow sequentially. /// - /// Command‑line arguments: [0] input folder, [1] output folder. - static void Main(string[] args) + static void Main() { - // Determine input folder (first argument) or use default "Input" - string inputFolder = args.Length > 0 ? args[0] : "Input"; + // Define and ensure the working folder exists + string workFolder = Path.Combine(Directory.GetCurrentDirectory(), "WorkFolder"); + Directory.CreateDirectory(workFolder); - // Determine output folder for generated images (second argument) or use default "Output" - string outputFolder = args.Length > 1 ? args[1] : "Output"; + // -------------------------------------------------------------------- + // 1. Create sample barcode images and export their generator settings to XML + // -------------------------------------------------------------------- + for (int i = 1; i <= 3; i++) + { + string codeText = $"Sample{i}"; + string imagePath = Path.Combine(workFolder, $"barcode{i}.png"); + string xmlPath = Path.Combine(workFolder, $"barcode{i}.xml"); - // Folder where processed XML files will be moved after successful handling - string processedFolder = Path.Combine(inputFolder, "Processed"); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + // Set unit‑based dimensions for the barcode and the image + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.ImageWidth.Point = 250f; + generator.Parameters.ImageHeight.Point = 100f; - // Validate that the input folder exists; abort if it does not - if (!Directory.Exists(inputFolder)) - { - Console.WriteLine($"Input directory '{inputFolder}' does not exist."); - return; - } + // Save the generated barcode image + generator.Save(imagePath, BarCodeImageFormat.Png); - // Ensure the output and processed folders exist (create if necessary) - Directory.CreateDirectory(outputFolder); - Directory.CreateDirectory(processedFolder); + // Export the generator configuration to an XML file for later reuse + generator.ExportToXml(xmlPath); + } + } - // Retrieve all XML files in the input folder - string[] xmlFiles = Directory.GetFiles(inputFolder, "*.xml"); - if (xmlFiles.Length == 0) + // -------------------------------------------------------------------- + // 2. Process each XML state file: import settings and generate a new image + // -------------------------------------------------------------------- + string[] xmlFiles = Directory.GetFiles(workFolder, "*.xml"); + foreach (string xmlFile in xmlFiles) { - Console.WriteLine("No XML files found to process."); - return; + try + { + // Import generator configuration from the XML file + using (var generator = BarcodeGenerator.ImportFromXml(xmlFile)) + { + // Determine output file name based on the XML file name + string fileName = Path.GetFileNameWithoutExtension(xmlFile); + string outputPath = Path.Combine(workFolder, $"processed_{fileName}.png"); + + // Optionally adjust image size before generation + generator.Parameters.ImageWidth.Point = 300f; + generator.Parameters.ImageHeight.Point = 120f; + + // Generate and save the processed barcode image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Processed XML '{Path.GetFileName(xmlFile)}' -> '{Path.GetFileName(outputPath)}'"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error processing XML '{Path.GetFileName(xmlFile)}': {ex.Message}"); + } } - // Process each XML file individually - foreach (string xmlPath in xmlFiles) + // -------------------------------------------------------------------- + // 3. Scan for pending barcode images and attempt to read them + // -------------------------------------------------------------------- + string[] imageFiles = Directory.GetFiles(workFolder, "*.png"); + foreach (string imageFile in imageFiles) { try { - // Import barcode settings from the XML file using Aspose.BarCode - using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath)) + using (var reader = new BarCodeReader(imageFile)) { - // If import fails, log and continue with next file - if (generator == null) + // Iterate through all detected barcodes in the image + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Failed to import barcode from '{xmlPath}'."); - continue; + Console.WriteLine($"Image '{Path.GetFileName(imageFile)}' - Detected Type: {result.CodeTypeName}, Text: {result.CodeText}"); } - - // Construct output image path (same base name as XML, but with .png extension) - string imageFileName = Path.GetFileNameWithoutExtension(xmlPath) + ".png"; - string imagePath = Path.Combine(outputFolder, imageFileName); - - // Save the generated barcode image to the output folder - generator.Save(imagePath); - Console.WriteLine($"Generated barcode saved to '{imagePath}'."); } - - // After successful generation, move the processed XML to the "Processed" subfolder - string destXmlPath = Path.Combine(processedFolder, Path.GetFileName(xmlPath)); - File.Move(xmlPath, destXmlPath); } catch (Exception ex) { - // Log any errors that occur during processing of the current XML file - Console.WriteLine($"Error processing '{xmlPath}': {ex.Message}"); + Console.WriteLine($"Error reading image '{Path.GetFileName(imageFile)}': {ex.Message}"); } } + + // Program completes here } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/develop-diagnostic-tool-that-compares-original-results-with-those-obtained-after-xml-import-to-ensure-data-integrity.cs b/barcode-recognition-xml-serialization/develop-diagnostic-tool-that-compares-original-results-with-those-obtained-after-xml-import-to-ensure-data-integrity.cs index e705c85..0e01ddd 100644 --- a/barcode-recognition-xml-serialization/develop-diagnostic-tool-that-compares-original-results-with-those-obtained-after-xml-import-to-ensure-data-integrity.cs +++ b/barcode-recognition-xml-serialization/develop-diagnostic-tool-that-compares-original-results-with-those-obtained-after-xml-import-to-ensure-data-integrity.cs @@ -1,7 +1,8 @@ -// Title: Barcode XML Import Integrity Diagnostic -// Description: Demonstrates generating a barcode, exporting its settings to XML, re‑importing them, and comparing the original and imported results to verify data integrity. +// Title: Barcode XML Settings Import Diagnostic +// Description: Demonstrates generating a barcode, exporting its settings to XML, re-importing them, and verifying image integrity. +// Category-Description: This example belongs to the Aspose.BarCode settings management category, illustrating how to use BarcodeGenerator, ExportToXml, and ImportFromXml for preserving barcode configuration. Developers often need to serialize barcode settings for storage or transfer and ensure that reconstituted barcodes remain identical to the originals. The snippet shows typical use cases such as configuration backup, migration, and automated testing of data integrity. // Prompt: Develop a diagnostic tool that compares original results with those obtained after XML import to ensure data integrity. -// Tags: barcode, xml, import, export, integrity, diagnostics, aspose.barcode, code128, png +// Tags: barcode symbology, generation, xml import, integrity check, aspose.barcode, code128, png using System; using System.IO; @@ -11,119 +12,90 @@ using Aspose.Drawing; /// -/// Entry point for the barcode XML import integrity diagnostic example. +/// Demonstrates creating a barcode, exporting its settings to XML, importing them back, +/// and comparing the resulting images to ensure data integrity. /// class Program { /// - /// Generates a barcode, exports its configuration to XML, re‑imports it, and compares the original and imported results. + /// Entry point of the diagnostic tool. /// static void Main() { - // -------------------------------------------------------------------- - // Define file names for the original image, imported image, and XML file. - // -------------------------------------------------------------------- - const string originalImagePath = "original.png"; - const string importedImagePath = "imported.png"; - const string xmlPath = "barcode.xml"; + // Prepare output folder for generated files + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "BarcodeDiagnostic"); + Directory.CreateDirectory(outputDir); - // -------------------------------------------------------------------- - // Sample barcode data: code text and symbology type. - // -------------------------------------------------------------------- - const string codeText = "1234567890"; - BaseEncodeType encodeType = EncodeTypes.Code128; + // Define file paths for original image, imported image, and XML settings + string originalImagePath = Path.Combine(outputDir, "original.png"); + string importedImagePath = Path.Combine(outputDir, "imported.png"); + string xmlPath = Path.Combine(outputDir, "settings.xml"); - // -------------------------------------------------------------------- - // Create the original barcode generator, apply custom visual settings, - // save the image, and export the generator configuration to XML. - // -------------------------------------------------------------------- - using (var generator = new BarcodeGenerator(encodeType, codeText)) + // 1. Create original barcode generator with sample settings + using (var originalGenerator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) { - // Example customizations - generator.Parameters.Barcode.BarColor = Color.Blue; - generator.Parameters.Barcode.XDimension.Point = 2f; - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - - // Save the generated barcode image. - generator.Save(originalImagePath, BarCodeImageFormat.Png); - - // Export the generator's settings to an XML file. - generator.ExportToXml(xmlPath); - } - - // -------------------------------------------------------------------- - // Verify that the XML file was created before attempting import. - // -------------------------------------------------------------------- - if (!File.Exists(xmlPath)) - { - Console.WriteLine("XML file was not created. Exiting."); - return; + // Configure a few barcode parameters + originalGenerator.Parameters.Barcode.XDimension.Point = 2f; + originalGenerator.Parameters.Barcode.BarHeight.Point = 40f; + originalGenerator.Parameters.Barcode.FilledBars = true; + originalGenerator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial"; + originalGenerator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f; + + // Save the original barcode image to PNG + originalGenerator.Save(originalImagePath, BarCodeImageFormat.Png); + + // Export the generator's configuration to an XML file + originalGenerator.ExportToXml(xmlPath); } - // -------------------------------------------------------------------- - // Import a new barcode generator from the previously saved XML. - // -------------------------------------------------------------------- + // 2. Import settings from XML into a new generator instance BarcodeGenerator importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath); if (importedGenerator == null) { - Console.WriteLine("Failed to import generator from XML. Exiting."); + Console.WriteLine("Failed to import barcode settings from XML."); return; } - // -------------------------------------------------------------------- - // Save an image using the imported generator settings. - // -------------------------------------------------------------------- + // Save the barcode generated from the imported settings importedGenerator.Save(importedImagePath, BarCodeImageFormat.Png); - importedGenerator.Dispose(); - - // -------------------------------------------------------------------- - // Compare the original and imported images byte‑by‑byte. - // -------------------------------------------------------------------- - bool imagesEqual = CompareFiles(originalImagePath, importedImagePath); - Console.WriteLine($"Image comparison result: {(imagesEqual ? "Identical" : "Different")}"); - // -------------------------------------------------------------------- - // Compare core properties (symbology type and code text) of the original - // and imported generators to ensure configuration integrity. - // -------------------------------------------------------------------- - using (var originalGen = new BarcodeGenerator(encodeType, codeText)) - using (var importedGen = BarcodeGenerator.ImportFromXml(xmlPath)) + // 3. Compare the two images byte by byte to verify they are identical + bool imagesIdentical = false; + if (File.Exists(originalImagePath) && File.Exists(importedImagePath)) { - bool typeEqual = originalGen.BarcodeType.TypeName == importedGen.BarcodeType.TypeName; - bool textEqual = originalGen.CodeText == importedGen.CodeText; - Console.WriteLine($"Symbology comparison: {(typeEqual ? "Match" : "Mismatch")}"); - Console.WriteLine($"CodeText comparison: {(textEqual ? "Match" : "Mismatch")}"); + byte[] originalBytes = File.ReadAllBytes(originalImagePath); + byte[] importedBytes = File.ReadAllBytes(importedImagePath); + + if (originalBytes.Length == importedBytes.Length) + { + imagesIdentical = true; + for (int i = 0; i < originalBytes.Length; i++) + { + if (originalBytes[i] != importedBytes[i]) + { + imagesIdentical = false; + break; + } + } + } + } + else + { + Console.WriteLine("One of the barcode images was not created."); + return; } - // -------------------------------------------------------------------- - // Clean up temporary files (optional). Uncomment to delete files. - // -------------------------------------------------------------------- - // File.Delete(originalImagePath); - // File.Delete(importedImagePath); - // File.Delete(xmlPath); - } - - // ------------------------------------------------------------------------ - // Helper method to compare two files byte by byte. - // Returns true if files are identical; otherwise false. - // ------------------------------------------------------------------------ - static bool CompareFiles(string path1, string path2) - { - if (!File.Exists(path1) || !File.Exists(path2)) - return false; - - byte[] file1 = File.ReadAllBytes(path1); - byte[] file2 = File.ReadAllBytes(path2); - - if (file1.Length != file2.Length) - return false; - - for (int i = 0; i < file1.Length; i++) + // 4. Output the comparison result to the console + if (imagesIdentical) + { + Console.WriteLine("Success: The barcode image after XML import matches the original."); + } + else { - if (file1[i] != file2[i]) - return false; + Console.WriteLine("Warning: The barcode image after XML import differs from the original."); } - return true; + + // Clean up the imported generator instance + importedGenerator.Dispose(); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/develop-method-that-loops-through-directory-sets-each-image-exports-state-to-xml-and-logs-results.cs b/barcode-recognition-xml-serialization/develop-method-that-loops-through-directory-sets-each-image-exports-state-to-xml-and-logs-results.cs index aaf7eb6..3e807c1 100644 --- a/barcode-recognition-xml-serialization/develop-method-that-loops-through-directory-sets-each-image-exports-state-to-xml-and-logs-results.cs +++ b/barcode-recognition-xml-serialization/develop-method-that-loops-through-directory-sets-each-image-exports-state-to-xml-and-logs-results.cs @@ -1,99 +1,119 @@ -// Title: Export barcode generator state to XML for images in a directory -// Description: Demonstrates looping through a folder of barcode images, creating a generator for each, exporting its configuration to XML, and logging the results. +// Title: Barcode generation, state export, and decoding batch processing +// Description: Demonstrates creating barcode images, exporting generator state to XML, then reading back each image to decode and log results. +// Category-Description: This example belongs to the Aspose.BarCode batch processing category, showcasing how to use BarcodeGenerator for image creation, ExportToXml for persisting generator settings, and BarCodeReader for decoding. Typical use cases include automated barcode workflows, bulk processing, and state persistence for later reuse. Developers often need to generate, store, and later validate barcodes in large volumes. // Prompt: Develop a method that loops through a directory, sets each image, exports state to XML, and logs results. -// Tags: barcode symbology, export, xml, file-io, aspose.barcode +// Tags: barcode generation, barcode decoding, xml export, code128, aspose.barcode, batch processing using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Example program that processes barcode images, creates generators, and exports their state to XML files. +/// Demonstrates batch creation of Code128 barcodes, exporting generator state to XML, +/// and decoding each generated image while logging the process. /// class Program { /// - /// Entry point of the application. Sets up input/output directories and starts processing. + /// Entry point of the example. Generates barcodes, exports their state, decodes them, + /// and writes detailed logs to a file. /// static void Main() { - // Define the folder that contains barcode image files (adjust path as needed) - string inputDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - - // Define the folder where the exported XML files will be saved - string outputDirectory = Path.Combine(Directory.GetCurrentDirectory(), "ExportedXml"); - - // Ensure the output directory exists; create it if it does not - if (!Directory.Exists(outputDirectory)) + // Define the working directory for barcode images and logs. + string workDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(workDir)) { - Directory.CreateDirectory(outputDirectory); + Directory.CreateDirectory(workDir); } - // Process each barcode image and export its generator state to XML - ProcessBarcodes(inputDirectory, outputDirectory); - } + // Initialize a simple log file with a start timestamp. + string logPath = Path.Combine(workDir, "process.log"); + File.WriteAllText(logPath, $"Process started at {DateTime.Now}{Environment.NewLine}"); - /// - /// Loops through image files in , creates a for each, - /// exports its configuration to an XML file in , and logs the outcome. - /// - /// Directory containing barcode image files. - /// Directory where XML files will be saved. - static void ProcessBarcodes(string inputDir, string outputDir) - { - // Verify that the input directory exists before proceeding - if (!Directory.Exists(inputDir)) + // -------------------------------------------------------------------- + // Generate sample barcode images and export their generator state to XML. + // -------------------------------------------------------------------- + for (int i = 1; i <= 5; i++) { - Console.WriteLine($"Input directory does not exist: {inputDir}"); - return; - } + string codeText = $"Sample{i}"; + string imagePath = Path.Combine(workDir, $"barcode{i}.png"); + string xmlPath = Path.Combine(workDir, $"barcode{i}.xml"); - // Retrieve up to 5 PNG files from the input directory (as per example guidelines) - string[] imageFiles = Directory.GetFiles(inputDir, "*.png"); - int maxItems = Math.Min(imageFiles.Length, 5); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + // Configure generator properties. + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.Barcode.BarHeight.Point = 40f; + generator.Parameters.Barcode.FilledBars = false; + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; + generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Helvetica"; + generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f; + generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center; - // Iterate over the selected image files - for (int i = 0; i < maxItems; i++) - { - string imagePath = imageFiles[i]; + // Save the barcode image to disk. + generator.Save(imagePath); + + // Export the current generator configuration to an XML file. + generator.ExportToXml(xmlPath); + } - // Skip the file if it cannot be found (defensive check) - if (!File.Exists(imagePath)) + // Log the successful generation and export. + Log(logPath, $"Generated barcode {i}: {imagePath}, state exported to {xmlPath}"); + } + + // -------------------------------------------------------------------- + // Decode each generated barcode image and log the results. + // -------------------------------------------------------------------- + string[] imageFiles = Directory.GetFiles(workDir, "*.png"); + foreach (string imgFile in imageFiles) + { + if (!File.Exists(imgFile)) { - Console.WriteLine($"File not found, skipping: {imagePath}"); + Log(logPath, $"File not found: {imgFile}"); continue; } try { - // Use the file name (without extension) as the barcode's codetext for demonstration purposes - string codeText = Path.GetFileNameWithoutExtension(imagePath); - - // Create a barcode generator with Code128 symbology and the derived codetext - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + using (var reader = new BarCodeReader(imgFile, DecodeType.Code128)) { - // Optional: customize appearance (example sets the barcode color to blue) - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; - - // Build the full path for the XML output file - string xmlFileName = Path.Combine(outputDir, $"{codeText}.xml"); - - // Export the generator's current state to the XML file - generator.ExportToXml(xmlFileName); + bool found = false; + foreach (var result in reader.ReadBarCodes()) + { + // Log each decoded barcode's type and text. + Log(logPath, $"Decoded from {Path.GetFileName(imgFile)}: Type={result.CodeTypeName}, Text={result.CodeText}"); + found = true; + } - // Log successful processing - Console.WriteLine($"Processed '{imagePath}' -> XML saved as '{xmlFileName}'."); + if (!found) + { + // No barcode detected in the current image. + Log(logPath, $"No barcode detected in {Path.GetFileName(imgFile)}"); + } } } catch (Exception ex) { - // Log any errors that occur during processing of the current file - Console.WriteLine($"Error processing '{imagePath}': {ex.Message}"); + // Log any errors that occur during decoding. + Log(logPath, $"Error processing {Path.GetFileName(imgFile)}: {ex.Message}"); } } - // Indicate that all processing is complete - Console.WriteLine("Processing completed."); + // Final log entry indicating completion. + Log(logPath, $"Process completed at {DateTime.Now}"); + } + + /// + /// Writes a message to both the console and the specified log file with a timestamp. + /// + /// Path to the log file. + /// Message to log. + static void Log(string logFile, string message) + { + Console.WriteLine(message); + File.AppendAllText(logFile, $"{DateTime.Now}: {message}{Environment.NewLine}"); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/develop-utility-that-loads-xml-state-file-sets-corresponding-image-and-outputs-detected-barcode-values.cs b/barcode-recognition-xml-serialization/develop-utility-that-loads-xml-state-file-sets-corresponding-image-and-outputs-detected-barcode-values.cs index 9a3df3b..ae40caa 100644 --- a/barcode-recognition-xml-serialization/develop-utility-that-loads-xml-state-file-sets-corresponding-image-and-outputs-detected-barcode-values.cs +++ b/barcode-recognition-xml-serialization/develop-utility-that-loads-xml-state-file-sets-corresponding-image-and-outputs-detected-barcode-values.cs @@ -1,55 +1,54 @@ -// Title: Barcode detection from XML state file -// Description: Demonstrates loading a barcode reader configuration from an XML file, applying it to an image, and printing detected barcode types and values. +// Title: Load XML state, set image, and read barcodes +// Description: Demonstrates loading a BarCodeReader configuration from an XML state file, assigning an image, and printing detected barcode values. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating how to import a BarCodeReader configuration from XML using BarCodeReader.ImportFromXml, set a barcode image with SetBarCodeImage, and retrieve results via ReadBarCodes. Typical use cases include batch processing of images with predefined settings, automated scanning workflows, and integration into CI pipelines where configuration is stored externally. Developers often need to load saved state, apply it to new images, and extract barcode data programmatically. // Prompt: Develop a utility that loads an XML state file, sets the corresponding image, and outputs detected barcode values. -// Tags: barcode, detection, xml, aspose, console +// Tags: barcode, xml, import, read, aspose.barcode, barcodereader, detection using System; using System.IO; using Aspose.BarCode.BarCodeRecognition; /// -/// Example utility that reads barcode detection settings from an XML state file, -/// applies them to a specified image, and writes detected barcode information to the console. +/// Utility that loads a BarCodeReader configuration from an XML state file, +/// assigns a barcode image, and outputs detected barcode values to the console. /// class Program { /// /// Entry point of the application. - /// Loads the XML configuration, validates input files, performs barcode detection, - /// and outputs each detected barcode's type and value. /// static void Main() { - // Default file names – replace with your own paths or pass as arguments. - string xmlPath = "state.xml"; - string imagePath = "barcode.png"; + // Define the file paths for the XML state file and the barcode image. + const string xmlPath = "state.xml"; + const string imagePath = "barcode.png"; - // Validate XML file existence. + // Ensure the XML state file exists before proceeding. if (!File.Exists(xmlPath)) { Console.WriteLine($"XML state file not found: {xmlPath}"); return; } - // Validate image file existence. + // Ensure the barcode image file exists before proceeding. if (!File.Exists(imagePath)) { - Console.WriteLine($"Image file not found: {imagePath}"); + Console.WriteLine($"Barcode image file not found: {imagePath}"); return; } - // Load reader settings from the XML file. - // ImportFromXml returns a BarCodeReader instance with the imported configuration. + // Load a configured BarCodeReader instance from the XML state file. + // ImportFromXml parses the XML and returns a ready‑to‑use reader. using (BarCodeReader reader = BarCodeReader.ImportFromXml(xmlPath)) { - // Assign the image to be processed. + // Assign the image that will be processed by the reader. reader.SetBarCodeImage(imagePath); - // Perform barcode detection. + // Iterate through all detected barcodes and output their type and text. foreach (var result in reader.ReadBarCodes()) { - // Output detected barcode type and value. - Console.WriteLine($"Type: {result.CodeTypeName}, Value: {result.CodeText}"); + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Detected Text: {result.CodeText}"); } } } diff --git a/barcode-recognition-xml-serialization/export-recognition-state-to-xml-file-after-processing-single-barcode-image.cs b/barcode-recognition-xml-serialization/export-recognition-state-to-xml-file-after-processing-single-barcode-image.cs index b0a42e9..d036b0d 100644 --- a/barcode-recognition-xml-serialization/export-recognition-state-to-xml-file-after-processing-single-barcode-image.cs +++ b/barcode-recognition-xml-serialization/export-recognition-state-to-xml-file-after-processing-single-barcode-image.cs @@ -1,51 +1,72 @@ -// Title: Export Barcode Recognition State to XML -// Description: Demonstrates how to read a barcode image, display detected information, and export the full recognition state to an XML file. +// Title: Export barcode recognition state to XML +// Description: Demonstrates how to read a barcode from an image and export the full recognition state to an XML file. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating the use of BarCodeReader to detect barcodes, retrieve their properties, and serialize the recognition session via ExportToXml. Developers often need to log or audit barcode scans, and this pattern shows how to generate a detailed XML report using key classes like BarCodeReader, DecodeType, and BarcodeGenerator. // Prompt: Export the recognition state to an XML file after processing a single barcode image. -// Tags: barcode, recognition, xml, export, aspose.barcode, c# +// Tags: barcode, recognition, xml, export, aspose.barcode, code128, generation, reading using System; using System.IO; using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Sample program that reads a barcode image, prints detection results, -/// and saves the complete recognition state to an XML file. +/// Example program that generates a sample barcode (if missing), reads it, +/// displays detected information, and exports the complete recognition state to an XML file. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Performs barcode generation (optional), recognition, + /// console output, and XML export of the recognition state. /// static void Main() { - // Path to the barcode image to be processed. - const string imagePath = "barcode.png"; + // Define file names in the current directory + string imagePath = "sample_barcode.png"; + string xmlPath = "recognition_state.xml"; - // Path where the recognition state XML will be saved. - const string xmlOutputPath = "recognition_state.xml"; + // Ensure a barcode image exists; generate one if missing + if (!File.Exists(imagePath)) + { + // Create a barcode generator for Code128 with sample text + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + { + // Save the generated barcode as a PNG file + generator.Save(imagePath, BarCodeImageFormat.Png); + Console.WriteLine($"Generated sample barcode image: {imagePath}"); + } + } - // Verify that the image file exists before attempting to read it. + // Verify the image file exists before processing if (!File.Exists(imagePath)) { - Console.WriteLine($"Error: Image file \"{imagePath}\" not found."); + Console.WriteLine($"Error: Barcode image not found at '{imagePath}'."); return; } - // Create a BarCodeReader for the image, detecting all supported symbologies. - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Create a reader for the image and detect barcodes + using (var reader = new BarCodeReader()) { - // Iterate through all detected barcodes. - foreach (var result in reader.ReadBarCodes()) + // Assign the image to the reader + reader.SetBarCodeImage(imagePath); + + // Use all supported symbologies for detection + reader.BarCodeReadType = DecodeType.AllSupportedTypes; + + // Perform recognition and retrieve results + var results = reader.ReadBarCodes(); + + // Output detected barcodes to console + foreach (var result in results) { - // Output basic information about each detected barcode. Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text: {result.CodeText}"); + Console.WriteLine($"Detected Text: {result.CodeText}"); } - // Export the full recognition state (detected barcodes, settings, metadata) to an XML file. - reader.ExportToXml(xmlOutputPath); - Console.WriteLine($"Recognition state exported to \"{xmlOutputPath}\"."); + // Export the full recognition state to an XML file + reader.ExportToXml(xmlPath); + Console.WriteLine($"Recognition state exported to: {xmlPath}"); } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/implement-checkpoint-functionality-by-exporting-state-to-xml-after-each-successful-barcode-detection.cs b/barcode-recognition-xml-serialization/implement-checkpoint-functionality-by-exporting-state-to-xml-after-each-successful-barcode-detection.cs index 3c492b9..701b48d 100644 --- a/barcode-recognition-xml-serialization/implement-checkpoint-functionality-by-exporting-state-to-xml-after-each-successful-barcode-detection.cs +++ b/barcode-recognition-xml-serialization/implement-checkpoint-functionality-by-exporting-state-to-xml-after-each-successful-barcode-detection.cs @@ -1,68 +1,89 @@ -// Title: Barcode Generation, Detection, and Checkpoint Export -// Description: Generates a Code128 barcode image, reads it, and exports a checkpoint XML after each detection. +// Title: Barcode generation, detection, and checkpoint export example +// Description: Demonstrates creating Code128 barcodes, reading them, and exporting detection state to XML after each successful read. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeReader for detecting them, and the ExportToXml method for checkpointing. Developers often need to generate barcodes, process scanned images, and persist recognition state for auditing or debugging, making this pattern common in inventory and logistics applications. // Prompt: Implement checkpoint functionality by exporting the state to XML after each successful barcode detection. -// Tags: barcode, code128, generation, detection, xml, checkpoint, aspose.barcode +// Tags: barcode generation, barcode recognition, code128, xml export, checkpoint, aspose.barcode using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates creating a barcode, reading it, and saving a checkpoint XML after each detection. +/// Generates sample Code128 barcodes, reads them back, and exports a checkpoint XML file +/// after each successful detection using Aspose.BarCode APIs. /// class Program { /// - /// Entry point of the application. Generates a barcode image, reads it, and exports checkpoints. + /// Entry point of the example. Handles barcode creation, detection, and checkpoint export. /// static void Main() { - // Define the file path for the generated barcode image - string imagePath = "barcode.png"; - - // ------------------------------------------------------------ - // Generate a Code128 barcode and save it to the specified file - // ------------------------------------------------------------ - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Ensure the output folder exists + string imagesFolder = "Barcodes"; + if (!Directory.Exists(imagesFolder)) { - generator.Save(imagePath); + Directory.CreateDirectory(imagesFolder); } - // Verify that the barcode image file was successfully created - if (!File.Exists(imagePath)) - { - Console.WriteLine($"Error: Barcode image not found at '{imagePath}'."); - return; - } + // Sample texts to encode into barcodes + string[] sampleTexts = new string[] { "12345", "ABCDEF", "9876543210" }; - // ------------------------------------------------------------ - // Initialize a barcode reader that supports all barcode types - // ------------------------------------------------------------ - using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Generate barcode images from the sample texts + int index = 0; + foreach (string text in sampleTexts) { - int index = 0; // Counter for detected barcodes - - // Iterate through each detected barcode in the image - foreach (var result in reader.ReadBarCodes()) + string imagePath = Path.Combine(imagesFolder, $"barcode_{index}.png"); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text)) { - // Output detection details to the console - Console.WriteLine($"Detected [{index}]: Type = {result.CodeTypeName}, Text = {result.CodeText}"); + generator.Save(imagePath, BarCodeImageFormat.Png); + } + index++; + } - // Export the current state of the reader to an XML checkpoint file - string checkpointFile = $"checkpoint_{index}.xml"; - reader.ExportToXml(checkpointFile); - Console.WriteLine($"Checkpoint saved to '{checkpointFile}'."); + // Retrieve all generated PNG files for processing + string[] imageFiles = Directory.GetFiles(imagesFolder, "*.png"); + int checkpointCounter = 0; - index++; + // Iterate over each image file and attempt barcode detection + foreach (string file in imageFiles) + { + if (!File.Exists(file)) + { + Console.WriteLine($"File not found: {file}"); + continue; } - // If no barcodes were found, inform the user - if (index == 0) + using (var reader = new BarCodeReader(file, DecodeType.AllSupportedTypes)) { - Console.WriteLine("No barcodes were detected in the image."); + // Read all barcodes present in the current image + foreach (var result in reader.ReadBarCodes()) + { + // Successful detection when CodeText is not null or empty + if (!string.IsNullOrEmpty(result.CodeText)) + { + Console.WriteLine($"Detected Barcode: Type={result.CodeTypeName}, Text={result.CodeText}"); + + // Export the reader's state to an XML checkpoint file + string checkpointPath = $"checkpoint_{checkpointCounter}.xml"; + try + { + reader.ExportToXml(checkpointPath); + Console.WriteLine($"Checkpoint exported to: {checkpointPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to export checkpoint: {ex.Message}"); + } + + checkpointCounter++; + } + } } } + + Console.WriteLine("Processing completed."); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/implement-error-handling-to-catch-exceptions-when-exporttoxml-is-called-without-initializing-reader-with-image.cs b/barcode-recognition-xml-serialization/implement-error-handling-to-catch-exceptions-when-exporttoxml-is-called-without-initializing-reader-with-image.cs index 1c5b9b4..e4d4b19 100644 --- a/barcode-recognition-xml-serialization/implement-error-handling-to-catch-exceptions-when-exporttoxml-is-called-without-initializing-reader-with-image.cs +++ b/barcode-recognition-xml-serialization/implement-error-handling-to-catch-exceptions-when-exporttoxml-is-called-without-initializing-reader-with-image.cs @@ -1,7 +1,8 @@ -// Title: Demonstrate ExportToXml error handling with uninitialized BarCodeReader -// Description: Shows how to catch exceptions when ExportToXml is called before setting an image, then performs successful export after initialization. +// Title: ExportToXml error handling demonstration +// Description: Demonstrates catching exceptions when calling ExportToXml on a BarCodeReader that hasn't been initialized with an image. +// Category-Description: This example belongs to the Aspose.BarCode reading and exporting category, illustrating the use of BarCodeReader and BarcodeGenerator classes to read barcodes and export results to XML. Developers often need to handle missing image scenarios, export data for downstream processing, and ensure robust error handling in barcode automation workflows. // Prompt: Implement error handling to catch exceptions when ExportToXml is called without initializing the reader with an image. -// Tags: barcode symbology, export, xml, barcodereader, barcodegenerator +// Tags: barcode symbology, error handling, export, xml, barcodereader, barcodegenerator using System; using System.IO; @@ -14,72 +15,66 @@ class Program { /// - /// Entry point of the example. + /// Entry point of the example. Shows both failing and successful ExportToXml scenarios. /// static void Main() { - // Define the path for the sample barcode image - string imagePath = "sample.png"; + // Path for the XML file that will be created by ExportToXml. + string xmlPath = "reader_export.xml"; - // Generate a simple Code128 barcode and save it to a file - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // ----------------------------------------------------------------- + // Attempt to export without initializing the reader with an image. + // This should throw an exception which we catch and handle. + // ----------------------------------------------------------------- + try { - generator.Save(imagePath); + using (var reader = new BarCodeReader()) + { + // ExportToXml requires an image; without one it throws. + reader.ExportToXml(xmlPath); + } } - - // Verify that the image file was created successfully - if (!File.Exists(imagePath)) + catch (Exception ex) { - Console.WriteLine("Failed to create the sample barcode image."); - return; + // Expected exception handling. + Console.WriteLine("Caught exception as expected: " + ex.Message); } - // Create a BarCodeReader without initializing it with an image - using (BarCodeReader reader = new BarCodeReader()) - { - // Attempt to export settings to XML without setting an image - try - { - reader.ExportToXml("reader_without_image.xml"); - Console.WriteLine("Export succeeded unexpectedly (no image was set)."); - } - catch (Exception ex) - { - // Expected exception handling - Console.WriteLine("Caught expected exception when exporting without image:"); - Console.WriteLine(ex.Message); - } + // ----------------------------------------------------------------- + // Optional: demonstrate a successful ExportToXml after setting an image. + // ----------------------------------------------------------------- + string barcodeImagePath = "sample.png"; - // Initialize the reader with the generated barcode image - reader.SetBarCodeImage(imagePath); + // Generate a sample barcode image to use for the successful case. + GenerateSampleBarcode(barcodeImagePath); - // Export to XML after proper initialization - try - { - reader.ExportToXml("reader_with_image.xml"); - Console.WriteLine("Export succeeded after initializing the reader with an image."); - } - catch (Exception ex) + try + { + using (var reader = new BarCodeReader(barcodeImagePath)) { - // Unexpected exception handling - Console.WriteLine("Unexpected exception after initializing the reader:"); - Console.WriteLine(ex.Message); + // Now the reader has an image, so ExportToXml succeeds. + reader.ExportToXml(xmlPath); + Console.WriteLine("ExportToXml succeeded after initializing the reader with an image."); } } - - // Clean up generated files (optional) - try + catch (Exception ex) { - if (File.Exists("reader_without_image.xml")) - File.Delete("reader_without_image.xml"); - if (File.Exists("reader_with_image.xml")) - File.Delete("reader_with_image.xml"); - if (File.Exists(imagePath)) - File.Delete(imagePath); + // Unexpected exception handling. + Console.WriteLine("Unexpected error during ExportToXml: " + ex.Message); } - catch + } + + /// + /// Generates a simple Code128 barcode image for demonstration purposes. + /// + /// Path where the barcode image will be saved. + static void GenerateSampleBarcode(string filePath) + { + // Create a barcode generator for Code128 with sample data. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Ignore any cleanup errors + // Save the generated barcode image to the specified file. + generator.Save(filePath); } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/implement-feature-that-encrypts-xml-state-file-after-exporttoxml-to-protect-sensitive-barcode-data.cs b/barcode-recognition-xml-serialization/implement-feature-that-encrypts-xml-state-file-after-exporttoxml-to-protect-sensitive-barcode-data.cs index d955e21..96741dc 100644 --- a/barcode-recognition-xml-serialization/implement-feature-that-encrypts-xml-state-file-after-exporttoxml-to-protect-sensitive-barcode-data.cs +++ b/barcode-recognition-xml-serialization/implement-feature-that-encrypts-xml-state-file-after-exporttoxml-to-protect-sensitive-barcode-data.cs @@ -1,7 +1,8 @@ -// Title: Encrypt barcode state XML after export -// Description: Demonstrates exporting a barcode's state to XML and then encrypting the file to protect sensitive data. +// Title: Encrypt exported barcode XML state file +// Description: Demonstrates exporting a barcode configuration to XML and then encrypting the file to protect sensitive data. +// Category-Description: This example belongs to the Aspose.BarCode configuration management category, showing how to use BarcodeGenerator, ExportToXml, and standard .NET cryptography classes to secure barcode state files. Developers often need to store barcode settings securely for later reuse, requiring encryption of the XML representation. The snippet illustrates typical use cases such as persisting and protecting barcode configurations in enterprise applications. // Prompt: Implement a feature that encrypts the XML state file after ExportToXml to protect sensitive barcode data. -// Tags: barcode symbology, export, xml, encryption, aes, aspose.barcode +// Tags: barcode symbology, export, xml, encryption, aes, aspnet, aspose.barcode using System; using System.IO; @@ -10,64 +11,57 @@ using Aspose.BarCode.Generation; /// -/// Example program that generates a barcode, exports its state to an XML file, -/// and then encrypts that XML file using AES to protect sensitive barcode data. +/// Demonstrates exporting a barcode generator's configuration to XML and encrypting the resulting file. /// class Program { /// - /// Entry point of the application. Performs barcode generation, XML export, - /// AES encryption of the exported file, and cleanup of the plain XML. + /// Entry point. Generates a Code128 barcode, exports its state to XML, encrypts the XML, and cleans up the plaintext file. /// static void Main() { - // Define file paths for the intermediate XML state and the final encrypted output + // Paths for the intermediate XML and the final encrypted file string xmlPath = "barcode_state.xml"; string encryptedPath = "barcode_state.enc"; - // Create a barcode generator for Code128 with sample data and export its state to XML - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Create a barcode generator, configure it, and export its state to an XML file + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Export the barcode properties to an XML file; ExportToXml returns true on success bool exported = generator.ExportToXml(xmlPath); - if (!exported) - { - Console.WriteLine("Failed to export barcode state to XML."); - return; - } + Console.WriteLine($"Exported to XML: {exported}"); } - // Prepare static AES key and IV for demonstration (do NOT use static values in production) + // Prepare a demo AES key and IV (replace with secure values in production) byte[] key = new byte[32]; // 256‑bit key byte[] iv = new byte[16]; // 128‑bit IV for (int i = 0; i < key.Length; i++) key[i] = (byte)(i + 1); for (int i = 0; i < iv.Length; i++) iv[i] = (byte)(i + 1); - // Encrypt the XML file using AES and write the ciphertext to a new file + // Encrypt the XML file using AES and write the ciphertext to the encrypted file path using (Aes aes = Aes.Create()) { aes.Key = key; aes.IV = iv; using (FileStream inputFile = new FileStream(xmlPath, FileMode.Open, FileAccess.Read)) - using (FileStream outputFile = new FileStream(encryptedPath, FileMode.Create, FileAccess.Write)) - using (CryptoStream cryptoStream = new CryptoStream(outputFile, aes.CreateEncryptor(), CryptoStreamMode.Write)) + using (FileStream encryptedFile = new FileStream(encryptedPath, FileMode.Create, FileAccess.Write)) + using (CryptoStream cryptoStream = new CryptoStream(encryptedFile, aes.CreateEncryptor(), CryptoStreamMode.Write)) { - // Copy the plaintext XML data into the CryptoStream, which encrypts it on the fly inputFile.CopyTo(cryptoStream); } } - // Attempt to delete the original plain XML file, leaving only the encrypted version + Console.WriteLine($"Encrypted XML saved to: {encryptedPath}"); + + // Attempt to delete the plain XML file to ensure only the encrypted version remains try { File.Delete(xmlPath); + Console.WriteLine("Plain XML file deleted."); } catch (Exception ex) { - Console.WriteLine($"Could not delete original XML file: {ex.Message}"); + Console.WriteLine($"Failed to delete plain XML: {ex.Message}"); } - - Console.WriteLine($"Barcode state encrypted successfully to '{encryptedPath}'."); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/implement-feature-that-merges-multiple-xml-state-files-into-single-document-summarizing-all-detected-barcodes.cs b/barcode-recognition-xml-serialization/implement-feature-that-merges-multiple-xml-state-files-into-single-document-summarizing-all-detected-barcodes.cs index 1b0da7d..dc307de 100644 --- a/barcode-recognition-xml-serialization/implement-feature-that-merges-multiple-xml-state-files-into-single-document-summarizing-all-detected-barcodes.cs +++ b/barcode-recognition-xml-serialization/implement-feature-that-merges-multiple-xml-state-files-into-single-document-summarizing-all-detected-barcodes.cs @@ -1,82 +1,152 @@ -// Title: Merge multiple barcode state XML files into a single summary document -// Description: Demonstrates importing Aspose.BarCode.BarCodeReader state from several XML files, extracting detected barcodes, and writing a consolidated XML summary. +// Title: Merge Multiple XML State Files into a Single Barcode Summary +// Description: Demonstrates merging several XML state files that contain detected barcode information into one consolidated summary document. +// Category-Description: This example belongs to the Aspose.BarCode file handling category, illustrating how to work with barcode state XML files using standard .NET XML APIs. It shows typical use cases such as aggregating results from multiple scans, generating a unified report, and preparing data for further processing. Developers often need to read, combine, and export barcode metadata, leveraging classes like BarCodeReader, BarCodeGenerator, and XDocument. // Prompt: Implement a feature that merges multiple XML state files into a single document summarizing all detected barcodes. -// Tags: barcode symbology, import, xml, summary, aspose.barcode, csharp +// Tags: barcode symbology, merge, xml, summary, aspose.barcode, file-io using System; using System.Collections.Generic; using System.IO; using System.Xml.Linq; -using Aspose.BarCode.BarCodeRecognition; -using Aspose.BarCode.Generation; /// -/// Program that merges barcode detection results from multiple Aspose.BarCode state XML files into a single summary XML document. +/// Provides a console application that merges multiple XML state files containing barcode information +/// into a single summary XML document. The example creates sample state files, reads them, +/// aggregates the barcode entries, and writes the combined result to disk. /// class Program { /// - /// Entry point. Reads each XML state file, extracts barcode type and text, and writes a consolidated summary. + /// Simple model representing a detected barcode with its type and text. + /// + class BarcodeInfo + { + public string CodeTypeName { get; set; } + public string CodeText { get; set; } + } + + /// + /// Entry point of the application. Generates sample XML state files, merges them, + /// and saves a consolidated summary document. /// static void Main() { - // Define the paths to the XML state files (replace with actual file locations as needed) - string[] xmlFiles = { "state1.xml", "state2.xml", "state3.xml" }; + // Define the folder that will hold the sample XML state files. + string stateFolder = "states"; - // List that will hold the combined barcode type and text pairs from all files - var mergedBarcodes = new List<(string Type, string CodeText)>(); + // Ensure the folder exists. + if (!Directory.Exists(stateFolder)) + { + Directory.CreateDirectory(stateFolder); + } + + // -------------------------------------------------------------------- + // Generate a few sample XML state files. + // In a real scenario these files would already exist on disk. + // -------------------------------------------------------------------- + GenerateSampleStateFile(Path.Combine(stateFolder, "state1.xml"), new[] + { + new BarcodeInfo { CodeTypeName = "Code128", CodeText = "ABC123" }, + new BarcodeInfo { CodeTypeName = "QR", CodeText = "https://example.com" } + }); - // Iterate over each XML file to import its BarCodeReader state - foreach (string xmlPath in xmlFiles) + GenerateSampleStateFile(Path.Combine(stateFolder, "state2.xml"), new[] { - // Verify that the file exists before attempting to import - if (!File.Exists(xmlPath)) + new BarcodeInfo { CodeTypeName = "Code39", CodeText = "CODE39VALUE" }, + new BarcodeInfo { CodeTypeName = "Code128", CodeText = "XYZ789" } + }); + + // -------------------------------------------------------------------- + // Collect all barcode entries from every XML file in the folder. + // -------------------------------------------------------------------- + List allBarcodes = new List(); + string[] xmlFiles = Directory.GetFiles(stateFolder, "*.xml"); + + foreach (string xmlFile in xmlFiles) + { + // Load the XML document safely using a FileStream. + XDocument doc; + using (FileStream fs = new FileStream(xmlFile, FileMode.Open, FileAccess.Read)) { - Console.WriteLine($"Warning: File not found - {xmlPath}"); - continue; + doc = XDocument.Load(fs); } - // Import the BarCodeReader state from the XML file - using (BarCodeReader reader = BarCodeReader.ImportFromXml(xmlPath)) + // Expected XML structure: + // + // + // ... + // ... + // + // ... + // + foreach (XElement barcodeElem in doc.Root.Elements("Barcode")) { - // If the import fails, report and skip to the next file - if (reader == null) - { - Console.WriteLine($"Warning: Failed to import {xmlPath}"); - continue; - } + string typeName = barcodeElem.Element("CodeTypeName")?.Value ?? string.Empty; + string codeText = barcodeElem.Element("CodeText")?.Value ?? string.Empty; - // Read barcodes from the imported state; this populates FoundBarCodes if needed - foreach (var result in reader.ReadBarCodes()) + // Only add entries that have both type and text. + if (!string.IsNullOrEmpty(typeName) && !string.IsNullOrEmpty(codeText)) { - // Add only valid results (non‑null and with a non‑empty CodeText) to the merged list - if (result != null && !string.IsNullOrEmpty(result.CodeText)) - { - mergedBarcodes.Add((result.CodeTypeName, result.CodeText)); - } + allBarcodes.Add(new BarcodeInfo { CodeTypeName = typeName, CodeText = codeText }); } } } - // Build a summary XML document containing all collected barcode information - var summaryDoc = new XDocument( + // -------------------------------------------------------------------- + // Build the summary XML document that contains all collected barcodes. + // -------------------------------------------------------------------- + XDocument summaryDoc = new XDocument( + new XElement("Summary", + new XElement("Barcodes", + // Convert each BarcodeInfo into a element. + new List(CreateBarcodeElements(allBarcodes)) + ) + ) + ); + + // Save the merged summary to a file. + string summaryPath = "merged_summary.xml"; + using (FileStream outStream = new FileStream(summaryPath, FileMode.Create, FileAccess.Write)) + { + summaryDoc.Save(outStream); + } + + Console.WriteLine($"Merged summary saved to '{summaryPath}'. Total barcodes: {allBarcodes.Count}"); + } + + /// + /// Generates a sample XML state file containing the specified barcodes. + /// + /// Full path where the XML file will be created. + /// Array of barcode information to include. + static void GenerateSampleStateFile(string filePath, BarcodeInfo[] barcodes) + { + XDocument doc = new XDocument( new XElement("Barcodes", - // Attribute indicating the total number of barcodes found across all files - new XAttribute("TotalCount", mergedBarcodes.Count), - // Timestamp of when the summary was generated (ISO 8601 format) - new XElement("GeneratedOn", DateTime.UtcNow.ToString("o")), - // Container for individual barcode entries - new XElement("Items", - new List(mergedBarcodes.ConvertAll(bc => - new XElement("BarCode", - new XAttribute("Type", bc.Type), - new XAttribute("CodeText", bc.CodeText))))))); - - // Define the output path for the merged summary XML - string outputPath = "merged_summary.xml"; - - // Save the summary document to disk - summaryDoc.Save(outputPath); - Console.WriteLine($"Merged summary saved to {outputPath}"); + new List(CreateBarcodeElements(barcodes)) + ) + ); + + using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) + { + doc.Save(fs); + } + } + + /// + /// Converts a collection of objects into a sequence of + /// representing individual <Barcode> elements. + /// + /// Enumerable of barcode information. + /// IEnumerable of ready for inclusion in an XML document. + static IEnumerable CreateBarcodeElements(IEnumerable barcodes) + { + foreach (var b in barcodes) + { + yield return new XElement("Barcode", + new XElement("CodeTypeName", b.CodeTypeName), + new XElement("CodeText", b.CodeText) + ); + } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/implement-method-that-aggregates-barcode-results-from-multiple-imported-xml-states-into-single-collection-for-reporting.cs b/barcode-recognition-xml-serialization/implement-method-that-aggregates-barcode-results-from-multiple-imported-xml-states-into-single-collection-for-reporting.cs index a33d50f..2e4e426 100644 --- a/barcode-recognition-xml-serialization/implement-method-that-aggregates-barcode-results-from-multiple-imported-xml-states-into-single-collection-for-reporting.cs +++ b/barcode-recognition-xml-serialization/implement-method-that-aggregates-barcode-results-from-multiple-imported-xml-states-into-single-collection-for-reporting.cs @@ -1,7 +1,8 @@ -// Title: Aggregate barcode results from multiple XML states -// Description: Demonstrates importing barcode generator XML, generating images, recognizing barcodes, and aggregating results for reporting. +// Title: Aggregate barcode results from multiple XML state files +// Description: Demonstrates exporting barcode generators to XML, importing them, and aggregating recognition results for reporting. +// Category-Description: This example belongs to the Aspose.BarCode XML state management category, showcasing how to use BarcodeGenerator.ExportToXml and BarcodeGenerator.ImportFromXml together with BarCodeReader. Developers often need to persist barcode generation settings, share them across services, and later batch‑process the generated barcodes for reporting or analytics. The snippet highlights key classes such as BarcodeGenerator, BarCodeReader, and DecodeType, useful for batch barcode processing scenarios. // Prompt: Implement a method that aggregates barcode results from multiple imported XML states into a single collection for reporting. -// Tags: barcode symbology, aggregation, xml import, aspose.barcode, console output +// Tags: barcode symbology, generation, recognition, xml, aspose.barcode, batch processing using System; using System.Collections.Generic; @@ -12,92 +13,74 @@ using Aspose.Drawing; /// -/// Sample program that creates barcode generators, exports them to XML, -/// imports the XML back, reads the generated barcodes, and aggregates the results. +/// Demonstrates exporting barcode generators to XML, importing them, and aggregating +/// recognition results from the generated images for reporting purposes. /// class Program { /// - /// Entry point of the application. Prepares sample XML states, aggregates barcode results, - /// and writes a simple report to the console. + /// Entry point of the example. Creates sample barcode generators, saves their state + /// to XML files, imports each state, generates barcode images, reads the barcodes, + /// and aggregates the results into a single collection. /// - static void Main() + /// Command‑line arguments (not used). + static void Main(string[] args) { - // Prepare a list to hold the XML streams representing exported barcode generators. - var xmlStreams = new List(); - - // ----- First barcode: Code128 with text "ABC123" ----- - using (var gen1 = new BarcodeGenerator(EncodeTypes.Code128, "ABC123")) + // Define a working directory for temporary XML state files. + string workDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(workDir)) { - // Export the generator configuration to a memory stream as XML. - var ms1 = new MemoryStream(); - gen1.ExportToXml(ms1); - ms1.Position = 0; // Reset stream position for later reading. - xmlStreams.Add(ms1); + Directory.CreateDirectory(workDir); } - // ----- Second barcode: QR with text "Hello World" ----- - using (var gen2 = new BarcodeGenerator(EncodeTypes.QR, "Hello World")) + // Prepare sample barcode definitions to be exported as XML states. + var samples = new List<(BaseEncodeType type, string text, string fileName)> { - // Export the generator configuration to a memory stream as XML. - var ms2 = new MemoryStream(); - gen2.ExportToXml(ms2); - ms2.Position = 0; // Reset stream position for later reading. - xmlStreams.Add(ms2); - } - - // Aggregate barcode results from the imported XML states. - List aggregatedResults = AggregateBarcodeResults(xmlStreams); + (EncodeTypes.Code128, "ABC123", "code128.xml"), + (EncodeTypes.QR, "Hello World", "qr.xml"), + (EncodeTypes.DataMatrix, "DM123", "datamatrix.xml") + }; - // Report the aggregated results to the console. - Console.WriteLine("Aggregated Barcode Results:"); - foreach (var result in aggregatedResults) + // Export each barcode generator's configuration to an individual XML file. + foreach (var sample in samples) { - Console.WriteLine($"Type: {result.CodeTypeName}, CodeText: {result.CodeText}"); - } - - // Clean up streams to release resources. - foreach (var stream in xmlStreams) - { - stream.Dispose(); + string xmlPath = Path.Combine(workDir, sample.fileName); + using (var generator = new BarcodeGenerator(sample.type, sample.text)) + { + generator.ExportToXml(xmlPath); + } } - } - - /// - /// Imports barcode generators from XML streams, generates barcode images, - /// recognizes the barcodes, and aggregates all objects into a single collection. - /// - /// Collection of streams containing exported barcode generator XML. - /// List of objects from all imported states. - static List AggregateBarcodeResults(IEnumerable xmlStreams) - { - var allResults = new List(); - // Process each XML stream individually. - foreach (var xmlStream in xmlStreams) + // Aggregate barcode results from all imported XML states. + var aggregatedResults = new List(); + string[] xmlFiles = Directory.GetFiles(workDir, "*.xml"); + foreach (string xmlFile in xmlFiles) { - // Import the BarcodeGenerator from its XML representation. - using (var generator = BarcodeGenerator.ImportFromXml(xmlStream)) + // Import the generator configuration from the XML file. + using (var generator = BarcodeGenerator.ImportFromXml(xmlFile)) { - // Generate the barcode image in memory. + // Generate the barcode image based on the imported configuration. using (var image = generator.GenerateBarCodeImage()) { - // Recognize the barcode(s) from the generated image. + // Initialize a reader that can decode all supported barcode types. using (var reader = new BarCodeReader(image, DecodeType.AllSupportedTypes)) { - // Read all barcodes found in the image. - BarCodeResult[] results = reader.ReadBarCodes(); - - // Add the results to the aggregated collection, if any were found. - if (results != null) + // Read all barcodes found in the image and add them to the collection. + foreach (var result in reader.ReadBarCodes()) { - allResults.AddRange(results); + aggregatedResults.Add(result); } } } } } - return allResults; + // Simple console reporting of the aggregated results. + Console.WriteLine($"Aggregated {aggregatedResults.Count} barcode result(s) from {xmlFiles.Length} XML state file(s)."); + int index = 1; + foreach (var result in aggregatedResults) + { + Console.WriteLine($"{index++}: Type = {result.CodeTypeName}, Text = {result.CodeText}"); + } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/implement-restartable-barcode-scanning-service-that-saves-its-state-to-xml-and-restores-it-after-crash.cs b/barcode-recognition-xml-serialization/implement-restartable-barcode-scanning-service-that-saves-its-state-to-xml-and-restores-it-after-crash.cs index 9b7fd8c..dcbe8e7 100644 --- a/barcode-recognition-xml-serialization/implement-restartable-barcode-scanning-service-that-saves-its-state-to-xml-and-restores-it-after-crash.cs +++ b/barcode-recognition-xml-serialization/implement-restartable-barcode-scanning-service-that-saves-its-state-to-xml-and-restores-it-after-crash.cs @@ -1,95 +1,144 @@ -// Title: Restartable barcode scanning service with XML state persistence -// Description: Demonstrates generating, reading, and persisting progress of barcode processing so the service can resume after a crash. +// Title: Restartable Barcode Scanning Service with XML State Persistence +// Description: Demonstrates scanning multiple barcode images, outputting results to the console, and persisting processed file information to an XML file so the service can resume after a crash. +// Category-Description: This example belongs to the Aspose.BarCode scanning and state‑management category. It showcases the use of BarcodeGenerator for creating sample barcodes and BarCodeReader for recognizing them, combined with XML handling to store processed file names. Developers building long‑running or fault‑tolerant barcode processing pipelines often need to track progress and recover gracefully, making this pattern a common reference point. // Prompt: Implement a restartable barcode scanning service that saves its state to XML and restores it after a crash. -// Tags: barcode symbology, generation, recognition, xml persistence, restartable service +// Tags: code128, qr, datamatrix, scanning, state, xml, console, barcodegenerator, barcodereader using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Xml.Linq; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that generates barcodes, reads them back, and persists processing state to allow restart after a failure. +/// Provides a console application that generates sample barcode images, +/// scans them, and maintains a persistent XML state file to allow +/// restartable processing after unexpected termination. /// class Program { /// - /// Entry point of the application. Executes the barcode processing loop and manages state persistence. + /// Entry point of the application. Generates sample barcodes if needed, + /// loads previously processed file information, scans remaining images, + /// and updates the XML state after each successful scan. /// static void Main() { - const string stateFile = "state.xml"; + // -------------------------------------------------------------------- + // Prepare folder for sample barcode images + // -------------------------------------------------------------------- + string imagesFolder = "Barcodes"; + Directory.CreateDirectory(imagesFolder); + + // -------------------------------------------------------------------- + // Generate sample barcode images when the folder is empty + // -------------------------------------------------------------------- + string[] sampleFiles = { "code128.png", "qr.png", "datamatrix.png" }; + if (Directory.GetFiles(imagesFolder, "*.png").Length == 0) + { + // Code128 sample + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + { + generator.Save(Path.Combine(imagesFolder, sampleFiles[0])); + } + + // QR code sample + using (var generator = new BarcodeGenerator(EncodeTypes.QR, "QR Sample")) + { + generator.Save(Path.Combine(imagesFolder, sampleFiles[1])); + } + + // DataMatrix sample + using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "DM Sample")) + { + generator.Save(Path.Combine(imagesFolder, sampleFiles[2])); + } + } + + // -------------------------------------------------------------------- + // Load or initialize processing state + // -------------------------------------------------------------------- + string stateFile = "state.xml"; + var processed = new HashSet(StringComparer.OrdinalIgnoreCase); - // Load previously processed indices from the state file (if it exists). - var processed = new HashSet(); if (File.Exists(stateFile)) { try { - var doc = XDocument.Load(stateFile); - // Retrieve each stored index element and add it to the processed set. - foreach (var elem in doc.Root?.Element("ProcessedIndices")?.Elements("Index") ?? Enumerable.Empty()) + XDocument doc = XDocument.Load(stateFile); + foreach (var elem in doc.Root.Element("ProcessedFiles").Elements("File")) { - if (int.TryParse(elem.Value, out int idx)) - processed.Add(idx); + processed.Add(elem.Value); } } catch { - // If the state file is corrupted, discard its contents and start fresh. + // If the state file is corrupted, start with a clean state processed.Clear(); } } - // Sample list of barcode texts to be generated and processed. - var codes = new List - { - "ABC123", - "XYZ789", - "123456", - "HELLO", - "WORLD" - }; + // -------------------------------------------------------------------- + // Scan each barcode image that hasn't been processed yet + // -------------------------------------------------------------------- + string[] imageFiles = Directory.GetFiles(imagesFolder, "*.png"); - // Iterate over each barcode text, skipping those already processed. - for (int i = 0; i < codes.Count; i++) + foreach (string filePath in imageFiles) { - if (processed.Contains(i)) - continue; // Skip index already handled in a previous run. - - string imagePath = $"barcode_{i}.png"; - - // Generate a barcode image for the current text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codes[i])) - { - generator.Save(imagePath); - } + string fileName = Path.GetFileName(filePath); + if (processed.Contains(fileName)) + continue; // Skip already processed files - // Read the generated barcode image and output its details. - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + // Read all supported barcodes from the current image + using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) { foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Index {i}: Type={result.CodeTypeName}, Text={result.CodeText}"); + Console.WriteLine($"File: {fileName} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); } } - // Mark this index as processed and persist the updated state to XML. - processed.Add(i); - var stateDoc = new XDocument( - new XElement("State", - new XElement("ProcessedIndices", - processed.Select(idx => new XElement("Index", idx)) - ) + // Record the file as processed and persist the updated state + processed.Add(fileName); + SaveState(stateFile, processed); + } + + Console.WriteLine("Scanning completed."); + } + + /// + /// Persists the set of processed file names to an XML state file. + /// + /// Path to the XML state file. + /// Collection of processed file names. + static void SaveState(string statePath, HashSet processedFiles) + { + var doc = new XDocument( + new XElement("State", + new XElement("ProcessedFiles", + new List(CreateFileElements(processedFiles)) ) - ); - stateDoc.Save(stateFile); + ) + ); + + // Ensure the state file is written atomically + using (var stream = new FileStream(statePath, FileMode.Create, FileAccess.Write, FileShare.None)) + { + doc.Save(stream); } + } - // All barcode items have been processed successfully. + /// + /// Generates XML elements for each processed file name. + /// + /// Enumerable of file names. + /// IEnumerable of XElement representing each file. + static IEnumerable CreateFileElements(IEnumerable files) + { + foreach (var f in files) + { + yield return new XElement("File", f); + } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/implement-support-for-custom-reader-options-such-as-reading-multiple-barcodes-per-image-and-serialize-them-to-xml.cs b/barcode-recognition-xml-serialization/implement-support-for-custom-reader-options-such-as-reading-multiple-barcodes-per-image-and-serialize-them-to-xml.cs index 72dcf0f..9b8b4e0 100644 --- a/barcode-recognition-xml-serialization/implement-support-for-custom-reader-options-such-as-reading-multiple-barcodes-per-image-and-serialize-them-to-xml.cs +++ b/barcode-recognition-xml-serialization/implement-support-for-custom-reader-options-such-as-reading-multiple-barcodes-per-image-and-serialize-them-to-xml.cs @@ -1,7 +1,8 @@ -// Title: Demonstrate reading multiple barcodes with custom options and XML serialization -// Description: Generates two barcodes, combines them into one image, reads them using custom reader options, and serializes the reader settings to XML. +// Title: Custom Reader Options and XML Serialization Example +// Description: Demonstrates how to configure BarCodeReader with custom options, read multiple barcodes from a combined image, and serialize/deserialize the settings to XML. +// Category-Description: This example belongs to the Aspose.BarCode reading and generation category. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeReader for recognizing multiple symbologies, and the QualitySettings and XML export/import features for persisting custom reader configurations. Developers working with barcode scanning, batch processing, or custom recognition pipelines often need to adjust reader options and reuse them across sessions. // Prompt: Implement support for custom reader options, such as reading multiple barcodes per image, and serialize them to XML. -// Tags: barcode, symbology, multiread, xml, readeroptions, aspose.barcode +// Tags: barcode, symbology, generation, recognition, custom-options, xml, aspose.barcode, aspose.barcode.generation, aspose.barcode.recognition using System; using System.IO; @@ -11,121 +12,118 @@ using Aspose.Drawing.Imaging; /// -/// Example program showing how to generate barcodes, combine them, read with custom options, -/// and serialize/deserialize reader settings to XML. +/// Demonstrates creating two barcodes, combining them into a single image, +/// configuring custom reader options, and persisting those settings to XML. /// class Program { /// - /// Entry point. Generates sample barcodes, combines them, reads using custom options, - /// exports/imports settings to XML, and displays results. + /// Entry point of the example. Generates barcodes, reads them with custom options, + /// and shows how to export and import reader settings via XML. /// static void Main() { - // Prepare temporary paths for output files - string outputDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeDemo"); + // -------------------------------------------------------------------- + // Prepare output directory and file paths + // -------------------------------------------------------------------- + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); Directory.CreateDirectory(outputDir); - string combinedImagePath = Path.Combine(outputDir, "combined.png"); - string xmlSettingsPath = Path.Combine(outputDir, "readerSettings.xml"); - - // Create two sample barcodes (Code128 and QR) in memory streams - MemoryStream barcode1Stream = new MemoryStream(); - MemoryStream barcode2Stream = new MemoryStream(); - - using (var generator1 = new BarcodeGenerator(EncodeTypes.Code128, "ABC123")) + string combinedPath = Path.Combine(outputDir, "combined.png"); + string xmlPath = Path.Combine(outputDir, "readerSettings.xml"); + + // -------------------------------------------------------------------- + // Generate a Code128 barcode and store it in a memory stream + // -------------------------------------------------------------------- + MemoryStream code128Stream = new MemoryStream(); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "CODE128-123")) { - generator1.Save(barcode1Stream, BarCodeImageFormat.Png); + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + generator.Save(code128Stream, BarCodeImageFormat.Png); } - using (var generator2 = new BarcodeGenerator(EncodeTypes.QR, "https://example.com")) + code128Stream.Position = 0; + Bitmap code128Bmp = new Bitmap(code128Stream); + + // -------------------------------------------------------------------- + // Generate a QR code and store it in a memory stream + // -------------------------------------------------------------------- + MemoryStream qrStream = new MemoryStream(); + using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com")) { - generator2.Save(barcode2Stream, BarCodeImageFormat.Png); + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + generator.Save(qrStream, BarCodeImageFormat.Png); } - - // Reset streams to the beginning for reading - barcode1Stream.Position = 0; - barcode2Stream.Position = 0; - - // Load bitmaps from the streams and combine them side‑by‑side - using (var bmp1 = new Bitmap(barcode1Stream)) - using (var bmp2 = new Bitmap(barcode2Stream)) + qrStream.Position = 0; + Bitmap qrBmp = new Bitmap(qrStream); + + // -------------------------------------------------------------------- + // Combine the two barcode images side by side into a single bitmap + // -------------------------------------------------------------------- + int combinedWidth = code128Bmp.Width + qrBmp.Width; + int combinedHeight = Math.Max(code128Bmp.Height, qrBmp.Height); + using (var combinedBmp = new Bitmap(combinedWidth, combinedHeight)) { - int combinedWidth = bmp1.Width + bmp2.Width; - int combinedHeight = Math.Max(bmp1.Height, bmp2.Height); - - using (var combinedBmp = new Bitmap(combinedWidth, combinedHeight)) + using (var graphics = Graphics.FromImage(combinedBmp)) { - using (var graphics = Graphics.FromImage(combinedBmp)) - { - graphics.Clear(Aspose.Drawing.Color.White); - graphics.DrawImage(bmp1, 0, 0, bmp1.Width, bmp1.Height); - graphics.DrawImage(bmp2, bmp1.Width, 0, bmp2.Width, bmp2.Height); - } - - // Save the combined image to disk - combinedBmp.Save(combinedImagePath, ImageFormat.Png); + graphics.Clear(Aspose.Drawing.Color.White); + graphics.DrawImage(code128Bmp, 0, 0, code128Bmp.Width, code128Bmp.Height); + graphics.DrawImage(qrBmp, code128Bmp.Width, 0, qrBmp.Width, qrBmp.Height); } + combinedBmp.Save(combinedPath, ImageFormat.Png); } + // -------------------------------------------------------------------- // Verify that the combined image was created successfully - if (!File.Exists(combinedImagePath)) + // -------------------------------------------------------------------- + if (!File.Exists(combinedPath)) { - Console.WriteLine("Failed to create combined barcode image."); + Console.WriteLine("Failed to create the combined barcode image."); return; } - // ---------- Read multiple barcodes with custom options ---------- - using (var reader = new BarCodeReader()) + // -------------------------------------------------------------------- + // Initialize BarCodeReader with custom quality settings + // -------------------------------------------------------------------- + using (var reader = new BarCodeReader(combinedPath, DecodeType.AllSupportedTypes)) { - // Configure the reader to decode both Code128 and QR symbologies - reader.BarCodeReadType = new MultiDecodeType(DecodeType.Code128, DecodeType.QR); - - // Example custom option: use fast deconvolution for quicker processing + // Enable reading of potentially imperfect barcodes + reader.QualitySettings.AllowIncorrectBarcodes = true; + // Use fast deconvolution for quicker processing reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; - // Assign the combined image as the source for reading - reader.SetBarCodeImage(combinedImagePath); - - // Perform the reading operation and output results + // Read and display all detected barcodes Console.WriteLine("Reading barcodes with custom options:"); foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}"); + Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}"); } - // Export the current reader settings to an XML file - reader.ExportToXml(xmlSettingsPath); + // Export the current reader configuration to an XML file + reader.ExportToXml(xmlPath); } - // Verify that the XML settings file was created - if (!File.Exists(xmlSettingsPath)) - { - Console.WriteLine("Failed to export reader settings to XML."); - return; - } - - // ---------- Import settings from XML and read again ---------- - var importedReader = BarCodeReader.ImportFromXml(xmlSettingsPath); + // -------------------------------------------------------------------- + // Import reader settings from the previously saved XML and read again + // -------------------------------------------------------------------- + var importedReader = BarCodeReader.ImportFromXml(xmlPath); if (importedReader == null) { Console.WriteLine("Failed to import reader settings from XML."); return; } - using (importedReader) + // Assign the same combined image to the imported reader instance + importedReader.SetBarCodeImage(combinedPath); + Console.WriteLine("\nReading barcodes after importing settings from XML:"); + foreach (var result in importedReader.ReadBarCodes()) { - // After importing, the image source must be set again - importedReader.SetBarCodeImage(combinedImagePath); - - Console.WriteLine("Reading barcodes after importing settings from XML:"); - foreach (var result in importedReader.ReadBarCodes()) - { - Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}"); - } + Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}"); } - // Cleanup temporary files (optional) - // File.Delete(combinedImagePath); - // File.Delete(xmlSettingsPath); - // Directory.Delete(outputDir, true); + // -------------------------------------------------------------------- + // Clean up the imported reader instance + // -------------------------------------------------------------------- + importedReader.Dispose(); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/import-saved-xml-state-file-into-new-reader-instance-before-setting-image.cs b/barcode-recognition-xml-serialization/import-saved-xml-state-file-into-new-reader-instance-before-setting-image.cs index 6202125..13af096 100644 --- a/barcode-recognition-xml-serialization/import-saved-xml-state-file-into-new-reader-instance-before-setting-image.cs +++ b/barcode-recognition-xml-serialization/import-saved-xml-state-file-into-new-reader-instance-before-setting-image.cs @@ -1,61 +1,83 @@ -// Title: Import barcode reader settings from XML and decode an image -// Description: Demonstrates loading a saved BarCodeReader configuration from an XML file, then applying it to a new reader instance to decode a barcode image. +// Title: Import XML Settings into BarCodeReader and Read Barcode +// Description: Demonstrates exporting a BarCodeReader configuration to XML, importing it into a new reader instance, and reading a barcode image. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator to create a barcode, BarCodeReader to configure recognition settings, and the ExportToXml/ImportFromXml methods to persist and restore reader state. Developers often need to save recognition configurations for reuse across applications or environments, especially when dealing with batch processing or CI pipelines. // Prompt: Import a saved XML state file into a new reader instance before setting the image. -// Tags: barcode, import, xml, reader, decode, aspose, barcoderecognition +// Tags: code128, import, export, read, png, xml, barcodegenerator, barcodereader using System; using System.IO; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Example program that imports a saved BarCodeReader state from XML and decodes a barcode image. +/// Example program that generates a barcode, saves reader settings to XML, +/// imports those settings into a new reader, and reads the barcode from an image. /// class Program { /// - /// Entry point. Loads XML state, configures the reader, and reads barcodes from an image. + /// Entry point of the example. Executes the barcode generation, settings export, + /// settings import, and barcode reading workflow. /// static void Main() { - // Paths to the XML state file and the barcode image. - string xmlPath = "readerState.xml"; + // Paths for the barcode image and the XML settings file string imagePath = "barcode.png"; + string xmlPath = "readerSettings.xml"; - // Verify that the XML file exists. + // ------------------------------------------------- + // Step 1: Generate a simple barcode image and save it + // ------------------------------------------------- + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + { + // Set visual parameters (optional) + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Save the barcode image to a PNG file + generator.Save(imagePath); + } + + // ------------------------------------------------- + // Step 2: Create a BarCodeReader, configure it, and export its settings to XML + // ------------------------------------------------- + using (var reader = new BarCodeReader(imagePath)) + { + // Example of a quality setting (optional) + reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; + + // Export the current reader configuration to an XML file + reader.ExportToXml(xmlPath); + } + + // ------------------------------------------------- + // Step 3: Import the saved XML state into a new reader instance, + // then set the image before reading barcodes. + // ------------------------------------------------- if (!File.Exists(xmlPath)) { - Console.WriteLine($"XML state file not found: {xmlPath}"); + Console.WriteLine($"XML settings file not found: {xmlPath}"); return; } - // Verify that the image file exists. if (!File.Exists(imagePath)) { Console.WriteLine($"Barcode image file not found: {imagePath}"); return; } - // Create a new BarCodeReader instance. - using (var reader = new BarCodeReader()) + // Import the reader configuration from XML; this returns a new BarCodeReader instance + using (var importedReader = BarCodeReader.ImportFromXml(xmlPath)) { - // Import the saved settings from the XML file. - // This static method applies the imported settings to the current reader instance. - BarCodeReader.ImportFromXml(xmlPath); - - // Optionally set the decode type to all supported types. - reader.BarCodeReadType = DecodeType.AllSupportedTypes; - - // Assign the image to be processed. - reader.SetBarCodeImage(imagePath); + // Assign the image to the imported reader (required before reading) + importedReader.SetBarCodeImage(imagePath); - // Perform recognition and output results. - foreach (var result in reader.ReadBarCodes()) + // Read barcodes from the image and output results + foreach (var result in importedReader.ReadBarCodes()) { - Console.WriteLine($"Type: {result.CodeTypeName}"); - Console.WriteLine($"Text: {result.CodeText}"); - Console.WriteLine($"Confidence: {result.Confidence}"); - Console.WriteLine($"Region: {result.Region.Rectangle}"); - Console.WriteLine(); + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); } } } diff --git a/barcode-recognition-xml-serialization/save-reader-state-to-memory-stream-in-xml-format-for-later-deserialization.cs b/barcode-recognition-xml-serialization/save-reader-state-to-memory-stream-in-xml-format-for-later-deserialization.cs index e7474a9..70d2e45 100644 --- a/barcode-recognition-xml-serialization/save-reader-state-to-memory-stream-in-xml-format-for-later-deserialization.cs +++ b/barcode-recognition-xml-serialization/save-reader-state-to-memory-stream-in-xml-format-for-later-deserialization.cs @@ -1,7 +1,8 @@ -// Title: Export and Import Barcode Reader State via XML -// Description: Demonstrates saving a BarCodeReader's state to an XML memory stream and later restoring it for reuse. +// Title: Save BarCodeReader State to XML MemoryStream +// Description: Demonstrates exporting a BarCodeReader's configuration to an XML memory stream and later importing it for barcode recognition. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator to create a barcode image, BarCodeReader to read it, and the ExportToXml/ImportFromXml methods to serialize and deserialize reader settings. Developers often need to persist reader configurations across sessions or share them between services, making XML serialization a practical approach. // Prompt: Save the reader state to a memory stream in XML format for later deserialization. -// Tags: code128, generation, recognition, xml, memorystream, export, import, aspose.barcode +// Tags: code128, barcode generation, barcode recognition, xml serialization, memory stream, aspose.barcode using System; using System.IO; @@ -10,49 +11,43 @@ using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode, exports the reader state to XML, -/// and then imports the state to verify that recognition still works. +/// Example program that creates a Code128 barcode, exports the reader's state to an XML +/// memory stream, imports it back, and performs barcode recognition using the imported state. /// class Program { /// - /// Entry point of the example. Performs barcode generation, state export, and import. + /// Entry point of the example. Executes the barcode generation, state export/import, + /// and recognition workflow. /// static void Main() { - // Create a simple Code128 barcode and generate its image. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Generate a simple Code128 barcode image. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - using (var barcodeImage = generator.GenerateBarCodeImage()) + using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) { // Initialize a reader for the generated image. using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128)) { - // Perform a read to ensure the reader is initialized and display the result. - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"Original read: {result.CodeText}"); - } - - // Save the reader's state to a memory stream in XML format. + // Export the reader's configuration (state) to an XML memory stream. using (var xmlStream = new MemoryStream()) { reader.ExportToXml(xmlStream); - Console.WriteLine($"Reader state exported to XML (size: {xmlStream.Length} bytes)."); - - // Reset the stream position before deserialization. + // Reset the stream position to the beginning before reading. xmlStream.Position = 0; - // Deserialize the reader state from the XML stream. + // Import a new reader instance from the XML stream. using (var importedReader = BarCodeReader.ImportFromXml(xmlStream)) { - // The imported reader needs the image to perform recognition. + // Assign the same barcode image to the imported reader. importedReader.SetBarCodeImage(barcodeImage); - // Verify that the imported reader works by reading the barcode again. - foreach (var importedResult in importedReader.ReadBarCodes()) + // Perform barcode recognition using the imported reader. + foreach (var result in importedReader.ReadBarCodes()) { - Console.WriteLine($"Imported read: {importedResult.CodeText}"); + Console.WriteLine($"Detected Code Type: {result.CodeType}"); + Console.WriteLine($"Detected Code Text: {result.CodeText}"); } } } diff --git a/barcode-recognition-xml-serialization/serialize-recognition-parameters-like-scan-mode-and-timeout-together-with-results-into-xml-document.cs b/barcode-recognition-xml-serialization/serialize-recognition-parameters-like-scan-mode-and-timeout-together-with-results-into-xml-document.cs index d3f1866..5f5df9f 100644 --- a/barcode-recognition-xml-serialization/serialize-recognition-parameters-like-scan-mode-and-timeout-together-with-results-into-xml-document.cs +++ b/barcode-recognition-xml-serialization/serialize-recognition-parameters-like-scan-mode-and-timeout-together-with-results-into-xml-document.cs @@ -1,89 +1,91 @@ // Title: Serialize barcode recognition parameters and results to XML -// Description: Demonstrates generating a barcode, recognizing it, and saving both recognition parameters and results into an XML file. +// Description: Demonstrates generating a QR barcode, recognizing it, and saving both recognition settings and results into an XML file. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to use BarcodeGenerator, BarCodeReader, and related classes to create barcodes, configure recognition parameters such as timeout and quality, and serialize the output. Developers often need to log or exchange barcode data with metadata, and this pattern provides a reusable approach for XML reporting. // Prompt: Serialize recognition parameters like scan mode and timeout together with results into an XML document. -// Tags: barcode, symbology, code128, recognition, xml, serialization, aspose.barcode, aspose.drawing +// Tags: qr, barcode, generation, recognition, xml, aspose.barcode, aspose.drawing using System; using System.IO; +using System.Linq; using System.Xml.Linq; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Example program that creates a barcode, reads it, and serializes -/// the recognition parameters and results into an XML document. +/// Example program that generates a QR barcode, reads it back, and writes +/// both the recognition parameters and the results to an XML document. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode image, reads it, and writes recognition data to XML. + /// Entry point of the example. Generates a barcode, reads it, and serializes + /// the recognition data to XML. /// static void Main() { - // Paths for the generated barcode image and the output XML - string imagePath = "barcode.png"; - string xmlPath = "barcode_results.xml"; + // Define file paths for the barcode image and the XML output. + string barcodeImagePath = "barcode.png"; + string xmlOutputPath = "barcode_info.xml"; // ------------------------------------------------------------ - // Generate a sample barcode image using Code128 symbology + // Generate a QR barcode and save it as a PNG image. // ------------------------------------------------------------ - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "Hello World")) { - generator.Save(imagePath); + generator.Save(barcodeImagePath, BarCodeImageFormat.Png); } - // Verify that the image was created successfully - if (!File.Exists(imagePath)) + // Verify that the barcode image was successfully created. + if (!File.Exists(barcodeImagePath)) { - Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); + Console.WriteLine("Failed to create barcode image."); return; } // ------------------------------------------------------------ - // Create a BarCodeReader to recognize the barcode from the image + // Set up a BarCodeReader to recognize the barcode from the image. // ------------------------------------------------------------ - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + using (BarCodeReader reader = new BarCodeReader(barcodeImagePath, DecodeType.AllSupportedTypes)) { - // Set recognition parameters - reader.Timeout = 5000; // timeout in milliseconds - reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; + // Configure recognition parameters: timeout (milliseconds) and quality preset. + reader.Timeout = 5000; // 5 seconds + reader.QualitySettings = QualitySettings.HighQuality; - // Perform recognition and obtain all detected barcodes + // Perform the recognition and obtain all detected results. BarCodeResult[] results = reader.ReadBarCodes(); - // -------------------------------------------------------- - // Build XML document containing both parameters and results - // -------------------------------------------------------- - var doc = new XDocument( - new XElement("BarCodeRecognition", - new XElement("Parameters", + // ------------------------------------------------------------ + // Build an XML document that includes both the parameters used + // for recognition and the details of each recognized barcode. + // ------------------------------------------------------------ + XDocument doc = new XDocument( + new XElement("BarCodeInfo", + new XElement("RecognitionParameters", new XElement("Timeout", reader.Timeout), - new XElement("Deconvolution", reader.QualitySettings.Deconvolution.ToString()) + new XElement("QualityPreset", "HighQuality") ), new XElement("Results", - from r in results + from result in results select new XElement("Result", - new XElement("CodeText", r.CodeText ?? string.Empty), - new XElement("CodeType", r.CodeTypeName ?? string.Empty), - new XElement("ReadingQuality", r.ReadingQuality), - new XElement("Angle", r.Region.Angle), + new XElement("CodeText", result.CodeText ?? string.Empty), + new XElement("CodeType", result.CodeTypeName ?? string.Empty), + new XElement("ReadingQuality", result.ReadingQuality), + new XElement("Angle", result.Region.Angle), new XElement("Region", - new XElement("X", r.Region.Rectangle.X), - new XElement("Y", r.Region.Rectangle.Y), - new XElement("Width", r.Region.Rectangle.Width), - new XElement("Height", r.Region.Rectangle.Height) + new XElement("X", result.Region.Rectangle.X), + new XElement("Y", result.Region.Rectangle.Y), + new XElement("Width", result.Region.Rectangle.Width), + new XElement("Height", result.Region.Rectangle.Height) ) ) ) ) ); - // Save the XML document to the specified file - doc.Save(xmlPath); + // Save the constructed XML document to the specified file. + doc.Save(xmlOutputPath); + Console.WriteLine("Recognition data saved to: " + xmlOutputPath); } - - Console.WriteLine($"Recognition data saved to '{xmlPath}'."); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/show-how-to-read-xml-state-from-memorystream-and-continue-processing-without-reloading-image-file.cs b/barcode-recognition-xml-serialization/show-how-to-read-xml-state-from-memorystream-and-continue-processing-without-reloading-image-file.cs index 4d40615..353856c 100644 --- a/barcode-recognition-xml-serialization/show-how-to-read-xml-state-from-memorystream-and-continue-processing-without-reloading-image-file.cs +++ b/barcode-recognition-xml-serialization/show-how-to-read-xml-state-from-memorystream-and-continue-processing-without-reloading-image-file.cs @@ -1,7 +1,8 @@ -// Title: Read XML State from MemoryStream and Continue Barcode Processing -// Description: Demonstrates exporting a BarCodeReader's state to XML stored in a MemoryStream, then importing it to continue recognition without reloading the image file. +// Title: Read barcode XML state from MemoryStream and continue processing +// Description: Demonstrates exporting a BarCodeReader state to XML in memory and importing it back without reloading the image file. +// Category-Description: This example belongs to the Aspose.BarCode state management category, showing how to use BarCodeReader.ExportToXml and BarCodeReader.ImportFromXml. Developers often need to persist reader settings or share state across processes, and these APIs let you serialize and deserialize the reader while reusing the same bitmap image. // Prompt: Show how to read an XML state from a MemoryStream and continue processing without reloading the image file. -// Tags: qr, barcode, xml, memorystream, import, export, aspose.barcode +// Tags: barcode, xml, memorystream, import, export, read, code128, aspose.barcode using System; using System.IO; @@ -10,54 +11,53 @@ using Aspose.Drawing; /// -/// Example program that generates a QR code, exports the reader state to XML, -/// imports it back, and continues processing without reloading the image file. +/// Demonstrates exporting and importing BarCodeReader state using XML in memory. /// class Program { /// - /// Entry point of the example. Generates a QR barcode, reads it, exports the reader state, - /// imports the state, and reads the barcode again using the same bitmap. + /// Entry point. Generates a barcode, reads it, exports the reader state to XML, imports it back, and reads again without reloading the image. /// static void Main() { - // Generate a QR barcode and keep it in a memory stream - using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello World")) + // Generate a barcode image in memory using Code128 symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345")) { + // Store the generated image in a MemoryStream. using (var imgStream = new MemoryStream()) { - // Save the generated barcode image to the memory stream in PNG format generator.Save(imgStream, BarCodeImageFormat.Png); - imgStream.Position = 0; // Reset stream position for reading + imgStream.Position = 0; // Reset stream position for reading. - // Load the image from the memory stream into a bitmap + // Load the image from the stream into a Bitmap object. using (var bitmap = new Bitmap(imgStream)) { - // First recognition pass using a BarCodeReader - using (var reader = new BarCodeReader(bitmap, DecodeType.QR)) + // First recognition pass using a BarCodeReader. + using (var reader = new BarCodeReader(bitmap, DecodeType.Code128)) { foreach (var result in reader.ReadBarCodes()) { Console.WriteLine($"First read: {result.CodeText}"); } - // Export the reader's internal state to XML stored in a memory stream + // Export the current reader state to an XML MemoryStream. using (var xmlStream = new MemoryStream()) { reader.ExportToXml(xmlStream); - xmlStream.Position = 0; // Reset for reading the XML + xmlStream.Position = 0; // Reset for import. - // Import a new BarCodeReader instance from the XML state - var importedReader = BarCodeReader.ImportFromXml(xmlStream); - using (importedReader) + // Import a new BarCodeReader from the XML state without reloading the image file. + using (var importedReader = BarCodeReader.ImportFromXml(xmlStream)) { - // Reassign the same bitmap (the image itself is not stored in the XML) + // Assign the same bitmap image to the imported reader. importedReader.SetBarCodeImage(bitmap); + // Optionally set the decode type (default is AllSupportedTypes). + importedReader.BarCodeReadType = DecodeType.Code128; - // Continue processing without reloading the image file + // Second recognition pass using the imported reader. foreach (var result in importedReader.ReadBarCodes()) { - Console.WriteLine($"After import read: {result.CodeText}"); + Console.WriteLine($"After import: {result.CodeText}"); } } } diff --git a/barcode-recognition-xml-serialization/write-code-to-decrypt-encrypted-xml-state-file-before-calling-importfromxml-for-barcode-recognition-restoration.cs b/barcode-recognition-xml-serialization/write-code-to-decrypt-encrypted-xml-state-file-before-calling-importfromxml-for-barcode-recognition-restoration.cs index 82398b4..a4f8551 100644 --- a/barcode-recognition-xml-serialization/write-code-to-decrypt-encrypted-xml-state-file-before-calling-importfromxml-for-barcode-recognition-restoration.cs +++ b/barcode-recognition-xml-serialization/write-code-to-decrypt-encrypted-xml-state-file-before-calling-importfromxml-for-barcode-recognition-restoration.cs @@ -1,125 +1,153 @@ -// Title: Decrypt Encrypted XML State for Barcode Recognition -// Description: Demonstrates decrypting an AES‑encrypted XML state file and importing it into Aspose.BarCode to restore barcode recognition settings. +// Title: Decrypt encrypted XML state file for barcode reader restoration +// Description: Demonstrates decrypting an AES‑encrypted XML state file and importing it to restore barcode recognition settings. +// Category-Description: This example belongs to the Aspose.BarCode state management category, showing how to export, encrypt, decrypt, and import barcode reader settings using ExportToXml, ImportFromXml, and AES encryption. Developers often need to persist and protect reader configurations for later reuse, especially in secure or distributed environments. // Prompt: Write code to decrypt an encrypted XML state file before calling ImportFromXml for barcode recognition restoration. -// Tags: barcode, decryption, xml, import, aspose.barcode, aes +// Tags: barcode symbology, encryption, importfromxml, aesencryption, barcoderecognition using System; using System.IO; using System.Security.Cryptography; -using System.Text; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Example program that decrypts an encrypted XML state file and restores barcode recognition settings using Aspose.BarCode. +/// Demonstrates exporting a barcode reader state to XML, encrypting the XML, +/// decrypting it back into memory, and restoring the reader settings using +/// BarCodeReader.ImportFromXml. The example uses AES‑128 for encryption +/// and shows how to reuse the same barcode image with the restored settings. /// class Program { - // Sample AES key (32 bytes) and IV (16 bytes) for encryption/decryption. - private static readonly byte[] AesKey = Encoding.UTF8.GetBytes("0123456789ABCDEF0123456789ABCDEF"); - private static readonly byte[] AesIv = Encoding.UTF8.GetBytes("ABCDEF0123456789"); - /// - /// Entry point. Ensures an encrypted state file exists, decrypts it, imports settings, generates a matching barcode, and reads it. + /// Encrypts the specified input file using AES and writes the ciphertext to the output file. + /// This method is for demonstration purposes only; a fixed key/IV is used. /// - static void Main() + /// Path to the plaintext file. + /// Path where the encrypted file will be created. + /// AES key (16 bytes for AES‑128). + /// AES initialization vector (16 bytes). + private static void EncryptFile(string inputPath, string outputPath, byte[] key, byte[] iv) { - const string encryptedFilePath = "encrypted_state.bin"; - - // Ensure an encrypted state file exists. If not, create one from a sample barcode. - if (!File.Exists(encryptedFilePath)) + using (var aes = Aes.Create()) { - CreateEncryptedStateFile(encryptedFilePath); + aes.Key = key; + aes.IV = iv; + + using (var inputFile = new FileStream(inputPath, FileMode.Open, FileAccess.Read)) + using (var outputFile = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + using (var cryptoStream = new CryptoStream(outputFile, aes.CreateEncryptor(), CryptoStreamMode.Write)) + { + // Copy plaintext into the crypto stream to produce encrypted output. + inputFile.CopyTo(cryptoStream); + } } + } - // Decrypt the XML state. - byte[] decryptedXml = DecryptFile(encryptedFilePath, AesKey, AesIv); + /// + /// Decrypts an AES‑encrypted file and returns its contents in a . + /// + /// Path to the encrypted file. + /// AES key used for decryption. + /// AES initialization vector used for decryption. + /// A memory stream containing the decrypted XML data. + private static MemoryStream DecryptToMemoryStream(string encryptedPath, byte[] key, byte[] iv) + { + var memoryStream = new MemoryStream(); - // Import the settings into a BarCodeReader instance. - using (var xmlStream = new MemoryStream(decryptedXml)) - using (var reader = BarCodeReader.ImportFromXml(xmlStream)) + using (var aes = Aes.Create()) { - if (reader == null) - { - Console.WriteLine("Failed to import settings from XML."); - return; - } + aes.Key = key; + aes.IV = iv; - // Generate a barcode image that matches the imported settings. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) - using (var barcodeImage = generator.GenerateBarCodeImage()) + using (var encryptedFile = new FileStream(encryptedPath, FileMode.Open, FileAccess.Read)) + using (var cryptoStream = new CryptoStream(encryptedFile, aes.CreateDecryptor(), CryptoStreamMode.Read)) { - // Assign the image to the reader. - reader.SetBarCodeImage(barcodeImage); - - // Perform recognition and output results. - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"BarCode Type: {result.CodeTypeName}"); - Console.WriteLine($"BarCode CodeText: {result.CodeText}"); - } + // Copy decrypted bytes into the memory stream. + cryptoStream.CopyTo(memoryStream); } } + + // Reset the stream position so it can be read from the beginning. + memoryStream.Position = 0; + return memoryStream; } - // Creates an encrypted XML state file from a sample barcode's settings. - private static void CreateEncryptedStateFile(string filePath) + /// + /// Entry point of the example. Generates a barcode, exports its reader state, + /// encrypts the state XML, decrypts it, and restores the reader settings for + /// barcode recognition. + /// + static void Main() { - // Generate a sample barcode and export its settings to XML. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) - using (var xmlMemory = new MemoryStream()) - { - generator.ExportToXml(xmlMemory); - byte[] xmlBytes = xmlMemory.ToArray(); - - // Encrypt the XML bytes. - byte[] encryptedBytes = Encrypt(xmlBytes, AesKey, AesIv); + // -------------------------------------------------------------------- + // Define file paths used throughout the example. + // -------------------------------------------------------------------- + const string barcodePath = "barcode.png"; + const string xmlPath = "state.xml"; + const string encryptedPath = "state.enc"; - // Write encrypted data to file. - File.WriteAllBytes(filePath, encryptedBytes); + // -------------------------------------------------------------------- + // Prepare a fixed AES‑128 key and IV (for demo only; use secure keys in production). + // -------------------------------------------------------------------- + byte[] key = new byte[16]; + byte[] iv = new byte[16]; + for (int i = 0; i < 16; i++) + { + key[i] = (byte)i; + iv[i] = (byte)(16 - i); } - } - // Encrypts plain data using AES-CBC with PKCS7 padding. - private static byte[] Encrypt(byte[] plainData, byte[] key, byte[] iv) - { - using (Aes aes = Aes.Create()) + // -------------------------------------------------------------------- + // 1. Generate a sample barcode image (Code128 with value "123456"). + // -------------------------------------------------------------------- + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - aes.Key = key; - aes.IV = iv; - aes.Mode = CipherMode.CBC; - aes.Padding = PaddingMode.PKCS7; + generator.Save(barcodePath); + } - using (ICryptoTransform encryptor = aes.CreateEncryptor()) - using (var ms = new MemoryStream()) - using (var cryptoStream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) + // -------------------------------------------------------------------- + // 2. Create a reader, assign the image, and perform an initial read. + // -------------------------------------------------------------------- + using (var reader = new BarCodeReader(barcodePath, DecodeType.AllSupportedTypes)) + { + foreach (var result in reader.ReadBarCodes()) { - cryptoStream.Write(plainData, 0, plainData.Length); - cryptoStream.FlushFinalBlock(); - return ms.ToArray(); + Console.WriteLine($"[Initial] Type: {result.CodeTypeName}, Text: {result.CodeText}"); } + + // 3. Export the reader's configuration and state to an XML file. + reader.ExportToXml(xmlPath); } - } - // Decrypts the entire file content using AES-CBC with PKCS7 padding. - private static byte[] DecryptFile(string filePath, byte[] key, byte[] iv) - { - byte[] cipherData = File.ReadAllBytes(filePath); - using (Aes aes = Aes.Create()) + // -------------------------------------------------------------------- + // 4. Encrypt the exported XML state file using the fixed key/IV. + // -------------------------------------------------------------------- + if (File.Exists(xmlPath)) { - aes.Key = key; - aes.IV = iv; - aes.Mode = CipherMode.CBC; - aes.Padding = PaddingMode.PKCS7; + EncryptFile(xmlPath, encryptedPath, key, iv); + } + else + { + Console.WriteLine("Exported XML file not found."); + return; + } - using (ICryptoTransform decryptor = aes.CreateDecryptor()) - using (var ms = new MemoryStream(cipherData)) - using (var cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) - using (var resultStream = new MemoryStream()) + // -------------------------------------------------------------------- + // 5. Decrypt the encrypted XML back into a memory stream. + // -------------------------------------------------------------------- + using (var decryptedStream = DecryptToMemoryStream(encryptedPath, key, iv)) + { + // 6. Import the reader settings from the decrypted XML stream. + using (var importedReader = BarCodeReader.ImportFromXml(decryptedStream)) { - cryptoStream.CopyTo(resultStream); - return resultStream.ToArray(); + // 7. Assign the same barcode image to the imported reader. + importedReader.SetBarCodeImage(barcodePath); + + // 8. Perform barcode recognition using the restored settings. + foreach (var result in importedReader.ReadBarCodes()) + { + Console.WriteLine($"[Restored] Type: {result.CodeTypeName}, Text: {result.CodeText}"); + } } } } diff --git a/barcode-recognition-xml-serialization/write-code-to-handle-importfromxml-errors-when-required-barcode-image-has-not-been-provided-via-setbarcodeimage.cs b/barcode-recognition-xml-serialization/write-code-to-handle-importfromxml-errors-when-required-barcode-image-has-not-been-provided-via-setbarcodeimage.cs index 2a6f671..06693d0 100644 --- a/barcode-recognition-xml-serialization/write-code-to-handle-importfromxml-errors-when-required-barcode-image-has-not-been-provided-via-setbarcodeimage.cs +++ b/barcode-recognition-xml-serialization/write-code-to-handle-importfromxml-errors-when-required-barcode-image-has-not-been-provided-via-setbarcodeimage.cs @@ -1,69 +1,119 @@ -// Title: ImportFromXml Error Handling for Missing Barcode Image -// Description: Demonstrates how to catch and report errors when ImportFromXml expects a barcode image that hasn't been supplied via SetBarCodeImage. +// Title: Demonstrate handling ImportFromXml errors when barcode image is missing +// Description: Shows how to catch errors from ImportFromXml and recover by loading the required barcode image via SetBarCodeImage. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, illustrating the use of BarcodeGenerator, BarCodeReader, and related classes. Developers often need to export generator settings to XML, import them later, and handle cases where the barcode image is not yet available, requiring explicit image loading before decoding. The snippet provides a typical error‑handling pattern for such scenarios. // Prompt: Write code to handle ImportFromXml errors when the required barcode image has not been provided via SetBarCodeImage. -// Tags: barcode symbology, import, xml, error handling, aspose.barcode, setbarcodeimage +// Tags: barcode generation, barcode recognition, importfromxml, setbarcodeimage, error handling, code128, png using System; using System.IO; -using Aspose.BarCode.Generation; using Aspose.BarCode; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Example program that imports barcode settings from an XML file and handles -/// errors related to missing barcode images required by the configuration. +/// Example program that demonstrates how to handle ImportFromXml errors +/// when the required barcode image has not been provided via SetBarCodeImage. /// class Program { /// - /// Entry point of the application. Imports barcode settings from XML, - /// attempts to generate the barcode, and provides detailed error messages - /// when the required image is not supplied via SetBarCodeImage. + /// Entry point of the example. Generates a barcode, exports settings to XML, + /// attempts to import those settings without an image, handles the resulting error, + /// and finally reads the barcode after loading the correct image. /// static void Main() { - // Path to the XML configuration file. - const string xmlPath = "barcodeConfig.xml"; + // Paths for temporary files + string imagePath = "sample_barcode.png"; + string xmlPath = "generator_settings.xml"; - // Verify that the XML file exists before attempting import. - if (!File.Exists(xmlPath)) + // ------------------------------------------------- + // Step 1: Generate a barcode image and export its settings to XML + // ------------------------------------------------- + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - Console.WriteLine($"XML configuration file not found: {xmlPath}"); - return; + // Save the barcode image to a PNG file + generator.Save(imagePath, BarCodeImageFormat.Png); + + // Export generator settings to XML for later import + generator.ExportToXml(xmlPath); } + // ------------------------------------------------- + // Step 2: Import generator settings from XML (simulating a scenario where + // the barcode image is not yet provided to the reader) + // ------------------------------------------------- + BarcodeGenerator importedGenerator; try { - // Import barcode generator settings from the XML file. - using (var generator = BarcodeGenerator.ImportFromXml(xmlPath)) - { - // Attempt to generate and save the barcode image. - // If the XML expects an external image (e.g., for a complex barcode) and it was not provided, - // an exception may be thrown here. The outer catch block will handle it. - generator.Save("output.png"); - Console.WriteLine("Barcode image generated successfully: output.png"); - } + importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to import generator from XML: {ex.Message}"); + return; } - catch (BarCodeException ex) + + // ------------------------------------------------- + // Step 3: Attempt to read the barcode without setting the image. + // This will raise an exception because the reader has no valid image. + // ------------------------------------------------- + // Create a dummy 1x1 bitmap just to satisfy the constructor. + using (var dummyBitmap = new Bitmap(1, 1)) + using (var reader = new BarCodeReader(dummyBitmap, DecodeType.Code128)) { - // Specific handling for missing barcode image errors. - // The exception message typically mentions SetBarCodeImage or missing image data. - if (ex.Message.Contains("SetBarCodeImage", StringComparison.OrdinalIgnoreCase) || - ex.Message.Contains("image", StringComparison.OrdinalIgnoreCase)) + try { - Console.WriteLine("Error: The imported XML requires a barcode image that was not provided via SetBarCodeImage."); - Console.WriteLine("Please ensure the XML includes a valid image reference or provide the image programmatically."); + // This call will fail because the dummy image does not contain a barcode. + var results = reader.ReadBarCodes(); + + // If no exception, but no results, treat it as missing image. + if (results.Length == 0) + { + throw new BarCodeException("No barcode detected – likely because a proper image was not set."); + } } - else + catch (BarCodeException ex) { - // General barcode-related errors. - Console.WriteLine($"BarCodeException: {ex.Message}"); + Console.WriteLine($"Reader error (expected): {ex.Message}"); + Console.WriteLine("Loading the required barcode image via SetBarCodeImage..."); + + // ------------------------------------------------- + // Step 4: Load the actual barcode image and set it. + // ------------------------------------------------- + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Barcode image file not found: {imagePath}"); + return; + } + + using (var barcodeImage = (Bitmap)Image.FromFile(imagePath)) + { + // Provide the correct image to the reader + reader.SetBarCodeImage(barcodeImage); + + // Now attempt to read again + var finalResults = reader.ReadBarCodes(); + foreach (var result in finalResults) + { + Console.WriteLine($"Detected Barcode Type: {result.CodeType}"); + Console.WriteLine($"Detected CodeText: {result.CodeText}"); + } + } } } - catch (Exception ex) + + // Clean up temporary files (optional) + try + { + if (File.Exists(imagePath)) File.Delete(imagePath); + if (File.Exists(xmlPath)) File.Delete(xmlPath); + } + catch { - // Fallback for any other unexpected errors. - Console.WriteLine($"Unexpected error: {ex.Message}"); + // Ignored – cleanup failure should not affect program flow } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/write-code-to-validate-that-imported-xml-state-contains-expected-barcode-symbology-before-processing-results.cs b/barcode-recognition-xml-serialization/write-code-to-validate-that-imported-xml-state-contains-expected-barcode-symbology-before-processing-results.cs index 3cb9c3f..a723d5a 100644 --- a/barcode-recognition-xml-serialization/write-code-to-validate-that-imported-xml-state-contains-expected-barcode-symbology-before-processing-results.cs +++ b/barcode-recognition-xml-serialization/write-code-to-validate-that-imported-xml-state-contains-expected-barcode-symbology-before-processing-results.cs @@ -1,7 +1,8 @@ // Title: Validate barcode symbology from imported XML state -// Description: Demonstrates how to import a barcode generator from an XML file, verify that its symbology matches the expected type, and then generate an image if validation succeeds. +// Description: Demonstrates how to load a barcode generator state from XML and verify that it uses the expected symbology before further processing. +// Category-Description: This example belongs to the Aspose.BarCode generation and validation category. It shows how to use BarcodeGenerator.ImportFromXml, access the BarcodeType property, and perform symbology checks. Typical use cases include validating saved barcode configurations, ensuring compatibility before rendering, and preventing processing of unexpected barcode types. Developers often need to read saved states, compare symbology, and conditionally generate images. // Prompt: Write code to validate that an imported XML state contains the expected barcode symbology before processing results. -// Tags: barcode symbology, validation, xml import, aspose.barcode, csharp +// Tags: barcode, symbology, validation, import, xml, generation, aspose.barcode using System; using System.IO; @@ -9,45 +10,60 @@ using Aspose.BarCode.Generation; /// -/// Example program that validates the barcode symbology defined in an imported XML state before generating the barcode image. +/// Example program that validates the barcode symbology stored in an imported XML state +/// before generating the barcode image. /// class Program { /// - /// Entry point of the program. Performs validation of the barcode symbology and generates an image if the validation passes. + /// Entry point of the application. + /// Loads a barcode generator from an XML file, checks its symbology, + /// and generates an image only if the symbology matches the expected value. /// static void Main() { - // Expected symbology name (e.g., "Code128") - const string expectedSymbology = "Code128"; + // Path to the XML file that contains the barcode generator state. + string xmlPath = "barcode_state.xml"; - // Path to the XML file that contains the barcode state - const string xmlPath = "barcode_state.xml"; + // Expected symbology name (e.g., "Code128", "QR", "DataMatrix"). + string expectedSymbology = "Code128"; - // Verify that the XML file exists before attempting import + // Verify that the XML file exists before attempting import. if (!File.Exists(xmlPath)) { Console.WriteLine($"Error: XML file not found at '{xmlPath}'."); return; } - // Import the barcode generator from the XML state - using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath)) + try { - // Retrieve the actual symbology type name from the imported generator - string actualSymbology = generator.BarcodeType.TypeName; - - // Compare with the expected symbology (case‑insensitive) - if (!string.Equals(actualSymbology, expectedSymbology, StringComparison.OrdinalIgnoreCase)) + // Import the barcode generator state from the XML file. + using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath)) { - Console.WriteLine($"Warning: Expected symbology '{expectedSymbology}' but found '{actualSymbology}'. Processing aborted."); - return; - } + // Retrieve the actual symbology of the imported generator. + string actualSymbology = generator.BarcodeType.TypeName; + + // Compare the actual symbology with the expected value (case‑insensitive). + if (string.Equals(actualSymbology, expectedSymbology, StringComparison.OrdinalIgnoreCase)) + { + Console.WriteLine($"Symbology validation succeeded: '{actualSymbology}'."); - // Symbology matches – proceed with barcode processing (e.g., generate and save an image) - const string outputImage = "validated_barcode.png"; - generator.Save(outputImage); - Console.WriteLine($"Barcode symbology validated as '{actualSymbology}'. Image saved to '{outputImage}'."); + // Proceed with further processing, e.g., generate and save the barcode image. + string outputImage = "generated_barcode.png"; + generator.Save(outputImage); + Console.WriteLine($"Barcode image saved to '{outputImage}'."); + } + else + { + // Symbology does not match; skip further processing. + Console.WriteLine($"Warning: Expected symbology '{expectedSymbology}' but found '{actualSymbology}'. Skipping processing."); + } + } + } + catch (Exception ex) + { + // Handle any errors that occur during import or processing. + Console.WriteLine($"Exception occurred: {ex.Message}"); } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/write-function-that-converts-reader-results-into-json-object-after-importing-xml-state-for-apis.cs b/barcode-recognition-xml-serialization/write-function-that-converts-reader-results-into-json-object-after-importing-xml-state-for-apis.cs index 429274e..8ac8f4f 100644 --- a/barcode-recognition-xml-serialization/write-function-that-converts-reader-results-into-json-object-after-importing-xml-state-for-apis.cs +++ b/barcode-recognition-xml-serialization/write-function-that-converts-reader-results-into-json-object-after-importing-xml-state-for-apis.cs @@ -1,10 +1,10 @@ -// Title: Convert BarCodeReader results to JSON after importing XML state -// Description: Demonstrates generating a barcode, exporting the reader state to XML, importing it back, reading barcodes, and converting the results to a JSON document. +// Title: Convert BarCodeReader results to JSON after XML state import +// Description: Demonstrates exporting a BarCodeReader configuration to XML, importing it back, and converting the read results into a formatted JSON string. +// Category-Description: This example belongs to the Aspose.BarCode reading and serialization category. It shows how to use BarCodeReader.ExportToXml, BarCodeReader.ImportFromXml, and related classes to persist reader settings, then deserialize barcode detection results into JSON using System.Text.Json. Developers often need to store reader configurations and share scan results across services, making this pattern useful for API integrations and data pipelines. // Prompt: Write a function that converts reader results into a JSON object after importing the XML state for APIs. -// Tags: barcode symbology, generation, recognition, json, xml, aspose.barcode +// Tags: barcode symbology, reading, json serialization, export xml, import xml, aspose.barcode using System; -using System.Collections.Generic; using System.IO; using System.Text.Json; using Aspose.BarCode.Generation; @@ -12,62 +12,56 @@ using Aspose.Drawing; /// -/// Sample program that shows how to generate a barcode, export/import the reader state via XML, -/// read the barcode, and serialize the results to JSON. +/// Example program that generates a barcode (if needed), exports a configuration to XML, +/// imports it back, reads barcodes from an image, and outputs the results as JSON. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Performs the barcode generation, state export/import, reading, and JSON conversion. /// static void Main() { - // Define temporary file paths for the barcode image and the exported XML state + // Define file paths for the barcode image and the exported reader state. string imagePath = "barcode.png"; - string xmlPath = "reader_state.xml"; + string readerXmlPath = "reader_state.xml"; - // ------------------------------------------------------------ - // Generate a sample Code128 barcode and save it to a PNG file - // ------------------------------------------------------------ - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Ensure a barcode image exists; generate one if it does not. + if (!File.Exists(imagePath)) { - generator.Save(imagePath); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + { + generator.Save(imagePath); + } } - // ------------------------------------------------------------ - // Create a BarCodeReader, export its internal state to XML, then dispose it - // ------------------------------------------------------------ - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Create a reader for the image and export its configuration (excluding the image) to XML. + using (var initialReader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - reader.ExportToXml(xmlPath); + // Export the reader's settings to an XML file. + initialReader.ExportToXml(readerXmlPath); } - // ------------------------------------------------------------ - // Import the previously saved reader state from the XML file - // ------------------------------------------------------------ - BarCodeReader importedReader = BarCodeReader.ImportFromXml(xmlPath); + // Import a new reader instance from the previously saved XML configuration. + BarCodeReader importedReader = BarCodeReader.ImportFromXml(readerXmlPath); if (importedReader == null) { Console.WriteLine("Failed to import BarCodeReader from XML."); return; } - // Assign the image source to the imported reader (required after import) + // Reassign the image source to the imported reader (required after import). importedReader.SetBarCodeImage(imagePath); - // ------------------------------------------------------------ - // Read barcodes from the image using the imported reader - // ------------------------------------------------------------ + // Perform barcode detection on the image. BarCodeResult[] results = importedReader.ReadBarCodes(); - // ------------------------------------------------------------ - // Convert each BarCodeResult into an anonymous object suitable for JSON serialization - // ------------------------------------------------------------ - var jsonItems = new List(); + // Prepare a list of anonymous objects representing the results for JSON serialization. + var jsonObjects = new System.Collections.Generic.List(); foreach (var result in results) { var region = result.Region.Rectangle; - jsonItems.Add(new + jsonObjects.Add(new { CodeText = result.CodeText, CodeTypeName = result.CodeTypeName, @@ -84,26 +78,11 @@ static void Main() }); } - // ------------------------------------------------------------ - // Serialize the list of result objects to a formatted JSON string - // ------------------------------------------------------------ - string json = JsonSerializer.Serialize(jsonItems, new JsonSerializerOptions { WriteIndented = true }); + // Serialize the result list to a formatted JSON string. + string json = JsonSerializer.Serialize(jsonObjects, new JsonSerializerOptions { WriteIndented = true }); Console.WriteLine(json); - // ------------------------------------------------------------ - // Clean up resources - // ------------------------------------------------------------ + // Release resources held by the imported reader. importedReader.Dispose(); - - // Optionally delete temporary files (comment out if you want to keep them) - try - { - if (File.Exists(imagePath)) File.Delete(imagePath); - if (File.Exists(xmlPath)) File.Delete(xmlPath); - } - catch - { - // Ignore any cleanup errors - } } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/write-script-that-loads-xml-state-sets-image-and-re-exports-state-to-file.cs b/barcode-recognition-xml-serialization/write-script-that-loads-xml-state-sets-image-and-re-exports-state-to-file.cs index c5765e6..9ab00d6 100644 --- a/barcode-recognition-xml-serialization/write-script-that-loads-xml-state-sets-image-and-re-exports-state-to-file.cs +++ b/barcode-recognition-xml-serialization/write-script-that-loads-xml-state-sets-image-and-re-exports-state-to-file.cs @@ -1,54 +1,56 @@ -// Title: Load barcode generator state from XML, generate image, and export state -// Description: Demonstrates loading a barcode generator configuration from an XML file, generating a barcode image, and exporting the (potentially modified) state back to XML. +// Title: Load barcode generator XML state, modify, and re-export +// Description: Demonstrates loading a barcode generator's state from an XML file, updating properties, generating an image, and saving the modified state. +// Category-Description: This example belongs to the Aspose.BarCode state management category, illustrating how to import and export barcode generator settings using XML. It showcases key API classes such as BarcodeGenerator, its Parameters, and image handling via Aspose.Drawing. Developers use these patterns to persist barcode configurations, apply batch modifications, and regenerate barcodes programmatically. // Prompt: Write a script that loads an XML state, sets an image, and re‑exports the state to a file. -// Tags: barcode symbology, generation, xml, export, aspose.barcode, aspose.drawing +// Tags: barcode, xml, state, import, export, image, generation, aspose.barcode using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Example program that loads a barcode generator state from an XML file, -/// generates a barcode image, and re‑exports the (possibly modified) state to a new XML file. +/// Demonstrates loading a barcode generator state from XML, modifying it, generating an image, and exporting the updated state. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Performs the load‑modify‑save workflow. /// static void Main() { - // Path to the input XML file containing the barcode generator state + // Paths for input XML, generated image, and output XML string inputXmlPath = "barcode_state.xml"; - - // Path where the generated barcode image will be saved string outputImagePath = "generated_barcode.png"; + string outputXmlPath = "modified_barcode_state.xml"; - // Path where the (potentially modified) generator state will be exported - string outputXmlPath = "exported_state.xml"; - - // Verify that the input XML file exists before proceeding + // Ensure the input XML file exists before proceeding if (!File.Exists(inputXmlPath)) { Console.WriteLine($"Input XML file not found: {inputXmlPath}"); return; } - // Load the BarcodeGenerator configuration from the XML file + // Import the barcode generator configuration from the XML state file using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(inputXmlPath)) { - // Generate the barcode image based on the loaded configuration + // Example modification: set a light gray background and change the code text + generator.Parameters.BackColor = Color.LightGray; + generator.CodeText = "ModifiedCode123"; + + // Generate the barcode image based on the modified settings using (var bitmap = generator.GenerateBarCodeImage()) { // Save the generated image as a PNG file bitmap.Save(outputImagePath, ImageFormat.Png); + Console.WriteLine($"Barcode image saved to: {outputImagePath}"); } - // Export the current generator state back to an XML file + // Export the modified generator state back to an XML file generator.ExportToXml(outputXmlPath); + Console.WriteLine($"Modified barcode state exported to: {outputXmlPath}"); } - - Console.WriteLine("Barcode image generated and state exported successfully."); } } \ No newline at end of file diff --git a/barcode-recognition-xml-serialization/write-wrapper-class-that-abstracts-xml-serialization-of-reader-and-reassigns-image-from-folder.cs b/barcode-recognition-xml-serialization/write-wrapper-class-that-abstracts-xml-serialization-of-reader-and-reassigns-image-from-folder.cs index b097742..f15fcde 100644 --- a/barcode-recognition-xml-serialization/write-wrapper-class-that-abstracts-xml-serialization-of-reader-and-reassigns-image-from-folder.cs +++ b/barcode-recognition-xml-serialization/write-wrapper-class-that-abstracts-xml-serialization-of-reader-and-reassigns-image-from-folder.cs @@ -1,133 +1,130 @@ -// Title: XML Serialization Wrapper for Aspose BarCode Reader -// Description: Demonstrates a wrapper that loads BarCodeReader settings from XML and assigns an image from a folder for barcode detection. +// Title: XML Serialization Wrapper for BarCodeReader +// Description: Demonstrates how to load BarCodeReader settings from an XML file, reassign an image from a folder, and read barcodes. +// Category-Description: This example belongs to the Aspose.BarCode reading and configuration category, showcasing the use of BarCodeReader, BarcodeGenerator, and XML import/export APIs. Developers often need to persist reader settings, reuse them across sessions, and dynamically assign images for batch processing. The snippet serves as a searchable reference for implementing wrapper classes that handle serialization and image management. // Prompt: Write a wrapper class that abstracts XML serialization of the reader and reassigns the image from a folder. -// Tags: barcode, xml-serialization, reader, wrapper, aspose.barcode +// Tags: barcode, xml-serialization, reader, image-assignment, aspnet, aspose.barcode, csharp using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; -namespace AsposeBarcodeWrapperDemo +/// +/// Wrapper for Aspose.BarCode that abstracts XML +/// serialization of the reader settings and reassigns the barcode image from a folder. +/// +class BarcodeReaderWrapper : IDisposable { + private BarCodeReader _reader; + + /// + /// Loads reader configuration from an XML file exported previously by . + /// + /// Full path to the XML configuration file. + public void LoadFromXml(string xmlPath) + { + if (!File.Exists(xmlPath)) + throw new FileNotFoundException($"XML file not found: {xmlPath}"); + + // Import reader settings from XML + _reader = BarCodeReader.ImportFromXml(xmlPath); + } + /// - /// Wrapper class that abstracts XML serialization of and handles image assignment. + /// Assigns the first image matching from + /// to the internal instance. /// - public class BarcodeReaderWrapper : IDisposable + /// Folder containing barcode images. + /// Search pattern for image files (default: "*.png"). + public void SetImageFromFolder(string folderPath, string searchPattern = "*.png") { - // Underlying Aspose BarCodeReader instance. - private readonly BarCodeReader _reader; + if (!Directory.Exists(folderPath)) + throw new DirectoryNotFoundException($"Folder not found: {folderPath}"); - /// - /// Initializes a new instance of the class. - /// - public BarcodeReaderWrapper() + string[] files = Directory.GetFiles(folderPath, searchPattern); + if (files.Length == 0) + throw new FileNotFoundException($"No image files matching pattern '{searchPattern}' found in folder."); + + // Load the first image and assign it to the reader + using (Bitmap bmp = new Bitmap(files[0])) { - // Create a fresh BarCodeReader. - _reader = new BarCodeReader(); + _reader.SetBarCodeImage(bmp); } + } - /// - /// Loads reader configuration from an XML file. - /// - /// Full path to the XML settings file. - public void LoadFromXml(string xmlPath) - { - // Verify that the XML file exists before attempting to load. - if (!File.Exists(xmlPath)) - throw new FileNotFoundException($"XML file not found: {xmlPath}"); + /// + /// Reads barcodes from the assigned image, writing up to results to the console. + /// + /// Maximum number of barcode results to display (default: 5). + public void ReadBarcodes(int maxCount = 5) + { + if (_reader == null) + throw new InvalidOperationException("BarCodeReader is not initialized. Call LoadFromXml first."); - // Apply the XML settings to the current reader instance. - BarCodeReader.ImportFromXml(xmlPath); + int count = 0; + foreach (var result in _reader.ReadBarCodes()) + { + Console.WriteLine($"Detected Type: {result.CodeTypeName}, Text: {result.CodeText}"); + count++; + if (count >= maxCount) + break; } - /// - /// Assigns an image file to the reader for barcode detection. - /// - /// Full path to the barcode image file. - public void SetImage(string imagePath) - { - // Ensure the image file exists. - if (!File.Exists(imagePath)) - throw new FileNotFoundException($"Image file not found: {imagePath}"); + if (count == 0) + Console.WriteLine("No barcodes detected."); + } - // Set the image for the reader. - _reader.SetBarCodeImage(imagePath); - } + /// + /// Disposes the underlying instance. + /// + public void Dispose() + { + _reader?.Dispose(); + } +} - /// - /// Reads barcodes from the assigned image and writes their type and text to the console. - /// - /// Maximum number of barcodes to process. Defaults to . - public void ReadBarcodes(int maxCount = int.MaxValue) +/// +/// Demonstrates generation of a barcode image, exporting reader settings to XML, +/// and using to reload settings and read the barcode. +/// +class Program +{ + static void Main() + { + // Prepare directory and file paths + string baseDir = Directory.GetCurrentDirectory(); + string imageFolder = Path.Combine(baseDir, "Barcodes"); + string imagePath = Path.Combine(imageFolder, "sample.png"); + string xmlPath = Path.Combine(baseDir, "reader.xml"); + + // Ensure the image folder exists + if (!Directory.Exists(imageFolder)) + Directory.CreateDirectory(imageFolder); + + // 1. Generate a sample barcode image and save it as PNG + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Retrieve all barcode results from the image. - var results = _reader.ReadBarCodes(); - int count = 0; - - // Iterate through results, respecting the maxCount limit. - foreach (var result in results) - { - if (count >= maxCount) - break; - - Console.WriteLine($"Detected Type: {result.CodeTypeName}, CodeText: {result.CodeText}"); - count++; - } + generator.Save(imagePath, BarCodeImageFormat.Png); } - /// - /// Releases resources used by the underlying . - /// - public void Dispose() + // 2. Create a BarCodeReader for the generated image and export its settings to XML + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - _reader?.Dispose(); + reader.ExportToXml(xmlPath); } - } - class Program - { - /// - /// Entry point of the demo application. Generates a barcode, exports its settings to XML, - /// then uses to load the settings, assign the image, - /// and read detected barcodes. - /// - static void Main() + // 3. Use the wrapper to load settings from XML, reassign the image from the folder, and read barcodes + using (var wrapper = new BarcodeReaderWrapper()) { - // Define the folder that will contain the generated barcode image and XML settings. - string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - string imagePath = Path.Combine(folderPath, "sample.png"); - string xmlPath = Path.Combine(folderPath, "sampleSettings.xml"); - - // Ensure the target folder exists. - if (!Directory.Exists(folderPath)) - Directory.CreateDirectory(folderPath); - - // Step 1: Generate a sample barcode image and export its configuration to XML. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) - { - // Save the barcode image to the file system. - generator.Save(imagePath); - - // Export the generator's settings to an XML file. - generator.ExportToXml(xmlPath); - } - - // Step 2: Use the wrapper to load settings, assign the image, and read barcodes. - using (var wrapper = new BarcodeReaderWrapper()) - { - // Load reader configuration from the previously exported XML. - wrapper.LoadFromXml(xmlPath); - - // Assign the generated barcode image to the reader. - wrapper.SetImage(imagePath); - - // Read and display up to three detected barcodes. - wrapper.ReadBarcodes(maxCount: 3); - } - - // Indicate that processing has finished. - Console.WriteLine("Processing completed."); + wrapper.LoadFromXml(xmlPath); + wrapper.SetImageFromFolder(imageFolder, "*.png"); + wrapper.ReadBarcodes(3); } + + // Optional cleanup (commented out) + // File.Delete(imagePath); + // File.Delete(xmlPath); + // Directory.Delete(imageFolder); } } \ No newline at end of file